Question: Is there a way to reserve a new rowid for a table in sqlite3 for later use?
Background: In my sqlite3 database, a capacity has one or more args. So I use the following tables:
CREATE TABLE IF NOT EXISTS capacity(
id INTEGER PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
org INTEGER NOT NULL,
user INTEGER NOT NULL,
FOREIGN KEY(user) REFERENCES user(id) ON DELETE CASCADE,
FOREIGN KEY(org) REFERENCES org(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS capacity_args(
id INTEGER PRIMARY KEY NOT NULL,
capacity INTEGER NOT NULL,
arg BLOB NOT NULL,
FOREIGN KEY(capacity) REFERENCES capacity(id) ON DELETE CASCADE,
);
The problem with this is that when I insert new records in a transaction, I need to know the capacity Id for the capacity column in capacity_args. Most solutions I’ve seen suggest SELECT last_insert_rowid();
but this doesn’t seem safe within a transaction in a concurrent environment. Using autoincrement has the same problem: After reading an autoincrement primary key, another process might add a capacity before I’ve added mine. The only safe answer I’ve found is manage a custom list of ids in a separate table and commit addition and removal accordingly but this does not use sqlite’s id allocation mechanism at all.
Isn’t there a better solution?