Change sqlx-sqlite to check for uniqueness error instead of checking for existence #52
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Currently, the sqlx-sqlite store has an issue with databases running using the WAL journal if multiple requests come in at the same time, causing a "database is locked" error. The sequence is roughly this:
SqliteStore::create
, at the same time.SqliteStore::id_exists
. Both lock the database for reading and sets their "end mark" to the current database state.save_with_conn
first and commits its transaction. This upgrades its lock to a write lock and advances the database state - connection 2's end mark is still before this update.save_with_conn
. It attempts to upgrade its read lock to a write lock, but fails since the database has been modified since the read lock was acquired, and sqlite returns a "database is locked" error.This patch fixes the issue by removing the
if_exists
check and instead attempts to insert the ID, check if the insert fails with a uniqueness error, and regenerate the ID if so. With this, all connections immediately lock the database for writing and will wait for each other to finish before inserting. It should also be more performant in the common case of the generated ID being unique.