From 22621cb49466a4e806ade30be51aca5cadf86b37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 08:01:17 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=97=83=EF=B8=8F=20feat!:=20port=20bank+po?= =?UTF-8?q?ol=20to=20sqlx/Postgres?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/bank_question.rs | 361 ++++++++++++++++----------------- src/db/bank_question_image.rs | 221 ++++++++++---------- src/db/pool_question.rs | 368 ++++++++++++++++------------------ src/db/solution.rs | 205 ++++++++++++------- src/web/questions.rs | 4 +- 5 files changed, 583 insertions(+), 576 deletions(-) diff --git a/src/db/bank_question.rs b/src/db/bank_question.rs index d99f4bf..8b8c63e 100644 --- a/src/db/bank_question.rs +++ b/src/db/bank_question.rs @@ -7,10 +7,10 @@ use std::collections::HashMap; -use surrealdb::types::{RecordId, SurrealValue}; +use sqlx::types::Json; -use crate::constant::USAGE_COUNTS_SQL; -use crate::database::{Database, transaction_with_retry, write_with_retry}; +use crate::database::{Database, tx_with_retry}; +use crate::db::page::{PagedList, Param}; use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; use crate::domain::bank_question_image::BankQuestionImage; use crate::domain::exam::ExamId; @@ -21,21 +21,6 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -/// One `GROUP BY from_bank` row of [`usage_counts`]. -#[derive(SurrealValue)] -struct UsageCount { - from_bank: BankQuestionId, - n: i64, -} - -/// What one [`delete`] transaction removed — the template (an empty list once -/// someone else deleted it first) and the image rows swept with it. -#[derive(SurrealValue)] -struct DeleteOutcome { - question: Vec, - images: Vec, -} - pub async fn create( db: &Database, owner: UserId, @@ -85,24 +70,52 @@ async fn insert( BankVisibility::default(), Timestamp::now(), ); - let created: Option = db.create(question.id.record()).content(question).await?; - created.ok_or_else(|| AppError::Internal("failed to create bank question".into())) + let row = sqlx::query_as!( + BankQuestion, + r#"INSERT INTO bank_question + (id, owner, subject, text, kind, points, choices, correct, + source_exam, visibility, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) + RETURNING *"#, + question.id, + question.owner, + question.subject, + question.text, + question.kind, + question.points, + question.choices, + question.correct, + question.source_exam, + question.visibility, + question.created_at, + ) + .fetch_one(db) + .await?; + Ok(row) } pub async fn read(db: &Database, id: &BankQuestionId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + BankQuestion, + "SELECT * FROM bank_question WHERE id = $1", + id + ) + .fetch_optional(db) + .await?; + Ok(row) } -/// One page of the bank the caller may see, **newest first** (ULID ids sort by -/// creation, so `id DESC` is newest-first) — plus the total row count under -/// the same filters, so a client can page past the window. +/// One page of the bank the caller may see, **newest first** (`id DESC` is +/// mint order — the ids are write-ordered UUIDv7) — plus the total row count +/// under the same filters, so a client can page past the window. /// -/// Every filter is a WHERE clause and the window is a real `LIMIT`/`START`: -/// the old version read the whole table and sliced it in memory, which hid -/// every template past the client's first page. `q` is a case- and -/// diacritic-insensitive fragment of the question text (blank = no text -/// filter): needle and column both go through -/// [`crate::domain::text_fold`], so `istanbul` finds `İSTANBUL` and back. +/// The window is a real `LIMIT`/`OFFSET` handed to the database (the +/// [`PagedList`] builder: the filters are runtime-conditional, which is that +/// builder's named exemption from the compile-time macros). `q` is a case- +/// and diacritic-insensitive fragment of the question text (blank = no text +/// filter): needle and column both go through [`crate::domain::text_fold`], +/// so `istanbul` finds `İSTANBUL` and back. `position` rather than `LIKE` +/// keeps the needle a *literal* substring — no `%`/`_` wildcard surprises. /// /// `visible_to` is the security filter, and it is a WHERE clause like every /// other one — never a post-filter, or `total` would count templates the @@ -113,11 +126,13 @@ pub async fn read(db: &Database, id: &BankQuestionId) -> Result Result<(Vec, i64), AppError> { let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); - let mut clauses = Vec::new(); - if visible_to.is_some() { - clauses.push("(visibility = 'school' OR owner = $viewer)"); - } - if visibility.is_some() { - clauses.push("visibility = $visibility"); - } - if owner.is_some() { - clauses.push("owner = $owner"); - } - if subject.is_some() { - clauses.push("subject = $subject"); - } - let text_clause = format!("{} CONTAINS $q", search_fold_sql("text")); - if needle.is_some() { - clauses.push(text_clause.as_str()); - } - let where_clause = if clauses.is_empty() { - "true".to_string() - } else { - clauses.join(" AND ") - }; - // `START` alone (no `LIMIT`) is the unpaged case — `?limit` is opt-in. - let window = match limit { - Some(_) => "LIMIT $limit START $offset", - None => "START $offset", - }; - // The count runs over the *same* WHERE, so `total` can never disagree - // with what paging through the list actually yields. - let mut query = db - .query(format!( - "SELECT * FROM bank_question WHERE {where_clause} ORDER BY id DESC {window}; - SELECT VALUE count() FROM bank_question WHERE {where_clause} GROUP ALL;" - )) - .bind(("offset", offset)); + let mut clauses: Vec = Vec::new(); + let mut binds: Vec = Vec::new(); if let Some(viewer) = visible_to { - query = query.bind(("viewer", viewer.record())); + binds.push(Param::Uuid(viewer.uuid())); + clauses.push(format!( + "(visibility = 'school' OR owner = ${})", + binds.len() + )); } if let Some(visibility) = visibility { - query = query.bind(("visibility", visibility.as_str().to_string())); + binds.push(Param::Text(visibility.as_str().to_string())); + clauses.push(format!("visibility = ${}", binds.len())); } if let Some(owner) = owner { - query = query.bind(("owner", owner.record())); + binds.push(Param::Uuid(owner.uuid())); + clauses.push(format!("owner = ${}", binds.len())); } if let Some(subject) = subject { - query = query.bind(("subject", subject.record())); + binds.push(Param::Uuid(subject.uuid())); + clauses.push(format!("subject = ${}", binds.len())); } if let Some(needle) = needle { - query = query.bind(("q", needle)); + binds.push(Param::Text(needle)); + clauses.push(format!( + "position(${} in {}) > 0", + binds.len(), + search_fold_sql("text") + )); } - if let Some(limit) = limit { - query = query.bind(("limit", limit)); + let from_where = if clauses.is_empty() { + "bank_question WHERE true".to_string() + } else { + format!("bank_question WHERE {}", clauses.join(" AND ")) + }; + // The count runs over the *same* WHERE, so `total` can never disagree + // with what paging through the list actually yields. + let mut page = PagedList::new(from_where, "ORDER BY id DESC"); + for bind in binds { + page = page.bind(bind); } - let mut result = query.await?.check()?; - let questions = result.take::>(0)?; - // `GROUP ALL` yields no row at all when nothing matched. - let total = result.take::>(1)?.first().copied().unwrap_or(0); - Ok((questions, total)) + page.run(limit, offset, db).await } /// How many exam questions were instantiated from each of `ids` — the /// `from_bank` side of the provenance link, tallied for a whole page in /// **one** grouped query (a `count()` per row would be the N+1 this page -/// already had removed once). Keys are template record keys; a template +/// already had removed once). Keys are the templates' wire keys; a template /// nobody ever used has no entry at all, so the caller reads a miss as /// zero — and the UI can stay quiet rather than print "0". /// @@ -207,16 +205,22 @@ pub async fn usage_counts( if ids.is_empty() { return Ok(HashMap::new()); } - let records: Vec = ids.iter().map(|id| id.record()).collect(); - let mut result = db - .query(USAGE_COUNTS_SQL) - .bind(("ids", records)) - .await? - .check()?; - Ok(result - .take::>(0)? + let ids: Vec = ids.iter().map(|id| (*id).clone()).collect(); + let rows = sqlx::query!( + r#"SELECT from_bank AS "from_bank: BankQuestionId", count(*) AS n + FROM exam_question + WHERE from_bank = ANY($1) + GROUP BY from_bank"#, + ids, + ) + .fetch_all(db) + .await?; + Ok(rows .into_iter() - .map(|row| (row.from_bank.key().to_string(), row.n)) + .filter_map(|row| { + let n = row.n; + row.from_bank.map(|from_bank| (from_bank.key(), n)) + }) .collect()) } @@ -228,22 +232,13 @@ pub async fn usage_counts( /// field is re-stated from the snapshot, and the kind/choices/correct trio /// has to be (a text-only edit re-submits the stored options *with their /// ids* so each keeps its picture) — so without the compare-and-set the -/// later writer silently reverts the earlier one — and the window is a -/// database round trip wide, which is exactly how far apart two concurrent -/// requests to this one process can sit. +/// later writer silently reverts the earlier one. /// /// Every field the merge re-states is in the guard, which is the same list -/// the `SET` writes. `choices` is compared whole: its objects carry two -/// required string keys, so none is ever dropped for being `NONE` (the trap -/// [`crate::db::settings::save_if_unchanged`] works around). -/// -/// Rides [`write_with_retry`] because an image write now moves this row too -/// ([`crate::db::bank_question_image::upsert`]): an upload landing in the -/// same instant makes the store answer "conflict, retry", and a bare -/// `check()` would turn that into a 500 for an edit that only had to be -/// re-sent. A lost round writes nothing, and the guard is re-evaluated on -/// the next one, so a genuine stale merge still comes back as `None`. -/// Admissible: an `UPDATE` can never answer "already exists". +/// the `SET` writes; the nullable ones compare `IS NOT DISTINCT FROM`, so an +/// absent subject/correct/choices guards truthfully. Postgres needs no retry +/// loop around this: the guard re-evaluates on the row lock at execution, so +/// a rival write either predates this statement's snapshot or loses its own. pub async fn update_if_unchanged( db: &Database, expected: BankQuestion, @@ -254,42 +249,40 @@ pub async fn update_if_unchanged( visibility: BankVisibility, ) -> Result, AppError> { let (kind, choices, correct) = spec.into_parts(); - let rows: Vec = write_with_retry( - db, - "UPDATE $id SET subject = $subject, text = $text, points = $points, - kind = $kind, choices = $choices, correct = $correct, - visibility = $visibility - WHERE subject = $was_subject AND text = $was_text - AND points = $was_points AND kind = $was_kind - AND choices = $was_choices AND correct = $was_correct - AND visibility = $was_visibility - RETURN AFTER", - &[ - ( - "was_subject".into(), - expected.subject.clone().map(|s| s.record()).into_value(), - ), - ("was_text".into(), expected.text.clone().into_value()), - ("was_points".into(), expected.points.into_value()), - ("was_kind".into(), expected.kind.clone().into_value()), - ("was_choices".into(), expected.choices.clone().into_value()), - ("was_correct".into(), expected.correct.clone().into_value()), - ( - "was_visibility".into(), - expected.visibility.clone().into_value(), - ), - ("id".into(), expected.id.record().into_value()), - ("subject".into(), subject.map(|s| s.record()).into_value()), - ("text".into(), text.into_value()), - ("points".into(), points.into_value()), - ("kind".into(), kind.into_value()), - ("choices".into(), choices.into_value()), - ("correct".into(), correct.into_value()), - ("visibility".into(), visibility.into_value()), - ], + let choices = choices.map(Json); + let row = sqlx::query_as!( + BankQuestion, + r#"UPDATE bank_question SET + subject = $2, text = $3, points = $4, kind = $5, + choices = $6, correct = $7, visibility = $8 + WHERE id = $1 + AND subject IS NOT DISTINCT FROM $9 + AND text = $10 + AND points = $11 + AND kind = $12 + AND choices IS NOT DISTINCT FROM $13 + AND correct IS NOT DISTINCT FROM $14 + AND visibility = $15 + RETURNING *"#, + expected.id, + subject, + text, + points, + kind, + choices, + correct, + visibility, + expected.subject, + expected.text, + expected.points, + expected.kind, + expected.choices, + expected.correct, + expected.visibility, ) + .fetch_optional(db) .await?; - Ok(rows.into_iter().next()) + Ok(row) } /// Delete the template and cascade-remove its bank images, so none points @@ -297,59 +290,53 @@ pub async fn update_if_unchanged( /// actually removed come back with it: the blobs are the web layer's to /// take off disk, but only for *these* rows — an upload that committed /// after the caller listed the template's images is swept here too, and a -/// pre-read snapshot would strand its blob for good -/// ([`crate::db::note::delete`]'s story, this domain over). -/// -/// Children first, in one transaction: as two queries, a failure between -/// them left image rows swept under a template that survived, or (the other -/// order) a template gone with its images still there. Rides the retry -/// because an image write now moves this very row -/// ([`crate::db::bank_question_image::upsert`]) — the two contend by -/// design, and a lost round through a bare `check()` would be a 500 for a -/// delete that only had to be re-sent. Admissible: no `UPDATE` or `DELETE` -/// in here can answer "already exists". +/// pre-read snapshot would strand its blob for good. /// -/// Exam questions tied to this template keep living: only their provenance -/// links are cleared, field-scoped (never a whole-row save — the question -/// isn't ours and may be edited concurrently), so nothing can read a link to -/// a template that no longer exists. *Both* directions point at a template, -/// so both are cleared: `from_bank` on the questions instantiated from it, -/// and `banked_as` on the question it was saved out of. +/// All four statements are one transaction, children before the parent so +/// the foreign keys never refuse the parent delete: the provenance links +/// clear first (exam questions tied to this template keep living — only the +/// links go, field-scoped, in both directions: `from_bank` on the questions +/// instantiated from it and `banked_as` on the question it was saved out +/// of), then the image sweep, then the row. `cascade = true` because an +/// image upsert committing inside this window makes the parent delete +/// answer 23503 — a mid-cascade race the retry loop re-runs, sweeping the +/// latecomer with it. pub async fn delete( db: &Database, target: BankQuestion, ) -> Result<(BankQuestion, Vec), AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - LET $images = (DELETE bank_question_image WHERE bank_question = $b RETURN BEFORE); - UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b; - UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b; - LET $gone = (DELETE $b RETURN BEFORE); - RETURN { question: $gone, images: $images }; - COMMIT TRANSACTION;", - &[("b".into(), target.id.record().into_value())], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is the last statement before `COMMIT`, so its - // slot follows the statement count rather than a hand-kept number; - // `num_statements` counts BEGIN and COMMIT. - let slot = result.num_statements().saturating_sub(2); - let outcome = result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to delete bank question".into()))?; - let question = outcome - .question - .into_iter() - .next() + tx_with_retry(db, true, async |tx| { + let id = target.id.clone(); + sqlx::query!( + "UPDATE exam_question SET from_bank = NULL WHERE from_bank = $1", + id + ) + .execute(tx) + .await?; + sqlx::query!( + "UPDATE exam_question SET banked_as = NULL WHERE banked_as = $1", + id + ) + .execute(tx) + .await?; + let images = sqlx::query_as!( + BankQuestionImage, + "DELETE FROM bank_question_image WHERE bank_question = $1 RETURNING *", + id + ) + .fetch_all(tx) + .await?; + let question = sqlx::query_as!( + BankQuestion, + "DELETE FROM bank_question WHERE id = $1 RETURNING *", + id + ) + .fetch_optional(tx) + .await? .ok_or(AppError::NotFound)?; - Ok((question, outcome.images)) + Ok((question, images)) + }) + .await } #[cfg(test)] diff --git a/src/db/bank_question_image.rs b/src/db/bank_question_image.rs index 988b2a1..3cb2be6 100644 --- a/src/db/bank_question_image.rs +++ b/src/db/bank_question_image.rs @@ -1,105 +1,69 @@ -//! The `bank_question_image` slot table: the per-slot upsert that pins the -//! template's existence into its own transaction, the page-wide listing, and -//! the choice sweep a non-destructive PATCH runs. Blob I/O stays in the web -//! layer; the pure entity and newtypes in +//! The `bank_question_image` slot table: the per-slot upsert, the page-wide +//! listing, and the choice sweep a non-destructive PATCH runs. Blob I/O +//! stays in the web layer; the pure entity and newtypes in //! [`crate::domain::bank_question_image`]. -use surrealdb::types::{RecordId, SurrealValue}; - -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, foreign_key_violation, tx_with_retry}; use crate::domain::bank_question::BankQuestionId; -use crate::domain::bank_question_image::{BankQuestionImage, BankQuestionImageId}; +use crate::domain::bank_question_image::BankQuestionImage; use crate::domain::exam_question::ChoiceId; use crate::error::AppError; -/// What one [`upsert`] transaction returns: the row it -/// stored and the blob name it replaced. Both are arrays because SurrealDB -/// drops an object key valued `NONE` on the way out, while an empty array -/// survives — "nothing was replaced" has to be readable, not missing. -#[derive(SurrealValue)] -struct UpsertOutcome { - stored: Vec, - replaced: Vec, -} - -/// Create or replace the slot's image row — the deterministic id makes this -/// the whole "one image per slot" story — handing back what it stored plus -/// the blob name it replaced, for the caller to take off disk. -/// -/// Both halves are the transaction's doing. The template's own `points` is -/// moved and put straight back inside it, the way -/// [`crate::db::pool_question::bump_question_and_write`] moves -/// `asked_at` (`created_at` is `READONLY`, so the move goes on the one other -/// int column): that makes the template's *existence* part of this write. -/// A bare `UPSERT` guarded by having read the template first does not -/// survive its delete window — the read sees a row -/// [`crate::db::bank_question::delete`] has removed but -/// not committed, while that delete's image sweep ran on a snapshot -/// predating this row, so both commit and the image outlives the template -/// it hangs on. Nothing could ever read, delete, or sweep it afterwards: -/// every image route goes through the template. Moving the value makes the -/// two transactions touch one key, so the store refuses a side; writing the -/// same value back would be elided and collide with nothing. +/// Create or replace the slot's image row — the table's `NULLS NOT DISTINCT` +/// unique key makes this the whole "one image per slot" story — handing back +/// what it stored plus the blob name it replaced, for the caller to take off +/// disk. /// -/// The replaced blob name comes out of this same transaction rather than a -/// read in front of it (the shape -/// [`crate::db::pool_question::set_image`] has): two -/// uploads to one slot both write this row, so they contend and the loser -/// re-reads the winner's blob name, where two pre-reads both saw the *old* -/// blob and left the loser's fresh one orphaned on disk. +/// Both halves are the transaction's doing, and the row lock makes them one +/// switch: two uploads racing on one slot serialize on the `FOR UPDATE`, and +/// the loser's `ON CONFLICT` re-reads the winner's row, where two unlocked +/// pre-reads would both have seen the *old* blob name and left the loser's +/// fresh one orphaned on disk. /// -/// Admissible for [`transaction_with_retry`]: the `UPSERT`'s id is -/// deterministic per (question, slot) and the table carries no `UNIQUE` -/// index, so the write always resolves onto the row its id names and can -/// never answer "already exists". +/// The template's existence rides the real foreign key: an insert whose +/// template was deleted mid-flight answers 23503 and maps to the same 404 +/// the old points-move transaction produced with its `THROW`. Nothing is +/// written either way. pub async fn upsert( db: &Database, image: BankQuestionImage, ) -> Result<(BankQuestionImage, Option), AppError> { - // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic - let (question, id) = (image.bank_question.record(), image.id.record()); - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - LET $was_points = (SELECT VALUE points FROM ONLY $b); - LET $bumped = (UPDATE $b SET points = points + 1 RETURN VALUE id); - IF array::len($bumped) = 0 { THROW 'no_question' }; - UPDATE $b SET points = $was_points; - LET $replaced = (SELECT VALUE file FROM $id); - LET $stored = (UPSERT $id CONTENT $image); - RETURN { stored: $stored, replaced: $replaced }; - COMMIT TRANSACTION;", - &[ - ("b".into(), question.into_value()), - ("id".into(), id.into_value()), - ("image".into(), image.into_value()), - ], - &["no_question"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_question")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is the last statement before `COMMIT`, so its - // slot follows the statement count rather than a hand-kept number; - // `num_statements` counts BEGIN and COMMIT. - let slot = result.num_statements().saturating_sub(2); - let failed = || AppError::Internal("failed to store bank question image".into()); - let outcome = result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(failed)?; - let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; - Ok((stored, outcome.replaced.into_iter().next())) + tx_with_retry(db, false, async |tx| { + let was = sqlx::query!( + r#"SELECT file FROM bank_question_image + WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2 + FOR UPDATE"#, + image.bank_question.clone(), + image.slot.clone(), + ) + .fetch_optional(tx) + .await? + .map(|row| row.file); + let stored = match sqlx::query_as!( + BankQuestionImage, + r#"INSERT INTO bank_question_image + (bank_question, slot, file, content_type, size) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (bank_question, slot) DO UPDATE + SET file = $3, content_type = $4, size = $5 + RETURNING *"#, + image.bank_question.clone(), + image.slot.clone(), + image.file.clone(), + image.content_type, + image.size, + ) + .fetch_one(tx) + .await + { + Ok(row) => row, + // The template row is gone; no orphan image may outlive it. + Err(err) if foreign_key_violation(&err) => return Err(AppError::NotFound), + Err(err) => return Err(err.into()), + }; + Ok((stored, was)) + }) + .await } pub async fn read_slot( @@ -107,21 +71,30 @@ pub async fn read_slot( question: &BankQuestionId, slot: Option<&ChoiceId>, ) -> Result, AppError> { - Ok(db - .select(BankQuestionImageId::for_slot(question, slot).record()) - .await?) + let row = sqlx::query_as!( + BankQuestionImage, + r#"SELECT * FROM bank_question_image + WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2"#, + question, + slot.cloned(), + ) + .fetch_optional(db) + .await?; + Ok(row) } pub async fn list_for_question( db: &Database, question: &BankQuestionId, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM bank_question_image WHERE bank_question = $b") - .bind(("b", question.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query_as!( + BankQuestionImage, + "SELECT * FROM bank_question_image WHERE bank_question = $1", + question + ) + .fetch_all(db) + .await?; + Ok(rows) } /// The image rows of several templates in one query — for bucketing onto a @@ -133,13 +106,15 @@ pub async fn list_for_questions( if questions.is_empty() { return Ok(Vec::new()); } - let records: Vec = questions.iter().map(|q| q.record()).collect(); - let mut result = db - .query("SELECT * FROM bank_question_image WHERE bank_question IN $ids") - .bind(("ids", records)) - .await? - .check()?; - Ok(result.take::>(0)?) + let ids: Vec = questions.iter().map(|q| (*q).clone()).collect(); + let rows = sqlx::query_as!( + BankQuestionImage, + "SELECT * FROM bank_question_image WHERE bank_question = ANY($1)", + ids + ) + .fetch_all(db) + .await?; + Ok(rows) } /// Drop the option pictures whose choice is gone — every choice image of @@ -157,23 +132,35 @@ pub async fn delete_choices_not_in( keep: &[ChoiceId], ) -> Result, AppError> { let keep: Vec = keep.iter().map(|id| id.as_str().to_string()).collect(); - let mut result = db - .query( - "DELETE bank_question_image \ - WHERE bank_question = $b AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", - ) - .bind(("b", question.record())) - .bind(("keep", keep)) - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query_as!( + BankQuestionImage, + r#"DELETE FROM bank_question_image + WHERE bank_question = $1 + AND slot IS NOT NULL + AND NOT (slot = ANY($2)) + RETURNING *"#, + question, + keep + ) + .fetch_all(db) + .await?; + Ok(rows) } pub async fn delete( db: &Database, image: BankQuestionImage, ) -> Result { - let deleted: Option = db.delete(image.id.record()).await?; + let deleted = sqlx::query_as!( + BankQuestionImage, + r#"DELETE FROM bank_question_image + WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2 + RETURNING *"#, + image.bank_question, + image.slot + ) + .fetch_optional(db) + .await?; deleted.ok_or(AppError::NotFound) } diff --git a/src/db/pool_question.rs b/src/db/pool_question.rs index 0adf2c4..ead4505 100644 --- a/src/db/pool_question.rs +++ b/src/db/pool_question.rs @@ -1,137 +1,85 @@ //! The `pool_question` table: ask/insert, the two listings, the guarded //! approve that rides the publish counters along, the pending-only image -//! writes, and the delete that cascades solutions — plus -//! [`bump_question_and_write`], the existence-move every child write goes -//! through. The pure entity and newtypes live in -//! [`crate::domain::pool_question`]; the web layer reaches these through -//! [`crate::service::pool_question`]. - -use surrealdb::types::SurrealValue; - -use crate::constant::{ - POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, STATUS_APPROVED, STATUS_PENDING, -}; -use crate::database::{Database, transaction_with_retry}; +//! writes, and the delete that cascades solutions. The pure entity and +//! newtypes live in [`crate::domain::pool_question`]; the web layer reaches +//! these through [`crate::service::pool_question`]. + +use crate::constant::{STATUS_APPROVED, STATUS_PENDING}; +use crate::database::{Database, tx_with_retry}; use crate::domain::note_file::FileContentType; use crate::domain::pool_question::{PoolQuestion, PoolQuestionId}; use crate::domain::solution::Solution; use crate::domain::user::UserId; use crate::error::AppError; -/// Move the question's `asked_at` **and** run `statement` — a write to -/// something hanging off a question — in one transaction, handing back the row -/// it returned. `NotFound` means the question is gone and nothing was written. -/// -/// The move is what makes the question's **existence** part of the child's own -/// write, the way [`crate::domain::menu::bump_menu_and_write`] does for a menu: -/// the `UPDATE` matches nothing once the row is deleted, and a delete racing -/// this one touches the very key this transaction writes, so the two cannot -/// both commit. Reading the question first does *not* survive that race — the -/// read sees a row [`delete`] has removed but not committed, while its -/// `DELETE solution WHERE question = $q` ran on a snapshot predating this -/// insert, so both commit and the child outlives its question with neither -/// caller told anything. -/// -/// `asked_at` rather than a revision column because this row carries no counter -/// to bump and must not grow one for this alone. It is put back *by captured -/// value* in the same transaction, so nothing outside ever observes the move -/// and the row is byte-identical afterwards (the pool lists order on it). -/// Writing the same value would buy nothing: an `UPDATE` that leaves the -/// document unchanged is elided and never reaches the store's write set, so it -/// collides with nothing. -/// -/// Admissible for [`transaction_with_retry`] as long as `statement` is: the -/// `UPDATE`s, `SELECT`, `IF`/`THROW` and `RETURN` can never answer "already -/// exists". -pub(crate) async fn bump_question_and_write( - question: &PoolQuestionId, - statement: &str, - mut bindings: Vec<(String, surrealdb::types::Value)>, - db: &Database, -) -> Result, AppError> { - bindings.push(("q".into(), question.record().into_value())); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $was_asked = (SELECT VALUE asked_at FROM ONLY $q); - LET $bumped = (UPDATE $q SET asked_at = asked_at + 1 RETURN VALUE id); - IF array::len($bumped) = 0 {{ THROW 'no_question' }}; - UPDATE $q SET asked_at = $was_asked; - LET $row = ({statement}); - RETURN $row; - COMMIT TRANSACTION;" - ), - &bindings, - &["no_question"], +pub async fn insert(db: &Database, question: PoolQuestion) -> Result { + let row = sqlx::query_as!( + PoolQuestion, + r#"INSERT INTO pool_question (id, asker, title, body, status, asked_at) + VALUES ($1, $2, $3, $4, $5, $6) + RETURNING *"#, + question.id, + question.asker, + question.title, + question.body, + question.status, + question.asked_at, ) + .fetch_one(db) .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_question")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is the last statement before `COMMIT`, so its slot - // follows the statement count rather than a hand-kept number; - // `num_statements` counts BEGIN and COMMIT. - let slot = result.num_statements().saturating_sub(2); - Ok(result.take::>(slot)?.into_iter().next()) -} - -pub async fn insert(db: &Database, question: PoolQuestion) -> Result { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - let created: Option = db.create(question.id.record()).content(question).await?; - created.ok_or_else(|| AppError::Internal("failed to create pool question".into())) + Ok(row) } pub async fn read(db: &Database, id: &PoolQuestionId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + PoolQuestion, + "SELECT * FROM pool_question WHERE id = $1", + id + ) + .fetch_optional(db) + .await?; + Ok(row) } /// Every question, newest first — the teacher+ view (approval queue and /// pool in one list). pub async fn list_all(db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC") - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query_as!( + PoolQuestion, + "SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC", + ) + .fetch_all(db) + .await?; + Ok(rows) } /// The pool as a non-staff user sees it, newest first: every approved /// question, plus the caller's own pending ones. pub async fn list_visible_to(db: &Database, user: &UserId) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM pool_question WHERE status = $approved OR asker = $usr \ - ORDER BY asked_at DESC, id DESC", - ) - .bind(("approved", STATUS_APPROVED)) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = sqlx::query_as!( + PoolQuestion, + r#"SELECT * FROM pool_question + WHERE status = $1 OR asker = $2 + ORDER BY asked_at DESC, id DESC"#, + STATUS_APPROVED, + user + ) + .fetch_all(db) + .await?; + Ok(rows) } /// Publish a pending question into the pool, stamping who approved it. -/// The `WHERE status = $pending` guard makes the transition atomic: of two +/// The `WHERE status = 'pending'` guard makes the transition atomic: of two /// racing approvals exactly one wins, and an approve can never land on a /// question deleted mid-flight. `None` = the question wasn't pending /// (already approved, or gone) — the caller sorts out which. /// -/// Two lifetime badge counters ride that same guard, inside this +/// Two lifetime badge counters ride that same guard inside this /// transaction: the approver's `pool_approved_total` and the *asker's* -/// `pool_published_total`. Both hang off `array::len($done) > 0` — the -/// guard's own verdict — so the pair moves once per real transition and -/// never on a second approve of an already-approved question. -/// (`count ?? 0 > 0` misparses here; `array::len` is the spelling that -/// holds.) The second conjunct is the self-approval rule below. +/// `pool_published_total`. Both move only when the guard's own verdict +/// landed, so the pair moves once per real transition and never on a second +/// approve of an already-approved question. /// /// Two rules keep the pair unfarmable, one per side of the transition. /// @@ -144,56 +92,56 @@ pub async fn list_visible_to(db: &Database, user: &UserId) -> Result Result, AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $done = (UPDATE $q SET status = $approved, approved_by = $by - WHERE status = $pending RETURN AFTER); - IF array::len($done) > 0 AND $done[0].asker != $by {{ - UPDATE $by SET - {POOL_APPROVED_TOTAL_FIELD} = ({POOL_APPROVED_TOTAL_FIELD} ?? 0) + 1; - LET $asker = $done[0].asker; - UPDATE $asker SET - {POOL_PUBLISHED_TOTAL_FIELD} = ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0) + 1; - }}; - RETURN $done; - COMMIT TRANSACTION;" - ), - &[ - ("q".into(), id.record().into_value()), - ("approved".into(), STATUS_APPROVED.to_string().into_value()), - ("by".into(), approver.record().into_value()), - ("pending".into(), STATUS_PENDING.to_string().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, - // so its slot follows the statement count rather than a hand-kept - // number (`num_statements` counts `BEGIN` and `COMMIT` too, hence -2). - let slot = result.num_statements().saturating_sub(2); - Ok(result.take::>(slot)?.into_iter().next()) + tx_with_retry(db, false, async |tx| { + let approved = sqlx::query_as!( + PoolQuestion, + r#"UPDATE pool_question SET status = $2, approved_by = $3 + WHERE id = $1 AND status = $4 + RETURNING *"#, + *id, + STATUS_APPROVED, + approver, + STATUS_PENDING, + ) + .fetch_optional(tx) + .await?; + if let Some(question) = &approved { + if question.asker != *approver { + // The counter columns are NOT NULL DEFAULT 0 — the old + // absent-reads-as-zero coalesce is gone with the schema. + sqlx::query!( + "UPDATE app_user SET pool_approved_total = pool_approved_total + 1 + WHERE id = $1", + approver + ) + .execute(tx) + .await?; + sqlx::query!( + "UPDATE app_user SET pool_published_total = pool_published_total + 1 + WHERE id = $1", + question.asker + ) + .execute(tx) + .await?; + } + } + Ok(approved) + }) + .await } /// Point the question at a freshly written image blob. Guarded on @@ -202,6 +150,10 @@ pub async fn approve( /// loses the race gets `None` (and the caller takes the orphan blob back /// off disk). Returns the *before* row — its `image_file` is the replaced /// blob the caller must remove. +/// +/// The row lock makes the before-read and the guarded write one switch; a +/// racing approve either predates this transaction's snapshot or waits on +/// the lock, so a fresh image can never straddle an approval. pub async fn set_image( db: &Database, id: &PoolQuestionId, @@ -209,19 +161,35 @@ pub async fn set_image( content_type: &FileContentType, size: i64, ) -> Result, AppError> { - let mut result = db - .query( - "UPDATE $q SET image_file = $file, image_content_type = $ct, image_size = $size \ - WHERE status = $pending RETURN BEFORE", + tx_with_retry(db, false, async |tx| { + let before = sqlx::query_as!( + PoolQuestion, + "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE", + *id ) - .bind(("q", id.record())) - .bind(("file", file.to_string())) - .bind(("ct", content_type.clone())) - .bind(("size", size)) - .bind(("pending", STATUS_PENDING)) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + .fetch_optional(tx) + .await?; + let Some(before) = before else { + return Ok(None); + }; + let written = sqlx::query!( + r#"UPDATE pool_question + SET image_file = $2, image_content_type = $3, image_size = $4 + WHERE id = $1 AND status = $5"#, + *id, + file, + content_type, + size, + STATUS_PENDING, + ) + .execute(tx) + .await?; + if written.rows_affected() == 0 { + return Ok(None); + } + Ok(Some(before)) + }) + .await } /// Detach the question's image (pending only, like `set_image`). Returns @@ -230,16 +198,32 @@ pub async fn clear_image( db: &Database, id: &PoolQuestionId, ) -> Result, AppError> { - let mut result = db - .query( - "UPDATE $q SET image_file = NONE, image_content_type = NONE, image_size = NONE \ - WHERE status = $pending RETURN BEFORE", + tx_with_retry(db, false, async |tx| { + let before = sqlx::query_as!( + PoolQuestion, + "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE", + *id + ) + .fetch_optional(tx) + .await?; + let Some(before) = before else { + return Ok(None); + }; + let written = sqlx::query!( + r#"UPDATE pool_question + SET image_file = NULL, image_content_type = NULL, image_size = NULL + WHERE id = $1 AND status = $2"#, + *id, + STATUS_PENDING, ) - .bind(("q", id.record())) - .bind(("pending", STATUS_PENDING)) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + .execute(tx) + .await?; + if written.rows_affected() == 0 { + return Ok(None); + } + Ok(Some(before)) + }) + .await } /// Delete the question and its solutions in one transaction, returning @@ -247,34 +231,34 @@ pub async fn clear_image( /// caller can take every image blob off disk (solutions carry photos too, /// and a row-only sweep would strand theirs forever). /// -/// Rides the retry because a solution offer now writes this very row -/// ([`bump_question_and_write`]): the two contend by design, and a lost -/// round through a bare `check()` was a 500 for a delete that only had to -/// be re-sent. Admissible — a `DELETE` can never answer "already exists". +/// Children before the parent, so the foreign keys never refuse the parent +/// delete. `cascade = true` because a solution offer committing inside this +/// window makes the parent delete answer 23503 — a mid-cascade race the +/// retry loop re-runs, sweeping the latecomer with it. That foreign key is +/// also what keeps a solution from outliving its question on the insert +/// side, so the old existence-move transaction is simply gone. pub async fn delete( db: &Database, id: &PoolQuestionId, ) -> Result)>, AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - DELETE solution WHERE question = $q RETURN BEFORE; - DELETE $q RETURN BEFORE; - COMMIT TRANSACTION;", - &[("q".into(), id.record().into_value())], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN: the solution sweep is slot 1, the question slot 2. - let solutions = result.take::>(1)?; - Ok(result - .take::>(2)? - .into_iter() - .next() - .map(|question| (question, solutions))) + tx_with_retry(db, true, async |tx| { + let solutions = sqlx::query_as!( + Solution, + "DELETE FROM solution WHERE question = $1 RETURNING *", + *id + ) + .fetch_all(tx) + .await?; + let question = sqlx::query_as!( + PoolQuestion, + "DELETE FROM pool_question WHERE id = $1 RETURNING *", + *id + ) + .fetch_optional(tx) + .await?; + Ok(question.map(|question| (question, solutions))) + }) + .await } #[cfg(test)] diff --git a/src/db/solution.rs b/src/db/solution.rs index 8ab5938..e12c8ed 100644 --- a/src/db/solution.rs +++ b/src/db/solution.rs @@ -1,54 +1,54 @@ -//! The `solution` table: offers (through the pool question's -//! existence-move), the question-scoped reads and page, the grouped counts, +//! The `solution` table: offers (their question's existence enforced by the +//! real foreign key), the question-scoped read and page, the grouped counts, //! and the unconditional body/image writes of an unmoderated row. The pure //! entity and newtypes live in [`crate::domain::solution`]; the web layer //! reaches these through [`crate::service::solution`]. use std::collections::HashMap; -use surrealdb::types::{RecordId, SurrealValue}; - -use crate::database::Database; +use crate::database::{Database, tx_with_retry}; use crate::db::page::PagedList; -use crate::db::pool_question::bump_question_and_write; use crate::domain::note_file::FileContentType; use crate::domain::pool_question::PoolQuestionId; use crate::domain::solution::{Solution, SolutionBody, SolutionId}; use crate::error::AppError; -/// One `GROUP BY question` row of [`counts_for`]. -#[derive(SurrealValue)] -struct SolutionCount { - question: PoolQuestionId, - n: i64, -} - /// Offer the solution. `NotFound` = the question is gone, and nothing was -/// written: the create rides [`bump_question_and_write`], so the question's -/// existence is a *write* to its row rather than a read the handler made a -/// moment earlier — a bare create landing inside -/// [`crate::db::pool_question::delete`]'s -/// window was swept by nothing and left a solution no route could ever -/// reach or remove (every path to one goes through its question), photo -/// blob included. +/// written: the insert's foreign key (`solution_question_fkey`) refuses an +/// orphan the old existence-move transaction spent five statements dodging — +/// a bare create landing inside +/// [`crate::db::pool_question::delete`]'s window used to be swept by +/// nothing and left a solution no route could ever reach or remove (every +/// path to one goes through its question), photo blob included. /// -/// Re-sendable despite the `CREATE`: `$id` is a ULID minted once per call -/// on a table with no `UNIQUE` index, so a re-send cannot answer "already -/// exists" — the one thing the retry could not survive. +/// The author's own foreign key never fires in practice (the request +/// carries a live session user) and stays a database error if it ever does; +/// only the question's key maps to the 404. pub async fn insert(db: &Database, solution: Solution) -> Result { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - let (question, id) = (solution.question.clone(), solution.id.record()); - bump_question_and_write( - &question, - "CREATE $id CONTENT $solution", - vec![ - ("id".into(), id.into_value()), - ("solution".into(), solution.into_value()), - ], - db, + match sqlx::query_as!( + Solution, + r#"INSERT INTO solution (id, question, author, body, offered_at) + VALUES ($1, $2, $3, $4, $5) + RETURNING *"#, + solution.id, + solution.question, + solution.author, + solution.body, + solution.offered_at, ) - .await? - .ok_or_else(|| AppError::Internal("failed to create solution".into())) + .fetch_one(db) + .await + { + Ok(row) => Ok(row), + Err(err) if is_question_gone(&err) => Err(AppError::NotFound), + Err(err) => Err(err.into()), + } +} + +/// Did this insert fail on the *question* foreign key — the parent-gone +/// refusal — rather than some unrelated database fault? +fn is_question_gone(err: &sqlx::Error) -> bool { + err.as_database_error().and_then(|db| db.constraint()) == Some("solution_question_fkey") } /// Read a solution only if it belongs to `question` — keeps the nested @@ -58,32 +58,40 @@ pub async fn read_for( id: &SolutionId, question: &PoolQuestionId, ) -> Result, AppError> { - let solution: Option = db.select(id.record()).await?; - Ok(solution.filter(|solution| &solution.question == question)) + let row = sqlx::query_as!( + Solution, + "SELECT * FROM solution WHERE id = $1 AND question = $2", + id, + question + ) + .fetch_optional(db) + .await?; + Ok(row) } /// The question's solutions, oldest first — a discussion reads downward. /// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond -/// offers *stable* across re-queries, not insertion-ordered (ULID low bits -/// are random within a millisecond, so same-ms order is arbitrary). +/// offers *stable* across re-queries (the ids are write-ordered UUIDv7, so +/// same-ms rows still sort by mint order). pub async fn list_for( db: &Database, question: &PoolQuestionId, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { + // `.uuid()` feeds the builder its raw bind value — exact, typed. PagedList::new( - "solution WHERE question = $q", + "solution WHERE question = $1", "ORDER BY offered_at ASC, id ASC", ) - .bind("q", question.record()) + .bind(question.uuid()) .run(limit, offset, db) .await } /// Per-question solution tallies for a page of questions, in one grouped /// query — a per-row `count()` would cost a query per question. Keys are -/// question record keys; a question with no solutions has no entry, so +/// the questions' wire keys; a question with no solutions has no entry, so /// the caller reads misses as zero. pub async fn counts_for( db: &Database, @@ -92,18 +100,19 @@ pub async fn counts_for( if questions.is_empty() { return Ok(HashMap::new()); } - let ids: Vec = questions.iter().map(|question| question.record()).collect(); - let mut result = db - .query( - "SELECT question, count() AS n FROM solution WHERE question IN $qs GROUP BY question", - ) - .bind(("qs", ids)) - .await? - .check()?; - Ok(result - .take::>(0)? + let ids: Vec = questions.iter().copied().collect(); + let rows = sqlx::query!( + r#"SELECT question AS "question: PoolQuestionId", count(*) AS n + FROM solution + WHERE question = ANY($1) + GROUP BY question"#, + ids, + ) + .fetch_all(db) + .await?; + Ok(rows .into_iter() - .map(|row| (row.question.key().to_string(), row.n)) + .map(|row| (row.question.key(), row.n)) .collect()) } @@ -115,13 +124,15 @@ pub async fn set_body( id: &SolutionId, body: &SolutionBody, ) -> Result, AppError> { - let mut result = db - .query("UPDATE $s SET body = $b RETURN AFTER") - .bind(("s", id.record())) - .bind(("b", body.clone())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let row = sqlx::query_as!( + Solution, + "UPDATE solution SET body = $2 WHERE id = $1 RETURNING *", + id, + body + ) + .fetch_optional(db) + .await?; + Ok(row) } /// Point the solution at a freshly written image blob. Unconditional for @@ -129,6 +140,9 @@ pub async fn set_body( /// `image_file` is the replaced blob the caller must remove; `None` means /// the row was deleted mid-flight (the fresh blob is the caller's orphan /// to take back off disk). +/// +/// The row lock makes the before-read and the write one switch, so two +/// racing uploads can never both be told they replaced the same blob. pub async fn set_image( db: &Database, id: &SolutionId, @@ -136,33 +150,68 @@ pub async fn set_image( content_type: &FileContentType, size: i64, ) -> Result, AppError> { - let mut result = db - .query("UPDATE $s SET image_file = $file, image_content_type = $ct, image_size = $size RETURN BEFORE") - .bind(("s", id.record())) - .bind(("file", file.to_string())) - .bind(("ct", content_type.clone())) - .bind(("size", size)) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + tx_with_retry(db, false, async |tx| { + let before = sqlx::query_as!( + Solution, + "SELECT * FROM solution WHERE id = $1 FOR UPDATE", + *id + ) + .fetch_optional(tx) + .await?; + let Some(before) = before else { + return Ok(None); + }; + sqlx::query!( + r#"UPDATE solution + SET image_file = $2, image_content_type = $3, image_size = $4 + WHERE id = $1"#, + *id, + file, + content_type, + size, + ) + .execute(tx) + .await?; + Ok(Some(before)) + }) + .await } /// Detach the solution's image. Returns the *before* row — its /// `image_file` is the blob the caller must remove. pub async fn clear_image(db: &Database, id: &SolutionId) -> Result, AppError> { - let mut result = db - .query( - "UPDATE $s SET image_file = NONE, image_content_type = NONE, image_size = NONE \ - RETURN BEFORE", + tx_with_retry(db, false, async |tx| { + let before = sqlx::query_as!( + Solution, + "SELECT * FROM solution WHERE id = $1 FOR UPDATE", + *id + ) + .fetch_optional(tx) + .await?; + let Some(before) = before else { + return Ok(None); + }; + sqlx::query!( + r#"UPDATE solution + SET image_file = NULL, image_content_type = NULL, image_size = NULL + WHERE id = $1"#, + *id, ) - .bind(("s", id.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + .execute(tx) + .await?; + Ok(Some(before)) + }) + .await } pub async fn delete(db: &Database, solution: Solution) -> Result { - let deleted: Option = db.delete(solution.id.record()).await?; + let deleted = sqlx::query_as!( + Solution, + "DELETE FROM solution WHERE id = $1 RETURNING *", + solution.id + ) + .fetch_optional(db) + .await?; deleted.ok_or(AppError::NotFound) } diff --git a/src/web/questions.rs b/src/web/questions.rs index fbcb612..367ba17 100644 --- a/src/web/questions.rs +++ b/src/web/questions.rs @@ -482,7 +482,7 @@ async fn upload_image( let upload = read_image_upload(&st, &mut multipart).await?; let size = upload.size(); - let file = ulid::Ulid::generate().to_string(); + let file = crate::domain::monotonic_id::next_uuid().to_string(); store_blob(&st, &file, &upload.data, || async { match pool_question::set_image(&st.db, question.get_id(), &file, &upload.content_type, size) .await? @@ -808,7 +808,7 @@ async fn upload_solution_image( let upload = read_image_upload(&st, &mut multipart).await?; let size = upload.size(); - let file = ulid::Ulid::generate().to_string(); + let file = crate::domain::monotonic_id::next_uuid().to_string(); store_blob(&st, &file, &upload.data, || async { match solution::set_image(&st.db, solution.get_id(), &file, &upload.content_type, size) .await?