[Dbix-class] Functionality in PK::Auto

Will Hawes (bytemark) info at whawes.co.uk
Thu Oct 12 18:47:21 CEST 2006


I have a Catalyst action which (simplified) does something along the 
lines of:

# $obj->id is the sole primary column, type int, auto increment
my $obj = $rs->create( $c->request->parameters );

When editing an existing record (e.g. $c->request->parameters == { id => 
1, name => 'existing_record' }), the record is updated and a call to 
$obj->id returns "1" in this case.

When creating a new record, e.g. $c->request->parameters == ({ id => '', 
name => 'new_record' }), a new record is added to the database, but the 
call to $obj->id returns an empty string rather than the new primary key 
value.

The reason is that DBIx::Class::PK::Auto::insert() appears not to 
retrieve the last insert id if supplied with anything other than undef 
for one or more primary key columns. In this case "id" contains an empty 
string, so PK::Auto does not try to look up the new value.

The workaround is trivial, i.e. manually delete empty string from any 
request parameter corresponding to an auto incrementing column, but I 
have a couple of thoughts.

Firstly, assuming this behaviour is as intended (for efficiency?), I 
think it's probably worth a mention in the Cookbook because it tripped 
me up and will doubtless trip others up in future.

Secondly, it also trips up 
DBIx::Class::HTMLWidget::populate_from_widget(), so perhaps that module 
needs a workaround.

Thirdly, I'm wondering if PK::Auto is doing the sane thing here. 
Technically I suppose it's doing the *right* thing, because a primary 
key column *could* contain an empty string. But in general a primary key 
containing an auto incrementing column usually contains *only* a single 
auto incrementing column of type int or similar. If you're using 
PK::Auto, chances are your primary key is a single auto-incrementing 
column and an empty string would not be a valid value. Consequently I 
think it might make sense if PK::Auto::insert() were to treat an empty 
string in the same way as undef when deciding whether to fetch last 
insert id from the database. I'd have thought the convenience of having 
primary key values returned correctly every time would far outweigh the 
small performance hit it might incur in a small percentage of cases.

Any thoughts?



More information about the Dbix-class mailing list