forge
Explore
Log in

Don't you dare go Hollow

🔀 merge: port bank+pool to sqlx/Postgres (L4)

Browse files at this commit

68db815723ba3bdf9ad7e82b9598166e4c3c80abAhmet Kaan GümüşParent: 761b1fbe12f993
src/db/bank_question.rsmodified+174 -187
@@ -7,10 +7,10 @@
77
88 use std::collections::HashMap;
99
10-use surrealdb::types::{RecordId, SurrealValue};
10+use sqlx::types::Json;
1111
12-use crate::constant::USAGE_COUNTS_SQL;
13-use crate::database::{Database, transaction_with_retry, write_with_retry};
12+use crate::database::{Database, tx_with_retry};
13+use crate::db::page::{PagedList, Param};
1414 use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility};
1515 use crate::domain::bank_question_image::BankQuestionImage;
1616 use crate::domain::exam::ExamId;
@@ -21,21 +21,6 @@ use crate::domain::timestamp::Timestamp;
2121 use crate::domain::user::UserId;
2222 use crate::error::AppError;
2323
24-/// One `GROUP BY from_bank` row of [`usage_counts`].
25-#[derive(SurrealValue)]
26-struct UsageCount {
27- from_bank: BankQuestionId,
28- n: i64,
29-}
30-
31-/// What one [`delete`] transaction removed — the template (an empty list once
32-/// someone else deleted it first) and the image rows swept with it.
33-#[derive(SurrealValue)]
34-struct DeleteOutcome {
35- question: Vec<BankQuestion>,
36- images: Vec<BankQuestionImage>,
37-}
38-
3924 pub async fn create(
4025 db: &Database,
4126 owner: UserId,
@@ -85,24 +70,52 @@ async fn insert(
8570 BankVisibility::default(),
8671 Timestamp::now(),
8772 );
88- let created: Option<BankQuestion> = db.create(question.id.record()).content(question).await?;
89- created.ok_or_else(|| AppError::Internal("failed to create bank question".into()))
73+ let row = sqlx::query_as!(
74+ BankQuestion,
75+ r#"INSERT INTO bank_question
76+ (id, owner, subject, text, kind, points, choices, correct,
77+ source_exam, visibility, created_at)
78+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
79+ RETURNING *"#,
80+ question.id,
81+ question.owner,
82+ question.subject,
83+ question.text,
84+ question.kind,
85+ question.points,
86+ question.choices,
87+ question.correct,
88+ question.source_exam,
89+ question.visibility,
90+ question.created_at,
91+ )
92+ .fetch_one(db)
93+ .await?;
94+ Ok(row)
9095 }
9196
9297 pub async fn read(db: &Database, id: &BankQuestionId) -> Result<Option<BankQuestion>, AppError> {
93- Ok(db.select(id.record()).await?)
98+ let row = sqlx::query_as!(
99+ BankQuestion,
100+ "SELECT * FROM bank_question WHERE id = $1",
101+ id
102+ )
103+ .fetch_optional(db)
104+ .await?;
105+ Ok(row)
94106 }
95107
96-/// One page of the bank the caller may see, **newest first** (ULID ids sort by
97-/// creation, so `id DESC` is newest-first) — plus the total row count under
98-/// the same filters, so a client can page past the window.
108+/// One page of the bank the caller may see, **newest first** (`id DESC` is
109+/// mint order — the ids are write-ordered UUIDv7) — plus the total row count
110+/// under the same filters, so a client can page past the window.
99111 ///
100-/// Every filter is a WHERE clause and the window is a real `LIMIT`/`START`:
101-/// the old version read the whole table and sliced it in memory, which hid
102-/// every template past the client's first page. `q` is a case- and
103-/// diacritic-insensitive fragment of the question text (blank = no text
104-/// filter): needle and column both go through
105-/// [`crate::domain::text_fold`], so `istanbul` finds `İSTANBUL` and back.
112+/// The window is a real `LIMIT`/`OFFSET` handed to the database (the
113+/// [`PagedList`] builder: the filters are runtime-conditional, which is that
114+/// builder's named exemption from the compile-time macros). `q` is a case-
115+/// and diacritic-insensitive fragment of the question text (blank = no text
116+/// filter): needle and column both go through [`crate::domain::text_fold`],
117+/// so `istanbul` finds `İSTANBUL` and back. `position` rather than `LIKE`
118+/// keeps the needle a *literal* substring — no `%`/`_` wildcard surprises.
106119 ///
107120 /// `visible_to` is the security filter, and it is a WHERE clause like every
108121 /// 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<Option<BankQuest
113126 /// `visibility` is the *user's* filter ("only mine" / "shared with the
114127 /// school") and is ANDed on top of that gate, so it can only ever narrow:
115128 /// `school` still hides another teacher's private rows, and `private`
116-/// intersected with the gate leaves exactly the caller's own drafts. It
117-/// joins the same `clauses` vec as the rest, so `total` honours it too —
118-/// a count that ignored it would break paging.
119-// Flat filter args, like every other `list` here — a builder struct for
120-// four `Option`s and a window would be more machinery than the call sites.
129+/// intersected with the gate leaves exactly the caller's own drafts. It is
130+/// part of the same WHERE, so `total` honours it too — a count that ignored
131+/// it would break paging.
132+///
133+/// The uuid filters bind raw through the id newtypes' [`crate::domain`]
134+/// `uuid()` accessor — [`Param::Uuid`] keeps the comparison exact, typed
135+/// rather than textual.
121136 #[allow(clippy::too_many_arguments)]
122137 pub async fn list(
123138 db: &Database,
@@ -130,70 +145,53 @@ pub async fn list(
130145 offset: i64,
131146 ) -> Result<(Vec<BankQuestion>, i64), AppError> {
132147 let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty());
133- let mut clauses = Vec::new();
134- if visible_to.is_some() {
135- clauses.push("(visibility = 'school' OR owner = $viewer)");
136- }
137- if visibility.is_some() {
138- clauses.push("visibility = $visibility");
139- }
140- if owner.is_some() {
141- clauses.push("owner = $owner");
142- }
143- if subject.is_some() {
144- clauses.push("subject = $subject");
145- }
146- let text_clause = format!("{} CONTAINS $q", search_fold_sql("text"));
147- if needle.is_some() {
148- clauses.push(text_clause.as_str());
149- }
150- let where_clause = if clauses.is_empty() {
151- "true".to_string()
152- } else {
153- clauses.join(" AND ")
154- };
155- // `START` alone (no `LIMIT`) is the unpaged case — `?limit` is opt-in.
156- let window = match limit {
157- Some(_) => "LIMIT $limit START $offset",
158- None => "START $offset",
159- };
160- // The count runs over the *same* WHERE, so `total` can never disagree
161- // with what paging through the list actually yields.
162- let mut query = db
163- .query(format!(
164- "SELECT * FROM bank_question WHERE {where_clause} ORDER BY id DESC {window};
165- SELECT VALUE count() FROM bank_question WHERE {where_clause} GROUP ALL;"
166- ))
167- .bind(("offset", offset));
148+ let mut clauses: Vec<String> = Vec::new();
149+ let mut binds: Vec<Param> = Vec::new();
168150 if let Some(viewer) = visible_to {
169- query = query.bind(("viewer", viewer.record()));
151+ binds.push(Param::Uuid(viewer.uuid()));
152+ clauses.push(format!(
153+ "(visibility = 'school' OR owner = ${})",
154+ binds.len()
155+ ));
170156 }
171157 if let Some(visibility) = visibility {
172- query = query.bind(("visibility", visibility.as_str().to_string()));
158+ binds.push(Param::Text(visibility.as_str().to_string()));
159+ clauses.push(format!("visibility = ${}", binds.len()));
173160 }
174161 if let Some(owner) = owner {
175- query = query.bind(("owner", owner.record()));
162+ binds.push(Param::Uuid(owner.uuid()));
163+ clauses.push(format!("owner = ${}", binds.len()));
176164 }
177165 if let Some(subject) = subject {
178- query = query.bind(("subject", subject.record()));
166+ binds.push(Param::Uuid(subject.uuid()));
167+ clauses.push(format!("subject = ${}", binds.len()));
179168 }
180169 if let Some(needle) = needle {
181- query = query.bind(("q", needle));
170+ binds.push(Param::Text(needle));
171+ clauses.push(format!(
172+ "position(${} in {}) > 0",
173+ binds.len(),
174+ search_fold_sql("text")
175+ ));
182176 }
183- if let Some(limit) = limit {
184- query = query.bind(("limit", limit));
177+ let from_where = if clauses.is_empty() {
178+ "bank_question WHERE true".to_string()
179+ } else {
180+ format!("bank_question WHERE {}", clauses.join(" AND "))
181+ };
182+ // The count runs over the *same* WHERE, so `total` can never disagree
183+ // with what paging through the list actually yields.
184+ let mut page = PagedList::new(from_where, "ORDER BY id DESC");
185+ for bind in binds {
186+ page = page.bind(bind);
185187 }
186- let mut result = query.await?.check()?;
187- let questions = result.take::<Vec<BankQuestion>>(0)?;
188- // `GROUP ALL` yields no row at all when nothing matched.
189- let total = result.take::<Vec<i64>>(1)?.first().copied().unwrap_or(0);
190- Ok((questions, total))
188+ page.run(limit, offset, db).await
191189 }
192190
193191 /// How many exam questions were instantiated from each of `ids` — the
194192 /// `from_bank` side of the provenance link, tallied for a whole page in
195193 /// **one** grouped query (a `count()` per row would be the N+1 this page
196-/// already had removed once). Keys are template record keys; a template
194+/// already had removed once). Keys are the templates' wire keys; a template
197195 /// nobody ever used has no entry at all, so the caller reads a miss as
198196 /// zero — and the UI can stay quiet rather than print "0".
199197 ///
@@ -207,16 +205,22 @@ pub async fn usage_counts(
207205 if ids.is_empty() {
208206 return Ok(HashMap::new());
209207 }
210- let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect();
211- let mut result = db
212- .query(USAGE_COUNTS_SQL)
213- .bind(("ids", records))
214- .await?
215- .check()?;
216- Ok(result
217- .take::<Vec<UsageCount>>(0)?
208+ let ids: Vec<BankQuestionId> = ids.iter().map(|id| (*id).clone()).collect();
209+ let rows = sqlx::query!(
210+ r#"SELECT from_bank AS "from_bank: BankQuestionId", count(*) AS n
211+ FROM exam_question
212+ WHERE from_bank = ANY($1)
213+ GROUP BY from_bank"#,
214+ ids,
215+ )
216+ .fetch_all(db)
217+ .await?;
218+ Ok(rows
218219 .into_iter()
219- .map(|row| (row.from_bank.key().to_string(), row.n))
220+ .filter_map(|row| {
221+ let n = row.n;
222+ row.from_bank.map(|from_bank| (from_bank.key(), n))
223+ })
220224 .collect())
221225 }
222226
@@ -228,22 +232,13 @@ pub async fn usage_counts(
228232 /// field is re-stated from the snapshot, and the kind/choices/correct trio
229233 /// has to be (a text-only edit re-submits the stored options *with their
230234 /// ids* so each keeps its picture) — so without the compare-and-set the
231-/// later writer silently reverts the earlier one — and the window is a
232-/// database round trip wide, which is exactly how far apart two concurrent
233-/// requests to this one process can sit.
235+/// later writer silently reverts the earlier one.
234236 ///
235237 /// Every field the merge re-states is in the guard, which is the same list
236-/// the `SET` writes. `choices` is compared whole: its objects carry two
237-/// required string keys, so none is ever dropped for being `NONE` (the trap
238-/// [`crate::db::settings::save_if_unchanged`] works around).
239-///
240-/// Rides [`write_with_retry`] because an image write now moves this row too
241-/// ([`crate::db::bank_question_image::upsert`]): an upload landing in the
242-/// same instant makes the store answer "conflict, retry", and a bare
243-/// `check()` would turn that into a 500 for an edit that only had to be
244-/// re-sent. A lost round writes nothing, and the guard is re-evaluated on
245-/// the next one, so a genuine stale merge still comes back as `None`.
246-/// Admissible: an `UPDATE` can never answer "already exists".
238+/// the `SET` writes; the nullable ones compare `IS NOT DISTINCT FROM`, so an
239+/// absent subject/correct/choices guards truthfully. Postgres needs no retry
240+/// loop around this: the guard re-evaluates on the row lock at execution, so
241+/// a rival write either predates this statement's snapshot or loses its own.
247242 pub async fn update_if_unchanged(
248243 db: &Database,
249244 expected: BankQuestion,
@@ -254,42 +249,40 @@ pub async fn update_if_unchanged(
254249 visibility: BankVisibility,
255250 ) -> Result<Option<BankQuestion>, AppError> {
256251 let (kind, choices, correct) = spec.into_parts();
257- let rows: Vec<BankQuestion> = write_with_retry(
258- db,
259- "UPDATE $id SET subject = $subject, text = $text, points = $points,
260- kind = $kind, choices = $choices, correct = $correct,
261- visibility = $visibility
262- WHERE subject = $was_subject AND text = $was_text
263- AND points = $was_points AND kind = $was_kind
264- AND choices = $was_choices AND correct = $was_correct
265- AND visibility = $was_visibility
266- RETURN AFTER",
267- &[
268- (
269- "was_subject".into(),
270- expected.subject.clone().map(|s| s.record()).into_value(),
271- ),
272- ("was_text".into(), expected.text.clone().into_value()),
273- ("was_points".into(), expected.points.into_value()),
274- ("was_kind".into(), expected.kind.clone().into_value()),
275- ("was_choices".into(), expected.choices.clone().into_value()),
276- ("was_correct".into(), expected.correct.clone().into_value()),
277- (
278- "was_visibility".into(),
279- expected.visibility.clone().into_value(),
280- ),
281- ("id".into(), expected.id.record().into_value()),
282- ("subject".into(), subject.map(|s| s.record()).into_value()),
283- ("text".into(), text.into_value()),
284- ("points".into(), points.into_value()),
285- ("kind".into(), kind.into_value()),
286- ("choices".into(), choices.into_value()),
287- ("correct".into(), correct.into_value()),
288- ("visibility".into(), visibility.into_value()),
289- ],
252+ let choices = choices.map(Json);
253+ let row = sqlx::query_as!(
254+ BankQuestion,
255+ r#"UPDATE bank_question SET
256+ subject = $2, text = $3, points = $4, kind = $5,
257+ choices = $6, correct = $7, visibility = $8
258+ WHERE id = $1
259+ AND subject IS NOT DISTINCT FROM $9
260+ AND text = $10
261+ AND points = $11
262+ AND kind = $12
263+ AND choices IS NOT DISTINCT FROM $13
264+ AND correct IS NOT DISTINCT FROM $14
265+ AND visibility = $15
266+ RETURNING *"#,
267+ expected.id,
268+ subject,
269+ text,
270+ points,
271+ kind,
272+ choices,
273+ correct,
274+ visibility,
275+ expected.subject,
276+ expected.text,
277+ expected.points,
278+ expected.kind,
279+ expected.choices,
280+ expected.correct,
281+ expected.visibility,
290282 )
283+ .fetch_optional(db)
291284 .await?;
292- Ok(rows.into_iter().next())
285+ Ok(row)
293286 }
294287
295288 /// Delete the template and cascade-remove its bank images, so none points
@@ -297,59 +290,53 @@ pub async fn update_if_unchanged(
297290 /// actually removed come back with it: the blobs are the web layer's to
298291 /// take off disk, but only for *these* rows — an upload that committed
299292 /// after the caller listed the template's images is swept here too, and a
300-/// pre-read snapshot would strand its blob for good
301-/// ([`crate::db::note::delete`]'s story, this domain over).
302-///
303-/// Children first, in one transaction: as two queries, a failure between
304-/// them left image rows swept under a template that survived, or (the other
305-/// order) a template gone with its images still there. Rides the retry
306-/// because an image write now moves this very row
307-/// ([`crate::db::bank_question_image::upsert`]) — the two contend by
308-/// design, and a lost round through a bare `check()` would be a 500 for a
309-/// delete that only had to be re-sent. Admissible: no `UPDATE` or `DELETE`
310-/// in here can answer "already exists".
293+/// pre-read snapshot would strand its blob for good.
311294 ///
312-/// Exam questions tied to this template keep living: only their provenance
313-/// links are cleared, field-scoped (never a whole-row save — the question
314-/// isn't ours and may be edited concurrently), so nothing can read a link to
315-/// a template that no longer exists. *Both* directions point at a template,
316-/// so both are cleared: `from_bank` on the questions instantiated from it,
317-/// and `banked_as` on the question it was saved out of.
295+/// All four statements are one transaction, children before the parent so
296+/// the foreign keys never refuse the parent delete: the provenance links
297+/// clear first (exam questions tied to this template keep living — only the
298+/// links go, field-scoped, in both directions: `from_bank` on the questions
299+/// instantiated from it and `banked_as` on the question it was saved out
300+/// of), then the image sweep, then the row. `cascade = true` because an
301+/// image upsert committing inside this window makes the parent delete
302+/// answer 23503 — a mid-cascade race the retry loop re-runs, sweeping the
303+/// latecomer with it.
318304 pub async fn delete(
319305 db: &Database,
320306 target: BankQuestion,
321307 ) -> Result<(BankQuestion, Vec<BankQuestionImage>), AppError> {
322- let (mut result, mut errors) = transaction_with_retry(
323- db,
324- "BEGIN TRANSACTION;
325- LET $images = (DELETE bank_question_image WHERE bank_question = $b RETURN BEFORE);
326- UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b;
327- UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b;
328- LET $gone = (DELETE $b RETURN BEFORE);
329- RETURN { question: $gone, images: $images };
330- COMMIT TRANSACTION;",
331- &[("b".into(), target.id.record().into_value())],
332- &[],
333- )
334- .await?;
335- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
336- return Err(error.into());
337- }
338- // The trailing `RETURN` is the last statement before `COMMIT`, so its
339- // slot follows the statement count rather than a hand-kept number;
340- // `num_statements` counts BEGIN and COMMIT.
341- let slot = result.num_statements().saturating_sub(2);
342- let outcome = result
343- .take::<Vec<DeleteOutcome>>(slot)?
344- .into_iter()
345- .next()
346- .ok_or_else(|| AppError::Internal("failed to delete bank question".into()))?;
347- let question = outcome
348- .question
349- .into_iter()
350- .next()
308+ tx_with_retry(db, true, async |tx| {
309+ let id = target.id.clone();
310+ sqlx::query!(
311+ "UPDATE exam_question SET from_bank = NULL WHERE from_bank = $1",
312+ id
313+ )
314+ .execute(tx)
315+ .await?;
316+ sqlx::query!(
317+ "UPDATE exam_question SET banked_as = NULL WHERE banked_as = $1",
318+ id
319+ )
320+ .execute(tx)
321+ .await?;
322+ let images = sqlx::query_as!(
323+ BankQuestionImage,
324+ "DELETE FROM bank_question_image WHERE bank_question = $1 RETURNING *",
325+ id
326+ )
327+ .fetch_all(tx)
328+ .await?;
329+ let question = sqlx::query_as!(
330+ BankQuestion,
331+ "DELETE FROM bank_question WHERE id = $1 RETURNING *",
332+ id
333+ )
334+ .fetch_optional(tx)
335+ .await?
351336 .ok_or(AppError::NotFound)?;
352- Ok((question, outcome.images))
337+ Ok((question, images))
338+ })
339+ .await
353340 }
354341
355342 #[cfg(test)]
src/db/bank_question_image.rsmodified+104 -117
@@ -1,105 +1,69 @@
1-//! The `bank_question_image` slot table: the per-slot upsert that pins the
2-//! template's existence into its own transaction, the page-wide listing, and
3-//! the choice sweep a non-destructive PATCH runs. Blob I/O stays in the web
4-//! layer; the pure entity and newtypes in
1+//! The `bank_question_image` slot table: the per-slot upsert, the page-wide
2+//! listing, and the choice sweep a non-destructive PATCH runs. Blob I/O
3+//! stays in the web layer; the pure entity and newtypes in
54 //! [`crate::domain::bank_question_image`].
65
7-use surrealdb::types::{RecordId, SurrealValue};
8-
9-use crate::database::{Database, transaction_with_retry};
6+use crate::database::{Database, foreign_key_violation, tx_with_retry};
107 use crate::domain::bank_question::BankQuestionId;
11-use crate::domain::bank_question_image::{BankQuestionImage, BankQuestionImageId};
8+use crate::domain::bank_question_image::BankQuestionImage;
129 use crate::domain::exam_question::ChoiceId;
1310 use crate::error::AppError;
1411
15-/// What one [`upsert`] transaction returns: the row it
16-/// stored and the blob name it replaced. Both are arrays because SurrealDB
17-/// drops an object key valued `NONE` on the way out, while an empty array
18-/// survives — "nothing was replaced" has to be readable, not missing.
19-#[derive(SurrealValue)]
20-struct UpsertOutcome {
21- stored: Vec<BankQuestionImage>,
22- replaced: Vec<String>,
23-}
24-
25-/// Create or replace the slot's image row — the deterministic id makes this
26-/// the whole "one image per slot" story — handing back what it stored plus
27-/// the blob name it replaced, for the caller to take off disk.
28-///
29-/// Both halves are the transaction's doing. The template's own `points` is
30-/// moved and put straight back inside it, the way
31-/// [`crate::db::pool_question::bump_question_and_write`] moves
32-/// `asked_at` (`created_at` is `READONLY`, so the move goes on the one other
33-/// int column): that makes the template's *existence* part of this write.
34-/// A bare `UPSERT` guarded by having read the template first does not
35-/// survive its delete window — the read sees a row
36-/// [`crate::db::bank_question::delete`] has removed but
37-/// not committed, while that delete's image sweep ran on a snapshot
38-/// predating this row, so both commit and the image outlives the template
39-/// it hangs on. Nothing could ever read, delete, or sweep it afterwards:
40-/// every image route goes through the template. Moving the value makes the
41-/// two transactions touch one key, so the store refuses a side; writing the
42-/// same value back would be elided and collide with nothing.
12+/// Create or replace the slot's image row — the table's `NULLS NOT DISTINCT`
13+/// unique key makes this the whole "one image per slot" story — handing back
14+/// what it stored plus the blob name it replaced, for the caller to take off
15+/// disk.
4316 ///
44-/// The replaced blob name comes out of this same transaction rather than a
45-/// read in front of it (the shape
46-/// [`crate::db::pool_question::set_image`] has): two
47-/// uploads to one slot both write this row, so they contend and the loser
48-/// re-reads the winner's blob name, where two pre-reads both saw the *old*
49-/// blob and left the loser's fresh one orphaned on disk.
17+/// Both halves are the transaction's doing, and the row lock makes them one
18+/// switch: two uploads racing on one slot serialize on the `FOR UPDATE`, and
19+/// the loser's `ON CONFLICT` re-reads the winner's row, where two unlocked
20+/// pre-reads would both have seen the *old* blob name and left the loser's
21+/// fresh one orphaned on disk.
5022 ///
51-/// Admissible for [`transaction_with_retry`]: the `UPSERT`'s id is
52-/// deterministic per (question, slot) and the table carries no `UNIQUE`
53-/// index, so the write always resolves onto the row its id names and can
54-/// never answer "already exists".
23+/// The template's existence rides the real foreign key: an insert whose
24+/// template was deleted mid-flight answers 23503 and maps to the same 404
25+/// the old points-move transaction produced with its `THROW`. Nothing is
26+/// written either way.
5527 pub async fn upsert(
5628 db: &Database,
5729 image: BankQuestionImage,
5830 ) -> Result<(BankQuestionImage, Option<String>), AppError> {
59- // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic
60- let (question, id) = (image.bank_question.record(), image.id.record());
61- let (mut result, mut errors) = transaction_with_retry(
62- db,
63- "BEGIN TRANSACTION;
64- LET $was_points = (SELECT VALUE points FROM ONLY $b);
65- LET $bumped = (UPDATE $b SET points = points + 1 RETURN VALUE id);
66- IF array::len($bumped) = 0 { THROW 'no_question' };
67- UPDATE $b SET points = $was_points;
68- LET $replaced = (SELECT VALUE file FROM $id);
69- LET $stored = (UPSERT $id CONTENT $image);
70- RETURN { stored: $stored, replaced: $replaced };
71- COMMIT TRANSACTION;",
72- &[
73- ("b".into(), question.into_value()),
74- ("id".into(), id.into_value()),
75- ("image".into(), image.into_value()),
76- ],
77- &["no_question"],
78- )
79- .await?;
80- // An aborted transaction errors *every* slot, most with a generic "not
81- // executed" — only the THROW's own slot names the reason.
82- if errors
83- .values()
84- .any(|error| error.to_string().contains("no_question"))
85- {
86- return Err(AppError::NotFound);
87- }
88- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
89- return Err(error.into());
90- }
91- // The trailing `RETURN` is the last statement before `COMMIT`, so its
92- // slot follows the statement count rather than a hand-kept number;
93- // `num_statements` counts BEGIN and COMMIT.
94- let slot = result.num_statements().saturating_sub(2);
95- let failed = || AppError::Internal("failed to store bank question image".into());
96- let outcome = result
97- .take::<Vec<UpsertOutcome>>(slot)?
98- .into_iter()
99- .next()
100- .ok_or_else(failed)?;
101- let stored = outcome.stored.into_iter().next().ok_or_else(failed)?;
102- Ok((stored, outcome.replaced.into_iter().next()))
31+ tx_with_retry(db, false, async |tx| {
32+ let was = sqlx::query!(
33+ r#"SELECT file FROM bank_question_image
34+ WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2
35+ FOR UPDATE"#,
36+ image.bank_question.clone(),
37+ image.slot.clone(),
38+ )
39+ .fetch_optional(tx)
40+ .await?
41+ .map(|row| row.file);
42+ let stored = match sqlx::query_as!(
43+ BankQuestionImage,
44+ r#"INSERT INTO bank_question_image
45+ (bank_question, slot, file, content_type, size)
46+ VALUES ($1, $2, $3, $4, $5)
47+ ON CONFLICT (bank_question, slot) DO UPDATE
48+ SET file = $3, content_type = $4, size = $5
49+ RETURNING *"#,
50+ image.bank_question.clone(),
51+ image.slot.clone(),
52+ image.file.clone(),
53+ image.content_type,
54+ image.size,
55+ )
56+ .fetch_one(tx)
57+ .await
58+ {
59+ Ok(row) => row,
60+ // The template row is gone; no orphan image may outlive it.
61+ Err(err) if foreign_key_violation(&err) => return Err(AppError::NotFound),
62+ Err(err) => return Err(err.into()),
63+ };
64+ Ok((stored, was))
65+ })
66+ .await
10367 }
10468
10569 pub async fn read_slot(
@@ -107,21 +71,30 @@ pub async fn read_slot(
10771 question: &BankQuestionId,
10872 slot: Option<&ChoiceId>,
10973 ) -> Result<Option<BankQuestionImage>, AppError> {
110- Ok(db
111- .select(BankQuestionImageId::for_slot(question, slot).record())
112- .await?)
74+ let row = sqlx::query_as!(
75+ BankQuestionImage,
76+ r#"SELECT * FROM bank_question_image
77+ WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2"#,
78+ question,
79+ slot.cloned(),
80+ )
81+ .fetch_optional(db)
82+ .await?;
83+ Ok(row)
11384 }
11485
11586 pub async fn list_for_question(
11687 db: &Database,
11788 question: &BankQuestionId,
11889 ) -> Result<Vec<BankQuestionImage>, AppError> {
119- let mut result = db
120- .query("SELECT * FROM bank_question_image WHERE bank_question = $b")
121- .bind(("b", question.record()))
122- .await?
123- .check()?;
124- Ok(result.take::<Vec<BankQuestionImage>>(0)?)
90+ let rows = sqlx::query_as!(
91+ BankQuestionImage,
92+ "SELECT * FROM bank_question_image WHERE bank_question = $1",
93+ question
94+ )
95+ .fetch_all(db)
96+ .await?;
97+ Ok(rows)
12598 }
12699
127100 /// The image rows of several templates in one query — for bucketing onto a
@@ -133,13 +106,15 @@ pub async fn list_for_questions(
133106 if questions.is_empty() {
134107 return Ok(Vec::new());
135108 }
136- let records: Vec<RecordId> = questions.iter().map(|q| q.record()).collect();
137- let mut result = db
138- .query("SELECT * FROM bank_question_image WHERE bank_question IN $ids")
139- .bind(("ids", records))
140- .await?
141- .check()?;
142- Ok(result.take::<Vec<BankQuestionImage>>(0)?)
109+ let ids: Vec<BankQuestionId> = questions.iter().map(|q| (*q).clone()).collect();
110+ let rows = sqlx::query_as!(
111+ BankQuestionImage,
112+ "SELECT * FROM bank_question_image WHERE bank_question = ANY($1)",
113+ ids
114+ )
115+ .fetch_all(db)
116+ .await?;
117+ Ok(rows)
143118 }
144119
145120 /// Drop the option pictures whose choice is gone — every choice image of
@@ -157,23 +132,35 @@ pub async fn delete_choices_not_in(
157132 keep: &[ChoiceId],
158133 ) -> Result<Vec<BankQuestionImage>, AppError> {
159134 let keep: Vec<String> = keep.iter().map(|id| id.as_str().to_string()).collect();
160- let mut result = db
161- .query(
162- "DELETE bank_question_image \
163- WHERE bank_question = $b AND slot != NONE AND slot NOT IN $keep RETURN BEFORE",
164- )
165- .bind(("b", question.record()))
166- .bind(("keep", keep))
167- .await?
168- .check()?;
169- Ok(result.take::<Vec<BankQuestionImage>>(0)?)
135+ let rows = sqlx::query_as!(
136+ BankQuestionImage,
137+ r#"DELETE FROM bank_question_image
138+ WHERE bank_question = $1
139+ AND slot IS NOT NULL
140+ AND NOT (slot = ANY($2))
141+ RETURNING *"#,
142+ question,
143+ keep
144+ )
145+ .fetch_all(db)
146+ .await?;
147+ Ok(rows)
170148 }
171149
172150 pub async fn delete(
173151 db: &Database,
174152 image: BankQuestionImage,
175153 ) -> Result<BankQuestionImage, AppError> {
176- let deleted: Option<BankQuestionImage> = db.delete(image.id.record()).await?;
154+ let deleted = sqlx::query_as!(
155+ BankQuestionImage,
156+ r#"DELETE FROM bank_question_image
157+ WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2
158+ RETURNING *"#,
159+ image.bank_question,
160+ image.slot
161+ )
162+ .fetch_optional(db)
163+ .await?;
177164 deleted.ok_or(AppError::NotFound)
178165 }
179166
src/db/pool_question.rsmodified+176 -192
@@ -1,137 +1,85 @@
11 //! The `pool_question` table: ask/insert, the two listings, the guarded
22 //! approve that rides the publish counters along, the pending-only image
3-//! writes, and the delete that cascades solutions — plus
4-//! [`bump_question_and_write`], the existence-move every child write goes
5-//! through. The pure entity and newtypes live in
6-//! [`crate::domain::pool_question`]; the web layer reaches these through
7-//! [`crate::service::pool_question`].
8-
9-use surrealdb::types::SurrealValue;
10-
11-use crate::constant::{
12- POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, STATUS_APPROVED, STATUS_PENDING,
13-};
14-use crate::database::{Database, transaction_with_retry};
3+//! writes, and the delete that cascades solutions. The pure entity and
4+//! newtypes live in [`crate::domain::pool_question`]; the web layer reaches
5+//! these through [`crate::service::pool_question`].
6+
7+use crate::constant::{STATUS_APPROVED, STATUS_PENDING};
8+use crate::database::{Database, tx_with_retry};
159 use crate::domain::note_file::FileContentType;
1610 use crate::domain::pool_question::{PoolQuestion, PoolQuestionId};
1711 use crate::domain::solution::Solution;
1812 use crate::domain::user::UserId;
1913 use crate::error::AppError;
2014
21-/// Move the question's `asked_at` **and** run `statement` — a write to
22-/// something hanging off a question — in one transaction, handing back the row
23-/// it returned. `NotFound` means the question is gone and nothing was written.
24-///
25-/// The move is what makes the question's **existence** part of the child's own
26-/// write, the way [`crate::domain::menu::bump_menu_and_write`] does for a menu:
27-/// the `UPDATE` matches nothing once the row is deleted, and a delete racing
28-/// this one touches the very key this transaction writes, so the two cannot
29-/// both commit. Reading the question first does *not* survive that race — the
30-/// read sees a row [`delete`] has removed but not committed, while its
31-/// `DELETE solution WHERE question = $q` ran on a snapshot predating this
32-/// insert, so both commit and the child outlives its question with neither
33-/// caller told anything.
34-///
35-/// `asked_at` rather than a revision column because this row carries no counter
36-/// to bump and must not grow one for this alone. It is put back *by captured
37-/// value* in the same transaction, so nothing outside ever observes the move
38-/// and the row is byte-identical afterwards (the pool lists order on it).
39-/// Writing the same value would buy nothing: an `UPDATE` that leaves the
40-/// document unchanged is elided and never reaches the store's write set, so it
41-/// collides with nothing.
42-///
43-/// Admissible for [`transaction_with_retry`] as long as `statement` is: the
44-/// `UPDATE`s, `SELECT`, `IF`/`THROW` and `RETURN` can never answer "already
45-/// exists".
46-pub(crate) async fn bump_question_and_write<T: SurrealValue>(
47- question: &PoolQuestionId,
48- statement: &str,
49- mut bindings: Vec<(String, surrealdb::types::Value)>,
50- db: &Database,
51-) -> Result<Option<T>, AppError> {
52- bindings.push(("q".into(), question.record().into_value()));
53- let (mut result, mut errors) = transaction_with_retry(
54- db,
55- &format!(
56- "BEGIN TRANSACTION;
57- LET $was_asked = (SELECT VALUE asked_at FROM ONLY $q);
58- LET $bumped = (UPDATE $q SET asked_at = asked_at + 1 RETURN VALUE id);
59- IF array::len($bumped) = 0 {{ THROW 'no_question' }};
60- UPDATE $q SET asked_at = $was_asked;
61- LET $row = ({statement});
62- RETURN $row;
63- COMMIT TRANSACTION;"
64- ),
65- &bindings,
66- &["no_question"],
15+pub async fn insert(db: &Database, question: PoolQuestion) -> Result<PoolQuestion, AppError> {
16+ let row = sqlx::query_as!(
17+ PoolQuestion,
18+ r#"INSERT INTO pool_question (id, asker, title, body, status, asked_at)
19+ VALUES ($1, $2, $3, $4, $5, $6)
20+ RETURNING *"#,
21+ question.id,
22+ question.asker,
23+ question.title,
24+ question.body,
25+ question.status,
26+ question.asked_at,
6727 )
28+ .fetch_one(db)
6829 .await?;
69- // An aborted transaction errors *every* slot, most with a generic "not
70- // executed" — only the THROW's own slot names the reason.
71- if errors
72- .values()
73- .any(|error| error.to_string().contains("no_question"))
74- {
75- return Err(AppError::NotFound);
76- }
77- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
78- return Err(error.into());
79- }
80- // The trailing `RETURN` is the last statement before `COMMIT`, so its slot
81- // follows the statement count rather than a hand-kept number;
82- // `num_statements` counts BEGIN and COMMIT.
83- let slot = result.num_statements().saturating_sub(2);
84- Ok(result.take::<Vec<T>>(slot)?.into_iter().next())
85-}
86-
87-pub async fn insert(db: &Database, question: PoolQuestion) -> Result<PoolQuestion, AppError> {
88- // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber
89- let created: Option<PoolQuestion> = db.create(question.id.record()).content(question).await?;
90- created.ok_or_else(|| AppError::Internal("failed to create pool question".into()))
30+ Ok(row)
9131 }
9232
9333 pub async fn read(db: &Database, id: &PoolQuestionId) -> Result<Option<PoolQuestion>, AppError> {
94- Ok(db.select(id.record()).await?)
34+ let row = sqlx::query_as!(
35+ PoolQuestion,
36+ "SELECT * FROM pool_question WHERE id = $1",
37+ id
38+ )
39+ .fetch_optional(db)
40+ .await?;
41+ Ok(row)
9542 }
9643
9744 /// Every question, newest first — the teacher+ view (approval queue and
9845 /// pool in one list).
9946 pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> {
100- let mut result = db
101- .query("SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC")
102- .await?
103- .check()?;
104- Ok(result.take::<Vec<PoolQuestion>>(0)?)
47+ let rows = sqlx::query_as!(
48+ PoolQuestion,
49+ "SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC",
50+ )
51+ .fetch_all(db)
52+ .await?;
53+ Ok(rows)
10554 }
10655
10756 /// The pool as a non-staff user sees it, newest first: every approved
10857 /// question, plus the caller's own pending ones.
10958 pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQuestion>, AppError> {
110- let mut result = db
111- .query(
112- "SELECT * FROM pool_question WHERE status = $approved OR asker = $usr \
113- ORDER BY asked_at DESC, id DESC",
114- )
115- .bind(("approved", STATUS_APPROVED))
116- .bind(("usr", user.record()))
117- .await?
118- .check()?;
119- Ok(result.take::<Vec<PoolQuestion>>(0)?)
59+ let rows = sqlx::query_as!(
60+ PoolQuestion,
61+ r#"SELECT * FROM pool_question
62+ WHERE status = $1 OR asker = $2
63+ ORDER BY asked_at DESC, id DESC"#,
64+ STATUS_APPROVED,
65+ user
66+ )
67+ .fetch_all(db)
68+ .await?;
69+ Ok(rows)
12070 }
12171
12272 /// Publish a pending question into the pool, stamping who approved it.
123-/// The `WHERE status = $pending` guard makes the transition atomic: of two
73+/// The `WHERE status = 'pending'` guard makes the transition atomic: of two
12474 /// racing approvals exactly one wins, and an approve can never land on a
12575 /// question deleted mid-flight. `None` = the question wasn't pending
12676 /// (already approved, or gone) — the caller sorts out which.
12777 ///
128-/// Two lifetime badge counters ride that same guard, inside this
78+/// Two lifetime badge counters ride that same guard inside this
12979 /// transaction: the approver's `pool_approved_total` and the *asker's*
130-/// `pool_published_total`. Both hang off `array::len($done) > 0` — the
131-/// guard's own verdict — so the pair moves once per real transition and
132-/// never on a second approve of an already-approved question.
133-/// (`count ?? 0 > 0` misparses here; `array::len` is the spelling that
134-/// holds.) The second conjunct is the self-approval rule below.
80+/// `pool_published_total`. Both move only when the guard's own verdict
81+/// landed, so the pair moves once per real transition and never on a second
82+/// approve of an already-approved question.
13583 ///
13684 /// Two rules keep the pair unfarmable, one per side of the transition.
13785 ///
@@ -144,56 +92,56 @@ pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQue
14492 ///
14593 /// And a *self*-approval — a teacher+ approving a question they asked
14694 /// themselves, which the route deliberately still allows — moves neither
147-/// counter, hence the `$done[0].asker != $by` half of the condition. It is
148-/// the same farm from the other end (ask, approve, delete, repeat, with no
149-/// second person involved), and the two together are why a counter can only
150-/// move when one person's work was judged by another's. Nothing else about
151-/// a self-approval changes: same 200, same freeze, same stamp — this skips
152-/// the credit, not the approval.
95+/// counter. It is the same farm from the other end (ask, approve, delete,
96+/// repeat, with no second person involved), and the two together are why a
97+/// counter can only move when one person's work was judged by another's.
98+/// Nothing else about a self-approval changes: same 200, same freeze, same
99+/// stamp — this skips the credit, not the approval.
153100 ///
154-/// Re-sent while the store answers "conflict, retry": the guard reads a
155-/// column a rival approve writes, and both counters sit on user rows every
156-/// other counter site writes too. Sound to re-send — every statement is an
157-/// `UPDATE`, none of which can legitimately answer "already exists" — and a
158-/// lost round aborts having written nothing, increments included.
101+/// Rides the retry loop because the counter bumps lock user rows every
102+/// other counter site writes too; a deadlock between two approvals takes a
103+/// round and lands the next attempt.
159104 pub async fn approve(
160105 db: &Database,
161106 id: &PoolQuestionId,
162107 approver: &UserId,
163108 ) -> Result<Option<PoolQuestion>, AppError> {
164- let (mut result, mut errors) = transaction_with_retry(
165- db,
166- &format!(
167- "BEGIN TRANSACTION;
168- LET $done = (UPDATE $q SET status = $approved, approved_by = $by
169- WHERE status = $pending RETURN AFTER);
170- IF array::len($done) > 0 AND $done[0].asker != $by {{
171- UPDATE $by SET
172- {POOL_APPROVED_TOTAL_FIELD} = ({POOL_APPROVED_TOTAL_FIELD} ?? 0) + 1;
173- LET $asker = $done[0].asker;
174- UPDATE $asker SET
175- {POOL_PUBLISHED_TOTAL_FIELD} = ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0) + 1;
176- }};
177- RETURN $done;
178- COMMIT TRANSACTION;"
179- ),
180- &[
181- ("q".into(), id.record().into_value()),
182- ("approved".into(), STATUS_APPROVED.to_string().into_value()),
183- ("by".into(), approver.record().into_value()),
184- ("pending".into(), STATUS_PENDING.to_string().into_value()),
185- ],
186- &[],
187- )
188- .await?;
189- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
190- return Err(error.into());
191- }
192- // The trailing `RETURN` is always the last statement before `COMMIT`,
193- // so its slot follows the statement count rather than a hand-kept
194- // number (`num_statements` counts `BEGIN` and `COMMIT` too, hence -2).
195- let slot = result.num_statements().saturating_sub(2);
196- Ok(result.take::<Vec<PoolQuestion>>(slot)?.into_iter().next())
109+ tx_with_retry(db, false, async |tx| {
110+ let approved = sqlx::query_as!(
111+ PoolQuestion,
112+ r#"UPDATE pool_question SET status = $2, approved_by = $3
113+ WHERE id = $1 AND status = $4
114+ RETURNING *"#,
115+ *id,
116+ STATUS_APPROVED,
117+ approver,
118+ STATUS_PENDING,
119+ )
120+ .fetch_optional(tx)
121+ .await?;
122+ if let Some(question) = &approved {
123+ if question.asker != *approver {
124+ // The counter columns are NOT NULL DEFAULT 0 — the old
125+ // absent-reads-as-zero coalesce is gone with the schema.
126+ sqlx::query!(
127+ "UPDATE app_user SET pool_approved_total = pool_approved_total + 1
128+ WHERE id = $1",
129+ approver
130+ )
131+ .execute(tx)
132+ .await?;
133+ sqlx::query!(
134+ "UPDATE app_user SET pool_published_total = pool_published_total + 1
135+ WHERE id = $1",
136+ question.asker
137+ )
138+ .execute(tx)
139+ .await?;
140+ }
141+ }
142+ Ok(approved)
143+ })
144+ .await
197145 }
198146
199147 /// Point the question at a freshly written image blob. Guarded on
@@ -202,6 +150,10 @@ pub async fn approve(
202150 /// loses the race gets `None` (and the caller takes the orphan blob back
203151 /// off disk). Returns the *before* row — its `image_file` is the replaced
204152 /// blob the caller must remove.
153+///
154+/// The row lock makes the before-read and the guarded write one switch; a
155+/// racing approve either predates this transaction's snapshot or waits on
156+/// the lock, so a fresh image can never straddle an approval.
205157 pub async fn set_image(
206158 db: &Database,
207159 id: &PoolQuestionId,
@@ -209,19 +161,35 @@ pub async fn set_image(
209161 content_type: &FileContentType,
210162 size: i64,
211163 ) -> Result<Option<PoolQuestion>, AppError> {
212- let mut result = db
213- .query(
214- "UPDATE $q SET image_file = $file, image_content_type = $ct, image_size = $size \
215- WHERE status = $pending RETURN BEFORE",
164+ tx_with_retry(db, false, async |tx| {
165+ let before = sqlx::query_as!(
166+ PoolQuestion,
167+ "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE",
168+ *id
216169 )
217- .bind(("q", id.record()))
218- .bind(("file", file.to_string()))
219- .bind(("ct", content_type.clone()))
220- .bind(("size", size))
221- .bind(("pending", STATUS_PENDING))
222- .await?
223- .check()?;
224- Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next())
170+ .fetch_optional(tx)
171+ .await?;
172+ let Some(before) = before else {
173+ return Ok(None);
174+ };
175+ let written = sqlx::query!(
176+ r#"UPDATE pool_question
177+ SET image_file = $2, image_content_type = $3, image_size = $4
178+ WHERE id = $1 AND status = $5"#,
179+ *id,
180+ file,
181+ content_type,
182+ size,
183+ STATUS_PENDING,
184+ )
185+ .execute(tx)
186+ .await?;
187+ if written.rows_affected() == 0 {
188+ return Ok(None);
189+ }
190+ Ok(Some(before))
191+ })
192+ .await
225193 }
226194
227195 /// Detach the question's image (pending only, like `set_image`). Returns
@@ -230,16 +198,32 @@ pub async fn clear_image(
230198 db: &Database,
231199 id: &PoolQuestionId,
232200 ) -> Result<Option<PoolQuestion>, AppError> {
233- let mut result = db
234- .query(
235- "UPDATE $q SET image_file = NONE, image_content_type = NONE, image_size = NONE \
236- WHERE status = $pending RETURN BEFORE",
201+ tx_with_retry(db, false, async |tx| {
202+ let before = sqlx::query_as!(
203+ PoolQuestion,
204+ "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE",
205+ *id
206+ )
207+ .fetch_optional(tx)
208+ .await?;
209+ let Some(before) = before else {
210+ return Ok(None);
211+ };
212+ let written = sqlx::query!(
213+ r#"UPDATE pool_question
214+ SET image_file = NULL, image_content_type = NULL, image_size = NULL
215+ WHERE id = $1 AND status = $2"#,
216+ *id,
217+ STATUS_PENDING,
237218 )
238- .bind(("q", id.record()))
239- .bind(("pending", STATUS_PENDING))
240- .await?
241- .check()?;
242- Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next())
219+ .execute(tx)
220+ .await?;
221+ if written.rows_affected() == 0 {
222+ return Ok(None);
223+ }
224+ Ok(Some(before))
225+ })
226+ .await
243227 }
244228
245229 /// Delete the question and its solutions in one transaction, returning
@@ -247,34 +231,34 @@ pub async fn clear_image(
247231 /// caller can take every image blob off disk (solutions carry photos too,
248232 /// and a row-only sweep would strand theirs forever).
249233 ///
250-/// Rides the retry because a solution offer now writes this very row
251-/// ([`bump_question_and_write`]): the two contend by design, and a lost
252-/// round through a bare `check()` was a 500 for a delete that only had to
253-/// be re-sent. Admissible — a `DELETE` can never answer "already exists".
234+/// Children before the parent, so the foreign keys never refuse the parent
235+/// delete. `cascade = true` because a solution offer committing inside this
236+/// window makes the parent delete answer 23503 — a mid-cascade race the
237+/// retry loop re-runs, sweeping the latecomer with it. That foreign key is
238+/// also what keeps a solution from outliving its question on the insert
239+/// side, so the old existence-move transaction is simply gone.
254240 pub async fn delete(
255241 db: &Database,
256242 id: &PoolQuestionId,
257243 ) -> Result<Option<(PoolQuestion, Vec<Solution>)>, AppError> {
258- let (mut result, mut errors) = transaction_with_retry(
259- db,
260- "BEGIN TRANSACTION;
261- DELETE solution WHERE question = $q RETURN BEFORE;
262- DELETE $q RETURN BEFORE;
263- COMMIT TRANSACTION;",
264- &[("q".into(), id.record().into_value())],
265- &[],
266- )
267- .await?;
268- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
269- return Err(error.into());
270- }
271- // Slots count BEGIN: the solution sweep is slot 1, the question slot 2.
272- let solutions = result.take::<Vec<Solution>>(1)?;
273- Ok(result
274- .take::<Vec<PoolQuestion>>(2)?
275- .into_iter()
276- .next()
277- .map(|question| (question, solutions)))
244+ tx_with_retry(db, true, async |tx| {
245+ let solutions = sqlx::query_as!(
246+ Solution,
247+ "DELETE FROM solution WHERE question = $1 RETURNING *",
248+ *id
249+ )
250+ .fetch_all(tx)
251+ .await?;
252+ let question = sqlx::query_as!(
253+ PoolQuestion,
254+ "DELETE FROM pool_question WHERE id = $1 RETURNING *",
255+ *id
256+ )
257+ .fetch_optional(tx)
258+ .await?;
259+ Ok(question.map(|question| (question, solutions)))
260+ })
261+ .await
278262 }
279263
280264 #[cfg(test)]
src/db/solution.rsmodified+127 -78
@@ -1,54 +1,54 @@
1-//! The `solution` table: offers (through the pool question's
2-//! existence-move), the question-scoped reads and page, the grouped counts,
1+//! The `solution` table: offers (their question's existence enforced by the
2+//! real foreign key), the question-scoped read and page, the grouped counts,
33 //! and the unconditional body/image writes of an unmoderated row. The pure
44 //! entity and newtypes live in [`crate::domain::solution`]; the web layer
55 //! reaches these through [`crate::service::solution`].
66
77 use std::collections::HashMap;
88
9-use surrealdb::types::{RecordId, SurrealValue};
10-
11-use crate::database::Database;
9+use crate::database::{Database, tx_with_retry};
1210 use crate::db::page::PagedList;
13-use crate::db::pool_question::bump_question_and_write;
1411 use crate::domain::note_file::FileContentType;
1512 use crate::domain::pool_question::PoolQuestionId;
1613 use crate::domain::solution::{Solution, SolutionBody, SolutionId};
1714 use crate::error::AppError;
1815
19-/// One `GROUP BY question` row of [`counts_for`].
20-#[derive(SurrealValue)]
21-struct SolutionCount {
22- question: PoolQuestionId,
23- n: i64,
24-}
25-
2616 /// Offer the solution. `NotFound` = the question is gone, and nothing was
27-/// written: the create rides [`bump_question_and_write`], so the question's
28-/// existence is a *write* to its row rather than a read the handler made a
29-/// moment earlier — a bare create landing inside
30-/// [`crate::db::pool_question::delete`]'s
31-/// window was swept by nothing and left a solution no route could ever
32-/// reach or remove (every path to one goes through its question), photo
33-/// blob included.
17+/// written: the insert's foreign key (`solution_question_fkey`) refuses an
18+/// orphan the old existence-move transaction spent five statements dodging —
19+/// a bare create landing inside
20+/// [`crate::db::pool_question::delete`]'s window used to be swept by
21+/// nothing and left a solution no route could ever reach or remove (every
22+/// path to one goes through its question), photo blob included.
3423 ///
35-/// Re-sendable despite the `CREATE`: `$id` is a ULID minted once per call
36-/// on a table with no `UNIQUE` index, so a re-send cannot answer "already
37-/// exists" — the one thing the retry could not survive.
24+/// The author's own foreign key never fires in practice (the request
25+/// carries a live session user) and stays a database error if it ever does;
26+/// only the question's key maps to the 404.
3827 pub async fn insert(db: &Database, solution: Solution) -> Result<Solution, AppError> {
39- // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber
40- let (question, id) = (solution.question.clone(), solution.id.record());
41- bump_question_and_write(
42- &question,
43- "CREATE $id CONTENT $solution",
44- vec![
45- ("id".into(), id.into_value()),
46- ("solution".into(), solution.into_value()),
47- ],
48- db,
28+ match sqlx::query_as!(
29+ Solution,
30+ r#"INSERT INTO solution (id, question, author, body, offered_at)
31+ VALUES ($1, $2, $3, $4, $5)
32+ RETURNING *"#,
33+ solution.id,
34+ solution.question,
35+ solution.author,
36+ solution.body,
37+ solution.offered_at,
4938 )
50- .await?
51- .ok_or_else(|| AppError::Internal("failed to create solution".into()))
39+ .fetch_one(db)
40+ .await
41+ {
42+ Ok(row) => Ok(row),
43+ Err(err) if is_question_gone(&err) => Err(AppError::NotFound),
44+ Err(err) => Err(err.into()),
45+ }
46+}
47+
48+/// Did this insert fail on the *question* foreign key — the parent-gone
49+/// refusal — rather than some unrelated database fault?
50+fn is_question_gone(err: &sqlx::Error) -> bool {
51+ err.as_database_error().and_then(|db| db.constraint()) == Some("solution_question_fkey")
5252 }
5353
5454 /// Read a solution only if it belongs to `question` — keeps the nested
@@ -58,32 +58,40 @@ pub async fn read_for(
5858 id: &SolutionId,
5959 question: &PoolQuestionId,
6060 ) -> Result<Option<Solution>, AppError> {
61- let solution: Option<Solution> = db.select(id.record()).await?;
62- Ok(solution.filter(|solution| &solution.question == question))
61+ let row = sqlx::query_as!(
62+ Solution,
63+ "SELECT * FROM solution WHERE id = $1 AND question = $2",
64+ id,
65+ question
66+ )
67+ .fetch_optional(db)
68+ .await?;
69+ Ok(row)
6370 }
6471
6572 /// The question's solutions, oldest first — a discussion reads downward.
6673 /// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond
67-/// offers *stable* across re-queries, not insertion-ordered (ULID low bits
68-/// are random within a millisecond, so same-ms order is arbitrary).
74+/// offers *stable* across re-queries (the ids are write-ordered UUIDv7, so
75+/// same-ms rows still sort by mint order).
6976 pub async fn list_for(
7077 db: &Database,
7178 question: &PoolQuestionId,
7279 limit: Option<i64>,
7380 offset: i64,
7481 ) -> Result<(Vec<Solution>, i64), AppError> {
82+ // `.uuid()` feeds the builder its raw bind value — exact, typed.
7583 PagedList::new(
76- "solution WHERE question = $q",
84+ "solution WHERE question = $1",
7785 "ORDER BY offered_at ASC, id ASC",
7886 )
79- .bind("q", question.record())
87+ .bind(question.uuid())
8088 .run(limit, offset, db)
8189 .await
8290 }
8391
8492 /// Per-question solution tallies for a page of questions, in one grouped
8593 /// query — a per-row `count()` would cost a query per question. Keys are
86-/// question record keys; a question with no solutions has no entry, so
94+/// the questions' wire keys; a question with no solutions has no entry, so
8795 /// the caller reads misses as zero.
8896 pub async fn counts_for(
8997 db: &Database,
@@ -92,18 +100,19 @@ pub async fn counts_for(
92100 if questions.is_empty() {
93101 return Ok(HashMap::new());
94102 }
95- let ids: Vec<RecordId> = questions.iter().map(|question| question.record()).collect();
96- let mut result = db
97- .query(
98- "SELECT question, count() AS n FROM solution WHERE question IN $qs GROUP BY question",
99- )
100- .bind(("qs", ids))
101- .await?
102- .check()?;
103- Ok(result
104- .take::<Vec<SolutionCount>>(0)?
103+ let ids: Vec<PoolQuestionId> = questions.iter().copied().collect();
104+ let rows = sqlx::query!(
105+ r#"SELECT question AS "question: PoolQuestionId", count(*) AS n
106+ FROM solution
107+ WHERE question = ANY($1)
108+ GROUP BY question"#,
109+ ids,
110+ )
111+ .fetch_all(db)
112+ .await?;
113+ Ok(rows
105114 .into_iter()
106- .map(|row| (row.question.key().to_string(), row.n))
115+ .map(|row| (row.question.key(), row.n))
107116 .collect())
108117 }
109118
@@ -115,13 +124,15 @@ pub async fn set_body(
115124 id: &SolutionId,
116125 body: &SolutionBody,
117126 ) -> Result<Option<Solution>, AppError> {
118- let mut result = db
119- .query("UPDATE $s SET body = $b RETURN AFTER")
120- .bind(("s", id.record()))
121- .bind(("b", body.clone()))
122- .await?
123- .check()?;
124- Ok(result.take::<Vec<Solution>>(0)?.into_iter().next())
127+ let row = sqlx::query_as!(
128+ Solution,
129+ "UPDATE solution SET body = $2 WHERE id = $1 RETURNING *",
130+ id,
131+ body
132+ )
133+ .fetch_optional(db)
134+ .await?;
135+ Ok(row)
125136 }
126137
127138 /// Point the solution at a freshly written image blob. Unconditional for
@@ -129,6 +140,9 @@ pub async fn set_body(
129140 /// `image_file` is the replaced blob the caller must remove; `None` means
130141 /// the row was deleted mid-flight (the fresh blob is the caller's orphan
131142 /// to take back off disk).
143+///
144+/// The row lock makes the before-read and the write one switch, so two
145+/// racing uploads can never both be told they replaced the same blob.
132146 pub async fn set_image(
133147 db: &Database,
134148 id: &SolutionId,
@@ -136,33 +150,68 @@ pub async fn set_image(
136150 content_type: &FileContentType,
137151 size: i64,
138152 ) -> Result<Option<Solution>, AppError> {
139- let mut result = db
140- .query("UPDATE $s SET image_file = $file, image_content_type = $ct, image_size = $size RETURN BEFORE")
141- .bind(("s", id.record()))
142- .bind(("file", file.to_string()))
143- .bind(("ct", content_type.clone()))
144- .bind(("size", size))
145- .await?
146- .check()?;
147- Ok(result.take::<Vec<Solution>>(0)?.into_iter().next())
153+ tx_with_retry(db, false, async |tx| {
154+ let before = sqlx::query_as!(
155+ Solution,
156+ "SELECT * FROM solution WHERE id = $1 FOR UPDATE",
157+ *id
158+ )
159+ .fetch_optional(tx)
160+ .await?;
161+ let Some(before) = before else {
162+ return Ok(None);
163+ };
164+ sqlx::query!(
165+ r#"UPDATE solution
166+ SET image_file = $2, image_content_type = $3, image_size = $4
167+ WHERE id = $1"#,
168+ *id,
169+ file,
170+ content_type,
171+ size,
172+ )
173+ .execute(tx)
174+ .await?;
175+ Ok(Some(before))
176+ })
177+ .await
148178 }
149179
150180 /// Detach the solution's image. Returns the *before* row — its
151181 /// `image_file` is the blob the caller must remove.
152182 pub async fn clear_image(db: &Database, id: &SolutionId) -> Result<Option<Solution>, AppError> {
153- let mut result = db
154- .query(
155- "UPDATE $s SET image_file = NONE, image_content_type = NONE, image_size = NONE \
156- RETURN BEFORE",
183+ tx_with_retry(db, false, async |tx| {
184+ let before = sqlx::query_as!(
185+ Solution,
186+ "SELECT * FROM solution WHERE id = $1 FOR UPDATE",
187+ *id
188+ )
189+ .fetch_optional(tx)
190+ .await?;
191+ let Some(before) = before else {
192+ return Ok(None);
193+ };
194+ sqlx::query!(
195+ r#"UPDATE solution
196+ SET image_file = NULL, image_content_type = NULL, image_size = NULL
197+ WHERE id = $1"#,
198+ *id,
157199 )
158- .bind(("s", id.record()))
159- .await?
160- .check()?;
161- Ok(result.take::<Vec<Solution>>(0)?.into_iter().next())
200+ .execute(tx)
201+ .await?;
202+ Ok(Some(before))
203+ })
204+ .await
162205 }
163206
164207 pub async fn delete(db: &Database, solution: Solution) -> Result<Solution, AppError> {
165- let deleted: Option<Solution> = db.delete(solution.id.record()).await?;
208+ let deleted = sqlx::query_as!(
209+ Solution,
210+ "DELETE FROM solution WHERE id = $1 RETURNING *",
211+ solution.id
212+ )
213+ .fetch_optional(db)
214+ .await?;
166215 deleted.ok_or(AppError::NotFound)
167216 }
168217
src/web/questions.rsmodified+2 -2
@@ -482,7 +482,7 @@ async fn upload_image(
482482 let upload = read_image_upload(&st, &mut multipart).await?;
483483 let size = upload.size();
484484
485- let file = ulid::Ulid::generate().to_string();
485+ let file = crate::domain::monotonic_id::next_uuid().to_string();
486486 store_blob(&st, &file, &upload.data, || async {
487487 match pool_question::set_image(&st.db, question.get_id(), &file, &upload.content_type, size)
488488 .await?
@@ -808,7 +808,7 @@ async fn upload_solution_image(
808808 let upload = read_image_upload(&st, &mut multipart).await?;
809809 let size = upload.size();
810810
811- let file = ulid::Ulid::generate().to_string();
811+ let file = crate::domain::monotonic_id::next_uuid().to_string();
812812 store_blob(&st, &file, &upload.data, || async {
813813 match solution::set_image(&st.db, solution.get_id(), &file, &upload.content_type, size)
814814 .await?