palantir/sqlite3worker

Get id of previously inserted row

Opened this issue · 5 comments

nk9 commented

I have two tables that I'd like to insert data into. They are joined by a foreign key. I want to put A into the first table, grab its auto-generated id, and then insert AA, AB, and AC into the second table, all referencing A.

Using vanilla sqlite3, I could use either cursor.lastrowid from Python or last_insert_rowid() in SQL. (See SO.) But in sqlite3worker, I can't figure out how to achieve this. Of course, given all the threads, it is absolutely essential that I grab the most recent row id in the same atomic transaction as the INSERT.

I thought maybe I could put both INSERT statements into a single call to execute(), but that's explicitly not possible. I'm supposed to use executescript() for that, but sqlite3worker doesn't implement this method.

So short of forking and implementing executescript(), or writing the thread safety by hand, is there a recommended way to achieve this task? I was kind of expecting it to be obvious, since this seems like a very common use case. Maybe I'm just missing it.

CC @dashawn888

nk9 commented

Thanks for the super quick reply!

I opened an issue here because it wasn't possible to do so in the forked repo. I think you have to turn that on.

Glad to hear it's not just me who wants to be able to do this. And thanks for your work on this library. For most simple tasks, it's a damn sight easier than implementing my own queue and writer thread. Bonkers that the Python standard sqlite3 library makes this so difficult.

nk9 commented

So, I have now spent a little more time looking into this, and I'm wondering if maybe SQLite has changed over the years. It now supports (compile-time) threading options, one of which allows multiple threads to use the database "without restrictions". My Debian install has this set to 1 by default, which is the "go bananas" Serialized mode.

While it might still be useful to employ sqlite3worker if your sqlite3 install is stuck on single-thread mode, I'm now wondering if maybe I've been over-complicating matters.

That said, there could still be a performance benefit to queueing the writes.