From 467c00410cbf4c17a5c7a27c6e40c0eee21e0743 Mon Sep 17 00:00:00 2001 From: Timo Ley Date: Sun, 16 Jan 2022 13:31:16 +0100 Subject: [PATCH] SQL add_meme returns meme ID --- src/v1/routes.rs | 2 +- src/v1/sql.rs | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/v1/routes.rs b/src/v1/routes.rs index 5e0f431..3bda2da 100644 --- a/src/v1/routes.rs +++ b/src/v1/routes.rs @@ -149,7 +149,7 @@ async fn upload( for f in files { let res = cat.add_meme(&user, &f, &ip, &db_pool).await?; - if res != 1 { + if res == 0 { return Err(APIError::Internal("Database insertion error".to_string())); } diff --git a/src/v1/sql.rs b/src/v1/sql.rs index fff7d9c..7a4ba98 100644 --- a/src/v1/sql.rs +++ b/src/v1/sql.rs @@ -116,14 +116,20 @@ impl Category { ip: &String, pool: &MySqlPool, ) -> Result { - let q = sqlx::query("INSERT INTO memes (filename, user, category, timestamp, ip, cid) VALUES (?, ?, ?, NOW(), ?, ?)") + let mut tx = pool.begin().await?; + sqlx::query("INSERT INTO memes (filename, user, category, timestamp, ip, cid) VALUES (?, ?, ?, NOW(), ?, ?)") .bind(&file.name) .bind(&user.id) .bind(&self.id) .bind(ip) .bind(&file.hash) - .execute(pool).await?; - Ok(q) + .execute(&mut tx).await?; + let id: u64 = sqlx::query("SELECT LAST_INSERT_ID() as id") + .map(|row: MySqlRow| row.get("id")) + .fetch_one(&mut tx) + .await?; + tx.commit().await?; + Ok(id) } }