Open jahagirdar opened 7 years ago
Hi,
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});