Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl DBIx::Class - Default Values when using new()?

When using the new() method on a DBIx::Class ResultSource to create a (potentially temporary) variable, it doesn't seem to populate attributes with the default values specified in the DBIC schema (which we have specified for creating tables from that schema).

Currently, we are creating one default value for one such class (the first case where this was a problem) with

sub new {
  my $class = shift;
  my $self = $class->next::method(@_);
  $self->queue('DEFAULT_QUEUE_VAL') unless $self->queue();
  return $self;
}

in that class (i.e., the attribute queue=>DEFAULT_QUEUE_VAL). However, longer term, we have several DBIC classes that have various default values, and we'd like to avoid replicating the above logic for all the various cases.

Are there any CPAN modules/plugins available to do this? We didn't see any in our (admittedly cursory) search of CPAN.

Edit: fixed some garbage in the code sample; turns out I cp'd from out-of-date code.

like image 691
Carl Avatar asked Nov 05 '22 17:11

Carl


1 Answers

It looks like there is no DBIC component for this, you can do it with a small mod to your existing code though:

sub new {
  my $class = shift;
  my $self = $class->next::method(@_);
  foreach my $col ($self->result_source->columns) {
    my $default = $self->result_source->column_info($col)->{default_value};
    $self->$col($default) if($default && !defined $self->$col());
  return $self;
}

As it's this straight forward, there's not much point for a component.

like image 183
castaway Avatar answered Nov 15 '22 07:11

castaway