views:

87

answers:

2

Is there a one-statement select-and-update (or update-and-select) method in SQLite?

A trigger can invoke select, but that doesn't allow update to be used in an expression:

CREATE TABLE id ( a integer );
CREATE TRIGGER idTrig AFTER UPDATE ON id BEGIN SELECT old.a FROM id; END;
INSERT INTO id VALUES ( 100 );
INSERT INTO test VALUES ( (UPDATE id SET a=a+1) ); -- syntax error

(Is a triggered select only accessible via the C API?)

I generate object IDs for several databases from a single ID database (with a single row for the next available ID). I'd like to select-and-update on the ID db in one statement, so that concurrent db connections which attach the ID db won't have trouble with this (where two connections could insert before either updates):

INSERT INTO tab VALUES ( (SELECT uuid||oid AS oid FROM id.tab), ... );
UPDATE id.tab SET oid = oid+1;
A: 

I'll start with the prerequisite nag: why not use GUIDs? They don't require central authority and are thus more efficient and easier to work with.

If you really need a central ID store, you can make the ID an autoincrement and fetch it with SELECT last_insert_rowid(). If you have to generate your own IDs, then make the ID column a primary key, so you can generate the ID, INSERT it, and retry if the INSERT fails.

Marcelo Cantos
SELECT last_insert_rowid() requires that I add rows to the ID db, and I imagined keeping one row there with the next available ID. I could INSERT/last_insert_rowid/DELETE... (BTW a UUID is already part of the generated ID.)
Liam
GUIDs or UUIDs are bad for caching. If the index doesn't fit in memory, performance will drop significantly.
Thomas Mueller
@Liam: If you are already using a UUID, why do you need anything extra?
Marcelo Cantos
Users can share objects, so a UUID is assigned to each user, and I append a counter to that.
Liam
@Liam: I'm confused. If the user's ID forms part of the object's ID, how can the object be shared by multiple users?
Marcelo Cantos
Each user has an ID generator based on a UUID, so that an object created by one can live in others' dbs.
Liam
A: 

This discussion presents two possible solutions:

http://www.mail-archive.com/[email protected]/msg10705.html

Liam