bigpresh/Dancer-Plugin-Database

Wishlist: Return last insert ID after quick_insert.

jahagirdar opened this issue · 2 comments

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

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