I'm trying to perform an INSERT + UPDATE transaction in a database from my node.js application using node-sqlite3. However, I can't figure out how to get the last_insert_rowid when the transaction is done. My query looks something like this:
BEGIN TRANSACTION;
INSERT INTO <table> (field1, ...) VALUES (value1, ...);
UPDATE <table> SET prev=last_insert_rowid() WHERE <condition>;
END TRANSACTION;
This string (minus extra whitespace) is assigned to var q
.
I've got my database opened at some point using this:
var db = new sqlite3.Database(dbfile)
But if I try to use:
db.run(q, function(err) {
if (err) ...
console.log(this.lastId)
})
not only does it print "0" with no errors, but no changes to the database occur!!! If I use exec
instead of run
then the query runs successfully, but I have no way of getting any data back from exec.
I have also tried something like this:
db.exec(q, function(err) {
if (err) ...
db.run(";", function(err) {
if (err) ...
console.log(this.lastId)
})
})
But the "this" context on the "run" does not have a lastId property!
I also looked at the sqlite3-transaction package, but it doesn't seem to provide any information in the transaction callback either!
I can't run the insert as a separate run(), get the this.lastId
and then use that to run the update, because this will leave the database in an invalid state between the two statements (hence the need for a transaction).
How do I get the last_insert_rowid() from this transaction?