-
I am using a SqlitePool to insert a row and return its id via this query: I am afraid, that i get into a race condition when executing multiple queries at once. Where one query overwrites the other querys' last inserted id. I checked the documentation for information, if sqlitepool uses different connections for each tokio thread but did not find something. I also found some blog posts, on how sqlite does not really insert in parallelism and waits for each insertion, but there is always someone who sais the opposit. How can i handle this? With a transaction? Or does sqlx handle this for me, and i don't need to worry about it? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
For this specific situation, if you have a recent enough SQLite, I think the documentation guarantees that |
Beta Was this translation helpful? Give feedback.
-
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 |
Beta Was this translation helpful? Give feedback.
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:
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 orpool.begin()
for a transaction), or better yet, useINSERT INTO ... RETURNING rowid
as @Ltrlg sugge…