bigpresh / Dancer-Plugin-Database

Dancer::Plugin::Database - easy database support for Dancer applications
http://search.cpan.org/dist/Dancer-Plugin-Database
37 stars 36 forks source link

Wishlist: Return last insert ID after quick_insert. #93

Open jahagirdar opened 6 years ago

jahagirdar commented 6 years ago

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});

1nickt commented 6 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];
};
sonntagd commented 6 years ago

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).