Add database transaction instead of multiple connections

This commit is contained in:
2026-03-16 17:37:09 +01:00
parent b011d134b9
commit ca1e8ff2bd

View File

@@ -147,7 +147,8 @@ impl Database {
song: &str,
rating: i64,
) -> Result<()> {
let mut conn = self.pool.acquire().await?;
// Begin the transaction
let mut tx = self.pool.begin().await?;
// Add interpret
let _ = sqlx::query(
@@ -157,7 +158,7 @@ impl Database {
"#,
)
.bind(interpret)
.execute(&mut *conn)
.execute(&mut *tx)
.await?;
// Get the interpret ID
@@ -168,7 +169,7 @@ impl Database {
"#,
)
.bind(interpret)
.fetch_one(&mut *conn)
.fetch_one(&mut *tx)
.await?;
let interpret_id: i64 = record.try_get("id")?;
@@ -182,7 +183,7 @@ impl Database {
)
.bind(song)
.bind(interpret_id)
.execute(&mut *conn)
.execute(&mut *tx)
.await?;
// Get the song ID
@@ -193,7 +194,7 @@ impl Database {
"#,
)
.bind(song)
.fetch_one(&mut *conn)
.fetch_one(&mut *tx)
.await?;
let song_id: i64 = record.try_get("id")?;
@@ -208,9 +209,12 @@ impl Database {
.bind(user_id)
.bind(song_id)
.bind(rating)
.execute(&mut *conn)
.execute(&mut *tx)
.await?;
// Commit the transaction to save everything!
tx.commit().await?;
Ok(())
}