Skip to content

Thread-safe last_insert_rowid in sqlite? #2090

Answered by abonander
ywegel asked this question in Q&A
Discussion options

You must be logged in to vote

last_insert_rowid() should always be consistent, provided that you actually execute it on the same connection that you did the insert.

If you are making your queries like this:

// where `pool` is `SqlitePool`:
sqlx::query!("INSERT INTO ... VALUES (...)")
    .execute(&pool)
    .await?;

let id = sqlx::query_scalar!("SELECT last_insert_rowid()")
    .fetch_one(&pool)
    .await?;

This will not be consistent as the two calls may potentially use different connections. You should either ensure you execute the two queries with the same connection (using either pool.acquire() for a connection or pool.begin() for a transaction), or better yet, use INSERT INTO ... RETURNING rowid as @Ltrlg sugge…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by ywegel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants