Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change sqlx-sqlite to check for uniqueness error instead of checking for existence #52

Merged
merged 1 commit into from
Oct 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 19 additions & 9 deletions sqlx-store/src/sqlite_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,30 @@ impl SqliteStore {
Ok(())
}

async fn id_exists(&self, conn: &mut SqliteConnection, id: &Id) -> session_store::Result<bool> {
async fn try_create_with_conn(
&self,
conn: &mut SqliteConnection,
record: &Record,
) -> session_store::Result<bool> {
let query = format!(
r#"
select exists(select 1 from {table_name} where id = ?)
insert or abort into {table_name}
(id, data, expiry_date) values (?, ?, ?)
"#,
table_name = self.table_name
);
let res = sqlx::query(&query)
.bind(record.id.to_string())
.bind(rmp_serde::to_vec(record).map_err(SqlxStoreError::Encode)?)
.bind(record.expiry_date)
.execute(conn)
.await;

Ok(sqlx::query_scalar(&query)
.bind(id.to_string())
.fetch_one(conn)
.await
.map_err(SqlxStoreError::Sqlx)?)
match res {
Ok(_) => Ok(true),
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => Ok(false),
Err(e) => Err(SqlxStoreError::Sqlx(e).into()),
}
}

async fn save_with_conn(
Expand Down Expand Up @@ -133,10 +144,9 @@ impl SessionStore for SqliteStore {
async fn create(&self, record: &mut Record) -> session_store::Result<()> {
let mut tx = self.pool.begin().await.map_err(SqlxStoreError::Sqlx)?;

while self.id_exists(&mut tx, &record.id).await? {
while !self.try_create_with_conn(&mut tx, record).await? {
record.id = Id::default(); // Generate a new ID
}
self.save_with_conn(&mut tx, record).await?;

tx.commit().await.map_err(SqlxStoreError::Sqlx)?;

Expand Down