Wednesday, March 21, 2012

Overriding insert in DBIx::Class

Sometimes when working with DBIX::Class whenever you create a record
in a table, you want to create another record in a corresponding
table. Are you going to go and sift through your code base looking for
all code that writes to the table? Not when you can change your schema
class to handle the action for you.

In order to do this we can override the insert method. This example is
taken from DBIx::Class::Manual::Cookbook :

sub insert {
  my ( $self, @args ) = @_;
  $self->create_related ('cds', \%initial_cd_data );
  return $self;

You see above that next::method is called and then a record is
inserted in a related field. Be aware that you need to call
next::method before you call create so that you write the original
call before making the new one.


  1. Personally I'd use a Moose after method modifier

  2. Put it where? Should I use a transaction?

  3. This code should go into the schema module for whichever table needs to do the extra write. The example above performs a transaction for each database insert. However, you can lump them together in the same transaction if you use DBIx::Class::Storage::TxnScopeGuard as is stated in the docs after the first insert override example.

  4. Hmmm... Wouldn't a trigger be easier?

    1. Sure, you can handle this with a trigger. It really depends where this kind of thing is traditionally handled within the organization.