开发者

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/pl开发者_如何转开发ugins 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.


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.


isn't your code calling queue() as a class method instead of an object method? did you mean

$new->queue('DEFAULT_QUEUE_VAL') unless $new->queue();

?

edit - sorry, just re-read the question, and presume that's just a typo

a thought - if the default value is in the SQL schema, then do you need to set it in the object as well? if you pass through NULL (undef) you'll get the default value in the table, and to reflect that in the object set the subclassed new() method to re-read the db row (->discard_changes() will do it i think?)


Another approach would be to have a 'saved' field in the database which you mark when you have saved it. you can use views to distinguish between saved objects and new ones.

This approach will be slower but allow you to pick up DATETIME or other DB specific defaults that the answer above may have problems with.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜