On TOF there is this question
I need to be sure of what primary key was just assigned. I know there are easy ways to do this with SQLite, but I need a reliable method that will work on other DBs too.
I would imagine it’s just the highest one in the table, but how would I know if someone else had written one at the same time - between my execute and select?
There is and the technique works in ANY ACID compliant DB
I’ve used it for nearly 30 years
And it makes it possible to support something like “sequences” which are unique per table
It requires a table to persist the last used ID, here called SEQUENCES, that has one column, NEXTID
Then the general process is
begin transaction
update SEQUENCES set NEXTID = NEXTID + 1
select NEXTID from SEQUENCES
commit transaction
// return what was selected
doing this in a transaction and updating FIRST causes every other access to this table to be paused until this simple sequence concludes
to make this per table make the SEQUENCES table have an extra column that is the table name and then update the code to update SEQUENCES where the table name matches & to select from SEQUENCES where the table name matches
And this is nicely portable to any DB that properly implements transactions
Note that some DB’s do NOT support nesting transactions so this can be something that you need to deal with