[CDBI] Why does CDBI not populate the object on insert

Michael G Schwern schwern at pobox.com
Thu Mar 5 22:15:40 GMT 2009


Edward J. Sabol wrote:
>> This list is pretty quiet these days. I'm looking at some old code and
>> feeling a bit rusty with CDBI and wondering about something. My guess
>> is I've just forgot the reasoning here:
>>
>> If I do:
>>
>>     my $artist = Artist->insert({ name => 'Artist Name' });
>>
>> then $artist->name doesn't exist yet in the object. That means, of
>> course, that $artist->name must do another fetch of the database.

Well, keep in mind that it's not *another* fetch of the database as no fetch
should have been done by that point unless it's to get the auto incremented
primary key which is cheap.

You're right, though, that it could have just cached the inserted data, but...


>> I suppose there could be times when "name" comes back out of the
>> database different than it went in, but most of the time not. Just
>> seems a bit inefficient.
> 
> That's exactly the reason. Triggers (both the database kind and possibly the
> CDBI kind) might change the record values after it is inserted into the
> database. The primary key columns should be intact, I believe, but the other
> columns are flushed and all "essential" columns reloaded upon access.

Exactly right.  Don't forget about defaults and truncation by type.  For
example, DECIMAL(6,2) or CHAR(2).  It's more common than you'd think.

You can mitigate the problem by not using lazy loading, just set all columns
to "All", then you just have the one select.

To turn it off entirely, you can override the create trigger.  A hack, but a
simpler hack than rewriting _insert().  It might be worth making it a
configurable option.


-- 
package Outer::Space;  use Test::More tests => 9;



More information about the ClassDBI mailing list