[Dbix-class] Populating Instance With Column's Defaults

Peter Rabbitson rabbit+dbic at rabbit.us
Wed Feb 9 21:08:22 GMT 2011


Skye Shaw wrote:
> 2011/2/8 Peter Rabbitson <rabbit+dbic at rabbit.us>:
>> Skye Shaw wrote:
>>> Is it possible to have DBIC populate a newly created instance with the
>>> underlying table's defaults when a value isn't provided?
>> The reason is that having every insert be followed by a select is...
>> how shall I put it, insane?!
> 
> Insane implementations shouldn't disqualify very sane ideas.

I simply answered your question:

...Is it possible to have DBIC populate a newly created instance with
the *underlying table's defaults*...

which I apparently misunderstood.

> An ORM should know the details of the tables and columns its mapping.
> Particularly in cases where the user actually specifies this
> information within the ORM's method calls:
> 
> __PACKAGE__->add_columns(
>      active => {
>        data_type => 'tinyint',
>        default_value => 1
>      }
> )
> 

Oh I see. You are assuming default_value is a well-defined attribute
that always contains something that makes sense in perl-land. However
it is simply an advisory value used exclusively by deploy(), and hence
can contain weird stuff like \'current_timestamp()', or something even
more esoteric. Even the plain scalar values can not be trusted, as
already existing schemas can very well contain garbage (courtesy of
botches DBIx::Class::Schema::Loader runs), since this field has never
been expected to be authoritative. Hence overloading the existing
attribute with new meaning would be unwise.

> 
>> What you want is the (admittedly misnamed)
>> http://search.cpan.org/~abraxxa/DBIx-Class-0.08127/lib/DBIx/Class/Row.pm#discard_changes_%28$attrs?%29
> 
> Well, what I want is $db->resultset('Account')->create/new to respect
> the underlying table's defaults.

This is something you can do today with DBIx::Class::DynamicDefault,
with the odd quirk that your values will need to be returned by a
coderef (due to the implementation and scope of this module).

> If an account table has an attribute named active that defaults to 1,
> I would expect that, when using an ORM, newly instantiated
> -nevertheless persisted- instances of the Account class would default
> to 1 too. Not the opposite. IMHO the current behavior is broken.

Bottom line - 'default_value' has a confusing name, sorry about that :)



More information about the DBIx-Class mailing list