You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Everywhere in my code I end up doing the following.
database->quick_insert($table,$data);
$data->{id}=database->last_insert_id(undef,undef,undef,$pk);
if ($data->{id}==0){
my $data=database->quick_select($table,$data);
}
it would be much cleaner to replace the above with either one of the following
$data=database->quick_insert($table,$data,{return=>$pk});
OR $data->{id}=database->quick_insert($table,$data,{return=>$pk});
OR $data->{id}=database->quick_insert_with_id($table,$data,{return=>$pk});
The text was updated successfully, but these errors were encountered:
last_insert_id is not supported by every DBI driver, and support is inconsistent among those that offer it.
This is how I do it for a MySQL DB:
get '/insert/:name' => sub {
database->quick_insert('people', { name => params->{name} });
my $id = ( database->selectall_array('select last_insert_id()') )[0][0];
};
I created the quite simple module DBIx::Core::Handle::ReturnValue which can be used together with Dancer2::Plugin::Database. In addition to simplifying the use of last_insert_id a bit, it can be very helpful when using the Postgres RETURNING - which can also be used with UUIDs or other non-autoincrement primary keys.
This functionality could also be integrated directly into Dancer::Plugin::Database::Core::Handle. And there are already other functions in the module which are Postgres-specific (e.g. ilike).
Everywhere in my code I end up doing the following.
it would be much cleaner to replace the above with either one of the following
$data=database->quick_insert($table,$data,{return=>$pk});
OR
$data->{id}=database->quick_insert($table,$data,{return=>$pk});
OR
$data->{id}=database->quick_insert_with_id($table,$data,{return=>$pk});
The text was updated successfully, but these errors were encountered: