Search code examples
javascriptsqliteinsert-updaterowid

Retrieve multiple rowids in SQLite insert or update, using JavaScript


I know SQLite have last_insert_rowid() function. I'd like to create a similar function but I want to retrieve an array of indexes, each one coming from an insert or update into my db. To be clearer, I have a populated table like this (name is UNIQUE):

rowid  name   age

1     'John'  18

2     'Anne'  25

3     'Jack'  32

Then I have to insert or update few lines: ('John',19), ('Michael',33), ('Jenny',12)

Result will be:

rowid  name     age

1     'John'    19

2     'Anne'    25

3     'Jack'    32

4     'Michael' 33

5     'Jenny'   12

And rowids inserted/updated are: 1,4,5

How may I retrieve those indexes? JS answer would be nice, anyway even in other languages I suppose I should understand.


Solution

  • I solved using two triggers. The logical flow is:

    1. Create a temp table, temp_table, clone of the main table;
    2. Create an insert trigger, tr_insert. This trigger verify the insertion in the main table and copy the new row also in temp_table;
    3. Create an update trigger, tr_update, that acts similarly to the one in point 2, but for updates;
    4. After all insertions / updates, call a function that analyze temp_table in which are rows inserted / updated.
    5. Remember to call delete from temp_table after its use