🔀 merge: port bank+pool to sqlx/Postgres (L4)
Browse files at this commit5 changed files +583 -576
- src/db/bank_question.rs +174 -187
- src/db/bank_question_image.rs +104 -117
- src/db/pool_question.rs +176 -192
- src/db/solution.rs +127 -78
- src/web/questions.rs +2 -2
src/db/bank_question.rsmodified+174 -187
| @@ -7,10 +7,10 @@ | |||
| 7 | 7 | ||
| 8 | use std::collections::HashMap; | 8 | use std::collections::HashMap; |
| 9 | 9 | ||
| 10 | -use surrealdb::types::{RecordId, SurrealValue}; | 10 | +use sqlx::types::Json; |
| 11 | 11 | ||
| 12 | -use crate::constant::USAGE_COUNTS_SQL; | 12 | +use crate::database::{Database, tx_with_retry}; |
| 13 | -use crate::database::{Database, transaction_with_retry, write_with_retry}; | 13 | +use crate::db::page::{PagedList, Param}; |
| 14 | use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; | 14 | use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; |
| 15 | use crate::domain::bank_question_image::BankQuestionImage; | 15 | use crate::domain::bank_question_image::BankQuestionImage; |
| 16 | use crate::domain::exam::ExamId; | 16 | use crate::domain::exam::ExamId; |
| @@ -21,21 +21,6 @@ use crate::domain::timestamp::Timestamp; | |||
| 21 | use crate::domain::user::UserId; | 21 | use crate::domain::user::UserId; |
| 22 | use crate::error::AppError; | 22 | use crate::error::AppError; |
| 23 | 23 | ||
| 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 | - | ||
| 39 | pub async fn create( | 24 | pub async fn create( |
| 40 | db: &Database, | 25 | db: &Database, |
| 41 | owner: UserId, | 26 | owner: UserId, |
| @@ -85,24 +70,52 @@ async fn insert( | |||
| 85 | BankVisibility::default(), | 70 | BankVisibility::default(), |
| 86 | Timestamp::now(), | 71 | Timestamp::now(), |
| 87 | ); | 72 | ); |
| 88 | - let created: Option<BankQuestion> = db.create(question.id.record()).content(question).await?; | 73 | + let row = sqlx::query_as!( |
| 89 | - created.ok_or_else(|| AppError::Internal("failed to create bank question".into())) | 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) | ||
| 90 | } | 95 | } |
| 91 | 96 | ||
| 92 | pub async fn read(db: &Database, id: &BankQuestionId) -> Result<Option<BankQuestion>, AppError> { | 97 | 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) | ||
| 94 | } | 106 | } |
| 95 | 107 | ||
| 96 | -/// One page of the bank the caller may see, **newest first** (ULID ids sort by | 108 | +/// One page of the bank the caller may see, **newest first** (`id DESC` is |
| 97 | -/// creation, so `id DESC` is newest-first) — plus the total row count under | 109 | +/// mint order — the ids are write-ordered UUIDv7) — plus the total row count |
| 98 | -/// the same filters, so a client can page past the window. | 110 | +/// under the same filters, so a client can page past the window. |
| 99 | /// | 111 | /// |
| 100 | -/// Every filter is a WHERE clause and the window is a real `LIMIT`/`START`: | 112 | +/// The window is a real `LIMIT`/`OFFSET` handed to the database (the |
| 101 | -/// the old version read the whole table and sliced it in memory, which hid | 113 | +/// [`PagedList`] builder: the filters are runtime-conditional, which is that |
| 102 | -/// every template past the client's first page. `q` is a case- and | 114 | +/// builder's named exemption from the compile-time macros). `q` is a case- |
| 103 | -/// diacritic-insensitive fragment of the question text (blank = no text | 115 | +/// and diacritic-insensitive fragment of the question text (blank = no text |
| 104 | -/// filter): needle and column both go through | 116 | +/// filter): needle and column both go through [`crate::domain::text_fold`], |
| 105 | -/// [`crate::domain::text_fold`], so `istanbul` finds `İSTANBUL` and back. | 117 | +/// so `istanbul` finds `İSTANBUL` and back. `position` rather than `LIKE` |
| 118 | +/// keeps the needle a *literal* substring — no `%`/`_` wildcard surprises. | ||
| 106 | /// | 119 | /// |
| 107 | /// `visible_to` is the security filter, and it is a WHERE clause like every | 120 | /// `visible_to` is the security filter, and it is a WHERE clause like every |
| 108 | /// other one — never a post-filter, or `total` would count templates the | 121 | /// 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 | |||
| 113 | /// `visibility` is the *user's* filter ("only mine" / "shared with the | 126 | /// `visibility` is the *user's* filter ("only mine" / "shared with the |
| 114 | /// school") and is ANDed on top of that gate, so it can only ever narrow: | 127 | /// school") and is ANDed on top of that gate, so it can only ever narrow: |
| 115 | /// `school` still hides another teacher's private rows, and `private` | 128 | /// `school` still hides another teacher's private rows, and `private` |
| 116 | -/// intersected with the gate leaves exactly the caller's own drafts. It | 129 | +/// intersected with the gate leaves exactly the caller's own drafts. It is |
| 117 | -/// joins the same `clauses` vec as the rest, so `total` honours it too — | 130 | +/// part of the same WHERE, so `total` honours it too — a count that ignored |
| 118 | -/// a count that ignored it would break paging. | 131 | +/// it would break paging. |
| 119 | -// Flat filter args, like every other `list` here — a builder struct for | 132 | +/// |
| 120 | -// four `Option`s and a window would be more machinery than the call sites. | 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. | ||
| 121 | #[allow(clippy::too_many_arguments)] | 136 | #[allow(clippy::too_many_arguments)] |
| 122 | pub async fn list( | 137 | pub async fn list( |
| 123 | db: &Database, | 138 | db: &Database, |
| @@ -130,70 +145,53 @@ pub async fn list( | |||
| 130 | offset: i64, | 145 | offset: i64, |
| 131 | ) -> Result<(Vec<BankQuestion>, i64), AppError> { | 146 | ) -> Result<(Vec<BankQuestion>, i64), AppError> { |
| 132 | let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); | 147 | let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); |
| 133 | - let mut clauses = Vec::new(); | 148 | + let mut clauses: Vec<String> = Vec::new(); |
| 134 | - if visible_to.is_some() { | 149 | + let mut binds: Vec<Param> = Vec::new(); |
| 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)); | ||
| 168 | if let Some(viewer) = visible_to { | 150 | 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 | + )); | ||
| 170 | } | 156 | } |
| 171 | if let Some(visibility) = visibility { | 157 | 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())); | ||
| 173 | } | 160 | } |
| 174 | if let Some(owner) = owner { | 161 | 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())); | ||
| 176 | } | 164 | } |
| 177 | if let Some(subject) = subject { | 165 | 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())); | ||
| 179 | } | 168 | } |
| 180 | if let Some(needle) = needle { | 169 | 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 | + )); | ||
| 182 | } | 176 | } |
| 183 | - if let Some(limit) = limit { | 177 | + let from_where = if clauses.is_empty() { |
| 184 | - query = query.bind(("limit", limit)); | 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); | ||
| 185 | } | 187 | } |
| 186 | - let mut result = query.await?.check()?; | 188 | + page.run(limit, offset, db).await |
| 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)) | ||
| 191 | } | 189 | } |
| 192 | 190 | ||
| 193 | /// How many exam questions were instantiated from each of `ids` — the | 191 | /// How many exam questions were instantiated from each of `ids` — the |
| 194 | /// `from_bank` side of the provenance link, tallied for a whole page in | 192 | /// `from_bank` side of the provenance link, tallied for a whole page in |
| 195 | /// **one** grouped query (a `count()` per row would be the N+1 this page | 193 | /// **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 |
| 197 | /// nobody ever used has no entry at all, so the caller reads a miss as | 195 | /// nobody ever used has no entry at all, so the caller reads a miss as |
| 198 | /// zero — and the UI can stay quiet rather than print "0". | 196 | /// zero — and the UI can stay quiet rather than print "0". |
| 199 | /// | 197 | /// |
| @@ -207,16 +205,22 @@ pub async fn usage_counts( | |||
| 207 | if ids.is_empty() { | 205 | if ids.is_empty() { |
| 208 | return Ok(HashMap::new()); | 206 | return Ok(HashMap::new()); |
| 209 | } | 207 | } |
| 210 | - let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect(); | 208 | + let ids: Vec<BankQuestionId> = ids.iter().map(|id| (*id).clone()).collect(); |
| 211 | - let mut result = db | 209 | + let rows = sqlx::query!( |
| 212 | - .query(USAGE_COUNTS_SQL) | 210 | + r#"SELECT from_bank AS "from_bank: BankQuestionId", count(*) AS n |
| 213 | - .bind(("ids", records)) | 211 | + FROM exam_question |
| 214 | - .await? | 212 | + WHERE from_bank = ANY($1) |
| 215 | - .check()?; | 213 | + GROUP BY from_bank"#, |
| 216 | - Ok(result | 214 | + ids, |
| 217 | - .take::<Vec<UsageCount>>(0)? | 215 | + ) |
| 216 | + .fetch_all(db) | ||
| 217 | + .await?; | ||
| 218 | + Ok(rows | ||
| 218 | .into_iter() | 219 | .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 | + }) | ||
| 220 | .collect()) | 224 | .collect()) |
| 221 | } | 225 | } |
| 222 | 226 | ||
| @@ -228,22 +232,13 @@ pub async fn usage_counts( | |||
| 228 | /// field is re-stated from the snapshot, and the kind/choices/correct trio | 232 | /// field is re-stated from the snapshot, and the kind/choices/correct trio |
| 229 | /// has to be (a text-only edit re-submits the stored options *with their | 233 | /// has to be (a text-only edit re-submits the stored options *with their |
| 230 | /// ids* so each keeps its picture) — so without the compare-and-set the | 234 | /// 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 | 235 | +/// later writer silently reverts the earlier one. |
| 232 | -/// database round trip wide, which is exactly how far apart two concurrent | ||
| 233 | -/// requests to this one process can sit. | ||
| 234 | /// | 236 | /// |
| 235 | /// Every field the merge re-states is in the guard, which is the same list | 237 | /// 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 | 238 | +/// the `SET` writes; the nullable ones compare `IS NOT DISTINCT FROM`, so an |
| 237 | -/// required string keys, so none is ever dropped for being `NONE` (the trap | 239 | +/// absent subject/correct/choices guards truthfully. Postgres needs no retry |
| 238 | -/// [`crate::db::settings::save_if_unchanged`] works around). | 240 | +/// loop around this: the guard re-evaluates on the row lock at execution, so |
| 239 | -/// | 241 | +/// a rival write either predates this statement's snapshot or loses its own. |
| 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". | ||
| 247 | pub async fn update_if_unchanged( | 242 | pub async fn update_if_unchanged( |
| 248 | db: &Database, | 243 | db: &Database, |
| 249 | expected: BankQuestion, | 244 | expected: BankQuestion, |
| @@ -254,42 +249,40 @@ pub async fn update_if_unchanged( | |||
| 254 | visibility: BankVisibility, | 249 | visibility: BankVisibility, |
| 255 | ) -> Result<Option<BankQuestion>, AppError> { | 250 | ) -> Result<Option<BankQuestion>, AppError> { |
| 256 | let (kind, choices, correct) = spec.into_parts(); | 251 | let (kind, choices, correct) = spec.into_parts(); |
| 257 | - let rows: Vec<BankQuestion> = write_with_retry( | 252 | + let choices = choices.map(Json); |
| 258 | - db, | 253 | + let row = sqlx::query_as!( |
| 259 | - "UPDATE $id SET subject = $subject, text = $text, points = $points, | 254 | + BankQuestion, |
| 260 | - kind = $kind, choices = $choices, correct = $correct, | 255 | + r#"UPDATE bank_question SET |
| 261 | - visibility = $visibility | 256 | + subject = $2, text = $3, points = $4, kind = $5, |
| 262 | - WHERE subject = $was_subject AND text = $was_text | 257 | + choices = $6, correct = $7, visibility = $8 |
| 263 | - AND points = $was_points AND kind = $was_kind | 258 | + WHERE id = $1 |
| 264 | - AND choices = $was_choices AND correct = $was_correct | 259 | + AND subject IS NOT DISTINCT FROM $9 |
| 265 | - AND visibility = $was_visibility | 260 | + AND text = $10 |
| 266 | - RETURN AFTER", | 261 | + AND points = $11 |
| 267 | - &[ | 262 | + AND kind = $12 |
| 268 | - ( | 263 | + AND choices IS NOT DISTINCT FROM $13 |
| 269 | - "was_subject".into(), | 264 | + AND correct IS NOT DISTINCT FROM $14 |
| 270 | - expected.subject.clone().map(|s| s.record()).into_value(), | 265 | + AND visibility = $15 |
| 271 | - ), | 266 | + RETURNING *"#, |
| 272 | - ("was_text".into(), expected.text.clone().into_value()), | 267 | + expected.id, |
| 273 | - ("was_points".into(), expected.points.into_value()), | 268 | + subject, |
| 274 | - ("was_kind".into(), expected.kind.clone().into_value()), | 269 | + text, |
| 275 | - ("was_choices".into(), expected.choices.clone().into_value()), | 270 | + points, |
| 276 | - ("was_correct".into(), expected.correct.clone().into_value()), | 271 | + kind, |
| 277 | - ( | 272 | + choices, |
| 278 | - "was_visibility".into(), | 273 | + correct, |
| 279 | - expected.visibility.clone().into_value(), | 274 | + visibility, |
| 280 | - ), | 275 | + expected.subject, |
| 281 | - ("id".into(), expected.id.record().into_value()), | 276 | + expected.text, |
| 282 | - ("subject".into(), subject.map(|s| s.record()).into_value()), | 277 | + expected.points, |
| 283 | - ("text".into(), text.into_value()), | 278 | + expected.kind, |
| 284 | - ("points".into(), points.into_value()), | 279 | + expected.choices, |
| 285 | - ("kind".into(), kind.into_value()), | 280 | + expected.correct, |
| 286 | - ("choices".into(), choices.into_value()), | 281 | + expected.visibility, |
| 287 | - ("correct".into(), correct.into_value()), | ||
| 288 | - ("visibility".into(), visibility.into_value()), | ||
| 289 | - ], | ||
| 290 | ) | 282 | ) |
| 283 | + .fetch_optional(db) | ||
| 291 | .await?; | 284 | .await?; |
| 292 | - Ok(rows.into_iter().next()) | 285 | + Ok(row) |
| 293 | } | 286 | } |
| 294 | 287 | ||
| 295 | /// Delete the template and cascade-remove its bank images, so none points | 288 | /// Delete the template and cascade-remove its bank images, so none points |
| @@ -297,59 +290,53 @@ pub async fn update_if_unchanged( | |||
| 297 | /// actually removed come back with it: the blobs are the web layer's to | 290 | /// actually removed come back with it: the blobs are the web layer's to |
| 298 | /// take off disk, but only for *these* rows — an upload that committed | 291 | /// take off disk, but only for *these* rows — an upload that committed |
| 299 | /// after the caller listed the template's images is swept here too, and a | 292 | /// after the caller listed the template's images is swept here too, and a |
| 300 | -/// pre-read snapshot would strand its blob for good | 293 | +/// 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". | ||
| 311 | /// | 294 | /// |
| 312 | -/// Exam questions tied to this template keep living: only their provenance | 295 | +/// All four statements are one transaction, children before the parent so |
| 313 | -/// links are cleared, field-scoped (never a whole-row save — the question | 296 | +/// the foreign keys never refuse the parent delete: the provenance links |
| 314 | -/// isn't ours and may be edited concurrently), so nothing can read a link to | 297 | +/// clear first (exam questions tied to this template keep living — only the |
| 315 | -/// a template that no longer exists. *Both* directions point at a template, | 298 | +/// links go, field-scoped, in both directions: `from_bank` on the questions |
| 316 | -/// so both are cleared: `from_bank` on the questions instantiated from it, | 299 | +/// instantiated from it and `banked_as` on the question it was saved out |
| 317 | -/// and `banked_as` on the question it was saved out of. | 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. | ||
| 318 | pub async fn delete( | 304 | pub async fn delete( |
| 319 | db: &Database, | 305 | db: &Database, |
| 320 | target: BankQuestion, | 306 | target: BankQuestion, |
| 321 | ) -> Result<(BankQuestion, Vec<BankQuestionImage>), AppError> { | 307 | ) -> Result<(BankQuestion, Vec<BankQuestionImage>), AppError> { |
| 322 | - let (mut result, mut errors) = transaction_with_retry( | 308 | + tx_with_retry(db, true, async |tx| { |
| 323 | - db, | 309 | + let id = target.id.clone(); |
| 324 | - "BEGIN TRANSACTION; | 310 | + sqlx::query!( |
| 325 | - LET $images = (DELETE bank_question_image WHERE bank_question = $b RETURN BEFORE); | 311 | + "UPDATE exam_question SET from_bank = NULL WHERE from_bank = $1", |
| 326 | - UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b; | 312 | + id |
| 327 | - UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b; | 313 | + ) |
| 328 | - LET $gone = (DELETE $b RETURN BEFORE); | 314 | + .execute(tx) |
| 329 | - RETURN { question: $gone, images: $images }; | 315 | + .await?; |
| 330 | - COMMIT TRANSACTION;", | 316 | + sqlx::query!( |
| 331 | - &[("b".into(), target.id.record().into_value())], | 317 | + "UPDATE exam_question SET banked_as = NULL WHERE banked_as = $1", |
| 332 | - &[], | 318 | + id |
| 333 | - ) | 319 | + ) |
| 334 | - .await?; | 320 | + .execute(tx) |
| 335 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | 321 | + .await?; |
| 336 | - return Err(error.into()); | 322 | + let images = sqlx::query_as!( |
| 337 | - } | 323 | + BankQuestionImage, |
| 338 | - // The trailing `RETURN` is the last statement before `COMMIT`, so its | 324 | + "DELETE FROM bank_question_image WHERE bank_question = $1 RETURNING *", |
| 339 | - // slot follows the statement count rather than a hand-kept number; | 325 | + id |
| 340 | - // `num_statements` counts BEGIN and COMMIT. | 326 | + ) |
| 341 | - let slot = result.num_statements().saturating_sub(2); | 327 | + .fetch_all(tx) |
| 342 | - let outcome = result | 328 | + .await?; |
| 343 | - .take::<Vec<DeleteOutcome>>(slot)? | 329 | + let question = sqlx::query_as!( |
| 344 | - .into_iter() | 330 | + BankQuestion, |
| 345 | - .next() | 331 | + "DELETE FROM bank_question WHERE id = $1 RETURNING *", |
| 346 | - .ok_or_else(|| AppError::Internal("failed to delete bank question".into()))?; | 332 | + id |
| 347 | - let question = outcome | 333 | + ) |
| 348 | - .question | 334 | + .fetch_optional(tx) |
| 349 | - .into_iter() | 335 | + .await? |
| 350 | - .next() | ||
| 351 | .ok_or(AppError::NotFound)?; | 336 | .ok_or(AppError::NotFound)?; |
| 352 | - Ok((question, outcome.images)) | 337 | + Ok((question, images)) |
| 338 | + }) | ||
| 339 | + .await | ||
| 353 | } | 340 | } |
| 354 | 341 | ||
| 355 | #[cfg(test)] | 342 | #[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 | 1 | +//! The `bank_question_image` slot table: the per-slot upsert, the page-wide |
| 2 | -//! template's existence into its own transaction, the page-wide listing, and | 2 | +//! listing, and the choice sweep a non-destructive PATCH runs. Blob I/O |
| 3 | -//! the choice sweep a non-destructive PATCH runs. Blob I/O stays in the web | 3 | +//! stays in the web layer; the pure entity and newtypes in |
| 4 | -//! layer; the pure entity and newtypes in | ||
| 5 | //! [`crate::domain::bank_question_image`]. | 4 | //! [`crate::domain::bank_question_image`]. |
| 6 | 5 | ||
| 7 | -use surrealdb::types::{RecordId, SurrealValue}; | 6 | +use crate::database::{Database, foreign_key_violation, tx_with_retry}; |
| 8 | - | ||
| 9 | -use crate::database::{Database, transaction_with_retry}; | ||
| 10 | use crate::domain::bank_question::BankQuestionId; | 7 | use crate::domain::bank_question::BankQuestionId; |
| 11 | -use crate::domain::bank_question_image::{BankQuestionImage, BankQuestionImageId}; | 8 | +use crate::domain::bank_question_image::BankQuestionImage; |
| 12 | use crate::domain::exam_question::ChoiceId; | 9 | use crate::domain::exam_question::ChoiceId; |
| 13 | use crate::error::AppError; | 10 | use crate::error::AppError; |
| 14 | 11 | ||
| 15 | -/// What one [`upsert`] transaction returns: the row it | 12 | +/// Create or replace the slot's image row — the table's `NULLS NOT DISTINCT` |
| 16 | -/// stored and the blob name it replaced. Both are arrays because SurrealDB | 13 | +/// unique key makes this the whole "one image per slot" story — handing back |
| 17 | -/// drops an object key valued `NONE` on the way out, while an empty array | 14 | +/// what it stored plus the blob name it replaced, for the caller to take off |
| 18 | -/// survives — "nothing was replaced" has to be readable, not missing. | 15 | +/// disk. |
| 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. | ||
| 43 | /// | 16 | /// |
| 44 | -/// The replaced blob name comes out of this same transaction rather than a | 17 | +/// Both halves are the transaction's doing, and the row lock makes them one |
| 45 | -/// read in front of it (the shape | 18 | +/// switch: two uploads racing on one slot serialize on the `FOR UPDATE`, and |
| 46 | -/// [`crate::db::pool_question::set_image`] has): two | 19 | +/// the loser's `ON CONFLICT` re-reads the winner's row, where two unlocked |
| 47 | -/// uploads to one slot both write this row, so they contend and the loser | 20 | +/// pre-reads would both have seen the *old* blob name and left the loser's |
| 48 | -/// re-reads the winner's blob name, where two pre-reads both saw the *old* | 21 | +/// fresh one orphaned on disk. |
| 49 | -/// blob and left the loser's fresh one orphaned on disk. | ||
| 50 | /// | 22 | /// |
| 51 | -/// Admissible for [`transaction_with_retry`]: the `UPSERT`'s id is | 23 | +/// The template's existence rides the real foreign key: an insert whose |
| 52 | -/// deterministic per (question, slot) and the table carries no `UNIQUE` | 24 | +/// template was deleted mid-flight answers 23503 and maps to the same 404 |
| 53 | -/// index, so the write always resolves onto the row its id names and can | 25 | +/// the old points-move transaction produced with its `THROW`. Nothing is |
| 54 | -/// never answer "already exists". | 26 | +/// written either way. |
| 55 | pub async fn upsert( | 27 | pub async fn upsert( |
| 56 | db: &Database, | 28 | db: &Database, |
| 57 | image: BankQuestionImage, | 29 | image: BankQuestionImage, |
| 58 | ) -> Result<(BankQuestionImage, Option<String>), AppError> { | 30 | ) -> Result<(BankQuestionImage, Option<String>), AppError> { |
| 59 | - // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic | 31 | + tx_with_retry(db, false, async |tx| { |
| 60 | - let (question, id) = (image.bank_question.record(), image.id.record()); | 32 | + let was = sqlx::query!( |
| 61 | - let (mut result, mut errors) = transaction_with_retry( | 33 | + r#"SELECT file FROM bank_question_image |
| 62 | - db, | 34 | + WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2 |
| 63 | - "BEGIN TRANSACTION; | 35 | + FOR UPDATE"#, |
| 64 | - LET $was_points = (SELECT VALUE points FROM ONLY $b); | 36 | + image.bank_question.clone(), |
| 65 | - LET $bumped = (UPDATE $b SET points = points + 1 RETURN VALUE id); | 37 | + image.slot.clone(), |
| 66 | - IF array::len($bumped) = 0 { THROW 'no_question' }; | 38 | + ) |
| 67 | - UPDATE $b SET points = $was_points; | 39 | + .fetch_optional(tx) |
| 68 | - LET $replaced = (SELECT VALUE file FROM $id); | 40 | + .await? |
| 69 | - LET $stored = (UPSERT $id CONTENT $image); | 41 | + .map(|row| row.file); |
| 70 | - RETURN { stored: $stored, replaced: $replaced }; | 42 | + let stored = match sqlx::query_as!( |
| 71 | - COMMIT TRANSACTION;", | 43 | + BankQuestionImage, |
| 72 | - &[ | 44 | + r#"INSERT INTO bank_question_image |
| 73 | - ("b".into(), question.into_value()), | 45 | + (bank_question, slot, file, content_type, size) |
| 74 | - ("id".into(), id.into_value()), | 46 | + VALUES ($1, $2, $3, $4, $5) |
| 75 | - ("image".into(), image.into_value()), | 47 | + ON CONFLICT (bank_question, slot) DO UPDATE |
| 76 | - ], | 48 | + SET file = $3, content_type = $4, size = $5 |
| 77 | - &["no_question"], | 49 | + RETURNING *"#, |
| 78 | - ) | 50 | + image.bank_question.clone(), |
| 79 | - .await?; | 51 | + image.slot.clone(), |
| 80 | - // An aborted transaction errors *every* slot, most with a generic "not | 52 | + image.file.clone(), |
| 81 | - // executed" — only the THROW's own slot names the reason. | 53 | + image.content_type, |
| 82 | - if errors | 54 | + image.size, |
| 83 | - .values() | 55 | + ) |
| 84 | - .any(|error| error.to_string().contains("no_question")) | 56 | + .fetch_one(tx) |
| 85 | - { | 57 | + .await |
| 86 | - return Err(AppError::NotFound); | 58 | + { |
| 87 | - } | 59 | + Ok(row) => row, |
| 88 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | 60 | + // The template row is gone; no orphan image may outlive it. |
| 89 | - return Err(error.into()); | 61 | + Err(err) if foreign_key_violation(&err) => return Err(AppError::NotFound), |
| 90 | - } | 62 | + Err(err) => return Err(err.into()), |
| 91 | - // The trailing `RETURN` is the last statement before `COMMIT`, so its | 63 | + }; |
| 92 | - // slot follows the statement count rather than a hand-kept number; | 64 | + Ok((stored, was)) |
| 93 | - // `num_statements` counts BEGIN and COMMIT. | 65 | + }) |
| 94 | - let slot = result.num_statements().saturating_sub(2); | 66 | + .await |
| 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())) | ||
| 103 | } | 67 | } |
| 104 | 68 | ||
| 105 | pub async fn read_slot( | 69 | pub async fn read_slot( |
| @@ -107,21 +71,30 @@ pub async fn read_slot( | |||
| 107 | question: &BankQuestionId, | 71 | question: &BankQuestionId, |
| 108 | slot: Option<&ChoiceId>, | 72 | slot: Option<&ChoiceId>, |
| 109 | ) -> Result<Option<BankQuestionImage>, AppError> { | 73 | ) -> Result<Option<BankQuestionImage>, AppError> { |
| 110 | - Ok(db | 74 | + let row = sqlx::query_as!( |
| 111 | - .select(BankQuestionImageId::for_slot(question, slot).record()) | 75 | + BankQuestionImage, |
| 112 | - .await?) | 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) | ||
| 113 | } | 84 | } |
| 114 | 85 | ||
| 115 | pub async fn list_for_question( | 86 | pub async fn list_for_question( |
| 116 | db: &Database, | 87 | db: &Database, |
| 117 | question: &BankQuestionId, | 88 | question: &BankQuestionId, |
| 118 | ) -> Result<Vec<BankQuestionImage>, AppError> { | 89 | ) -> Result<Vec<BankQuestionImage>, AppError> { |
| 119 | - let mut result = db | 90 | + let rows = sqlx::query_as!( |
| 120 | - .query("SELECT * FROM bank_question_image WHERE bank_question = $b") | 91 | + BankQuestionImage, |
| 121 | - .bind(("b", question.record())) | 92 | + "SELECT * FROM bank_question_image WHERE bank_question = $1", |
| 122 | - .await? | 93 | + question |
| 123 | - .check()?; | 94 | + ) |
| 124 | - Ok(result.take::<Vec<BankQuestionImage>>(0)?) | 95 | + .fetch_all(db) |
| 96 | + .await?; | ||
| 97 | + Ok(rows) | ||
| 125 | } | 98 | } |
| 126 | 99 | ||
| 127 | /// The image rows of several templates in one query — for bucketing onto a | 100 | /// The image rows of several templates in one query — for bucketing onto a |
| @@ -133,13 +106,15 @@ pub async fn list_for_questions( | |||
| 133 | if questions.is_empty() { | 106 | if questions.is_empty() { |
| 134 | return Ok(Vec::new()); | 107 | return Ok(Vec::new()); |
| 135 | } | 108 | } |
| 136 | - let records: Vec<RecordId> = questions.iter().map(|q| q.record()).collect(); | 109 | + let ids: Vec<BankQuestionId> = questions.iter().map(|q| (*q).clone()).collect(); |
| 137 | - let mut result = db | 110 | + let rows = sqlx::query_as!( |
| 138 | - .query("SELECT * FROM bank_question_image WHERE bank_question IN $ids") | 111 | + BankQuestionImage, |
| 139 | - .bind(("ids", records)) | 112 | + "SELECT * FROM bank_question_image WHERE bank_question = ANY($1)", |
| 140 | - .await? | 113 | + ids |
| 141 | - .check()?; | 114 | + ) |
| 142 | - Ok(result.take::<Vec<BankQuestionImage>>(0)?) | 115 | + .fetch_all(db) |
| 116 | + .await?; | ||
| 117 | + Ok(rows) | ||
| 143 | } | 118 | } |
| 144 | 119 | ||
| 145 | /// Drop the option pictures whose choice is gone — every choice image of | 120 | /// Drop the option pictures whose choice is gone — every choice image of |
| @@ -157,23 +132,35 @@ pub async fn delete_choices_not_in( | |||
| 157 | keep: &[ChoiceId], | 132 | keep: &[ChoiceId], |
| 158 | ) -> Result<Vec<BankQuestionImage>, AppError> { | 133 | ) -> Result<Vec<BankQuestionImage>, AppError> { |
| 159 | let keep: Vec<String> = keep.iter().map(|id| id.as_str().to_string()).collect(); | 134 | let keep: Vec<String> = keep.iter().map(|id| id.as_str().to_string()).collect(); |
| 160 | - let mut result = db | 135 | + let rows = sqlx::query_as!( |
| 161 | - .query( | 136 | + BankQuestionImage, |
| 162 | - "DELETE bank_question_image \ | 137 | + r#"DELETE FROM bank_question_image |
| 163 | - WHERE bank_question = $b AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", | 138 | + WHERE bank_question = $1 |
| 164 | - ) | 139 | + AND slot IS NOT NULL |
| 165 | - .bind(("b", question.record())) | 140 | + AND NOT (slot = ANY($2)) |
| 166 | - .bind(("keep", keep)) | 141 | + RETURNING *"#, |
| 167 | - .await? | 142 | + question, |
| 168 | - .check()?; | 143 | + keep |
| 169 | - Ok(result.take::<Vec<BankQuestionImage>>(0)?) | 144 | + ) |
| 145 | + .fetch_all(db) | ||
| 146 | + .await?; | ||
| 147 | + Ok(rows) | ||
| 170 | } | 148 | } |
| 171 | 149 | ||
| 172 | pub async fn delete( | 150 | pub async fn delete( |
| 173 | db: &Database, | 151 | db: &Database, |
| 174 | image: BankQuestionImage, | 152 | image: BankQuestionImage, |
| 175 | ) -> Result<BankQuestionImage, AppError> { | 153 | ) -> 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?; | ||
| 177 | deleted.ok_or(AppError::NotFound) | 164 | deleted.ok_or(AppError::NotFound) |
| 178 | } | 165 | } |
| 179 | 166 | ||
src/db/pool_question.rsmodified+176 -192
| @@ -1,137 +1,85 @@ | |||
| 1 | //! The `pool_question` table: ask/insert, the two listings, the guarded | 1 | //! The `pool_question` table: ask/insert, the two listings, the guarded |
| 2 | //! approve that rides the publish counters along, the pending-only image | 2 | //! approve that rides the publish counters along, the pending-only image |
| 3 | -//! writes, and the delete that cascades solutions — plus | 3 | +//! writes, and the delete that cascades solutions. The pure entity and |
| 4 | -//! [`bump_question_and_write`], the existence-move every child write goes | 4 | +//! newtypes live in [`crate::domain::pool_question`]; the web layer reaches |
| 5 | -//! through. The pure entity and newtypes live in | 5 | +//! these through [`crate::service::pool_question`]. |
| 6 | -//! [`crate::domain::pool_question`]; the web layer reaches these through | 6 | + |
| 7 | -//! [`crate::service::pool_question`]. | 7 | +use crate::constant::{STATUS_APPROVED, STATUS_PENDING}; |
| 8 | - | 8 | +use crate::database::{Database, tx_with_retry}; |
| 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}; | ||
| 15 | use crate::domain::note_file::FileContentType; | 9 | use crate::domain::note_file::FileContentType; |
| 16 | use crate::domain::pool_question::{PoolQuestion, PoolQuestionId}; | 10 | use crate::domain::pool_question::{PoolQuestion, PoolQuestionId}; |
| 17 | use crate::domain::solution::Solution; | 11 | use crate::domain::solution::Solution; |
| 18 | use crate::domain::user::UserId; | 12 | use crate::domain::user::UserId; |
| 19 | use crate::error::AppError; | 13 | use crate::error::AppError; |
| 20 | 14 | ||
| 21 | -/// Move the question's `asked_at` **and** run `statement` — a write to | 15 | +pub async fn insert(db: &Database, question: PoolQuestion) -> Result<PoolQuestion, AppError> { |
| 22 | -/// something hanging off a question — in one transaction, handing back the row | 16 | + let row = sqlx::query_as!( |
| 23 | -/// it returned. `NotFound` means the question is gone and nothing was written. | 17 | + PoolQuestion, |
| 24 | -/// | 18 | + r#"INSERT INTO pool_question (id, asker, title, body, status, asked_at) |
| 25 | -/// The move is what makes the question's **existence** part of the child's own | 19 | + VALUES ($1, $2, $3, $4, $5, $6) |
| 26 | -/// write, the way [`crate::domain::menu::bump_menu_and_write`] does for a menu: | 20 | + RETURNING *"#, |
| 27 | -/// the `UPDATE` matches nothing once the row is deleted, and a delete racing | 21 | + question.id, |
| 28 | -/// this one touches the very key this transaction writes, so the two cannot | 22 | + question.asker, |
| 29 | -/// both commit. Reading the question first does *not* survive that race — the | 23 | + question.title, |
| 30 | -/// read sees a row [`delete`] has removed but not committed, while its | 24 | + question.body, |
| 31 | -/// `DELETE solution WHERE question = $q` ran on a snapshot predating this | 25 | + question.status, |
| 32 | -/// insert, so both commit and the child outlives its question with neither | 26 | + question.asked_at, |
| 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"], | ||
| 67 | ) | 27 | ) |
| 28 | + .fetch_one(db) | ||
| 68 | .await?; | 29 | .await?; |
| 69 | - // An aborted transaction errors *every* slot, most with a generic "not | 30 | + Ok(row) |
| 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())) | ||
| 91 | } | 31 | } |
| 92 | 32 | ||
| 93 | pub async fn read(db: &Database, id: &PoolQuestionId) -> Result<Option<PoolQuestion>, AppError> { | 33 | 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) | ||
| 95 | } | 42 | } |
| 96 | 43 | ||
| 97 | /// Every question, newest first — the teacher+ view (approval queue and | 44 | /// Every question, newest first — the teacher+ view (approval queue and |
| 98 | /// pool in one list). | 45 | /// pool in one list). |
| 99 | pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> { | 46 | pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> { |
| 100 | - let mut result = db | 47 | + let rows = sqlx::query_as!( |
| 101 | - .query("SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC") | 48 | + PoolQuestion, |
| 102 | - .await? | 49 | + "SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC", |
| 103 | - .check()?; | 50 | + ) |
| 104 | - Ok(result.take::<Vec<PoolQuestion>>(0)?) | 51 | + .fetch_all(db) |
| 52 | + .await?; | ||
| 53 | + Ok(rows) | ||
| 105 | } | 54 | } |
| 106 | 55 | ||
| 107 | /// The pool as a non-staff user sees it, newest first: every approved | 56 | /// The pool as a non-staff user sees it, newest first: every approved |
| 108 | /// question, plus the caller's own pending ones. | 57 | /// question, plus the caller's own pending ones. |
| 109 | pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQuestion>, AppError> { | 58 | pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQuestion>, AppError> { |
| 110 | - let mut result = db | 59 | + let rows = sqlx::query_as!( |
| 111 | - .query( | 60 | + PoolQuestion, |
| 112 | - "SELECT * FROM pool_question WHERE status = $approved OR asker = $usr \ | 61 | + r#"SELECT * FROM pool_question |
| 113 | - ORDER BY asked_at DESC, id DESC", | 62 | + WHERE status = $1 OR asker = $2 |
| 114 | - ) | 63 | + ORDER BY asked_at DESC, id DESC"#, |
| 115 | - .bind(("approved", STATUS_APPROVED)) | 64 | + STATUS_APPROVED, |
| 116 | - .bind(("usr", user.record())) | 65 | + user |
| 117 | - .await? | 66 | + ) |
| 118 | - .check()?; | 67 | + .fetch_all(db) |
| 119 | - Ok(result.take::<Vec<PoolQuestion>>(0)?) | 68 | + .await?; |
| 69 | + Ok(rows) | ||
| 120 | } | 70 | } |
| 121 | 71 | ||
| 122 | /// Publish a pending question into the pool, stamping who approved it. | 72 | /// 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 |
| 124 | /// racing approvals exactly one wins, and an approve can never land on a | 74 | /// racing approvals exactly one wins, and an approve can never land on a |
| 125 | /// question deleted mid-flight. `None` = the question wasn't pending | 75 | /// question deleted mid-flight. `None` = the question wasn't pending |
| 126 | /// (already approved, or gone) — the caller sorts out which. | 76 | /// (already approved, or gone) — the caller sorts out which. |
| 127 | /// | 77 | /// |
| 128 | -/// Two lifetime badge counters ride that same guard, inside this | 78 | +/// Two lifetime badge counters ride that same guard inside this |
| 129 | /// transaction: the approver's `pool_approved_total` and the *asker's* | 79 | /// transaction: the approver's `pool_approved_total` and the *asker's* |
| 130 | -/// `pool_published_total`. Both hang off `array::len($done) > 0` — the | 80 | +/// `pool_published_total`. Both move only when the guard's own verdict |
| 131 | -/// guard's own verdict — so the pair moves once per real transition and | 81 | +/// landed, so the pair moves once per real transition and never on a second |
| 132 | -/// never on a second approve of an already-approved question. | 82 | +/// 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. | ||
| 135 | /// | 83 | /// |
| 136 | /// Two rules keep the pair unfarmable, one per side of the transition. | 84 | /// Two rules keep the pair unfarmable, one per side of the transition. |
| 137 | /// | 85 | /// |
| @@ -144,56 +92,56 @@ pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQue | |||
| 144 | /// | 92 | /// |
| 145 | /// And a *self*-approval — a teacher+ approving a question they asked | 93 | /// And a *self*-approval — a teacher+ approving a question they asked |
| 146 | /// themselves, which the route deliberately still allows — moves neither | 94 | /// themselves, which the route deliberately still allows — moves neither |
| 147 | -/// counter, hence the `$done[0].asker != $by` half of the condition. It is | 95 | +/// counter. It is the same farm from the other end (ask, approve, delete, |
| 148 | -/// the same farm from the other end (ask, approve, delete, repeat, with no | 96 | +/// repeat, with no second person involved), and the two together are why a |
| 149 | -/// second person involved), and the two together are why a counter can only | 97 | +/// counter can only move when one person's work was judged by another's. |
| 150 | -/// move when one person's work was judged by another's. Nothing else about | 98 | +/// Nothing else about a self-approval changes: same 200, same freeze, same |
| 151 | -/// a self-approval changes: same 200, same freeze, same stamp — this skips | 99 | +/// stamp — this skips the credit, not the approval. |
| 152 | -/// the credit, not the approval. | ||
| 153 | /// | 100 | /// |
| 154 | -/// Re-sent while the store answers "conflict, retry": the guard reads a | 101 | +/// Rides the retry loop because the counter bumps lock user rows every |
| 155 | -/// column a rival approve writes, and both counters sit on user rows every | 102 | +/// other counter site writes too; a deadlock between two approvals takes a |
| 156 | -/// other counter site writes too. Sound to re-send — every statement is an | 103 | +/// round and lands the next attempt. |
| 157 | -/// `UPDATE`, none of which can legitimately answer "already exists" — and a | ||
| 158 | -/// lost round aborts having written nothing, increments included. | ||
| 159 | pub async fn approve( | 104 | pub async fn approve( |
| 160 | db: &Database, | 105 | db: &Database, |
| 161 | id: &PoolQuestionId, | 106 | id: &PoolQuestionId, |
| 162 | approver: &UserId, | 107 | approver: &UserId, |
| 163 | ) -> Result<Option<PoolQuestion>, AppError> { | 108 | ) -> Result<Option<PoolQuestion>, AppError> { |
| 164 | - let (mut result, mut errors) = transaction_with_retry( | 109 | + tx_with_retry(db, false, async |tx| { |
| 165 | - db, | 110 | + let approved = sqlx::query_as!( |
| 166 | - &format!( | 111 | + PoolQuestion, |
| 167 | - "BEGIN TRANSACTION; | 112 | + r#"UPDATE pool_question SET status = $2, approved_by = $3 |
| 168 | - LET $done = (UPDATE $q SET status = $approved, approved_by = $by | 113 | + WHERE id = $1 AND status = $4 |
| 169 | - WHERE status = $pending RETURN AFTER); | 114 | + RETURNING *"#, |
| 170 | - IF array::len($done) > 0 AND $done[0].asker != $by {{ | 115 | + *id, |
| 171 | - UPDATE $by SET | 116 | + STATUS_APPROVED, |
| 172 | - {POOL_APPROVED_TOTAL_FIELD} = ({POOL_APPROVED_TOTAL_FIELD} ?? 0) + 1; | 117 | + approver, |
| 173 | - LET $asker = $done[0].asker; | 118 | + STATUS_PENDING, |
| 174 | - UPDATE $asker SET | 119 | + ) |
| 175 | - {POOL_PUBLISHED_TOTAL_FIELD} = ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0) + 1; | 120 | + .fetch_optional(tx) |
| 176 | - }}; | 121 | + .await?; |
| 177 | - RETURN $done; | 122 | + if let Some(question) = &approved { |
| 178 | - COMMIT TRANSACTION;" | 123 | + if question.asker != *approver { |
| 179 | - ), | 124 | + // The counter columns are NOT NULL DEFAULT 0 — the old |
| 180 | - &[ | 125 | + // absent-reads-as-zero coalesce is gone with the schema. |
| 181 | - ("q".into(), id.record().into_value()), | 126 | + sqlx::query!( |
| 182 | - ("approved".into(), STATUS_APPROVED.to_string().into_value()), | 127 | + "UPDATE app_user SET pool_approved_total = pool_approved_total + 1 |
| 183 | - ("by".into(), approver.record().into_value()), | 128 | + WHERE id = $1", |
| 184 | - ("pending".into(), STATUS_PENDING.to_string().into_value()), | 129 | + approver |
| 185 | - ], | 130 | + ) |
| 186 | - &[], | 131 | + .execute(tx) |
| 187 | - ) | 132 | + .await?; |
| 188 | - .await?; | 133 | + sqlx::query!( |
| 189 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | 134 | + "UPDATE app_user SET pool_published_total = pool_published_total + 1 |
| 190 | - return Err(error.into()); | 135 | + WHERE id = $1", |
| 191 | - } | 136 | + question.asker |
| 192 | - // The trailing `RETURN` is always the last statement before `COMMIT`, | 137 | + ) |
| 193 | - // so its slot follows the statement count rather than a hand-kept | 138 | + .execute(tx) |
| 194 | - // number (`num_statements` counts `BEGIN` and `COMMIT` too, hence -2). | 139 | + .await?; |
| 195 | - let slot = result.num_statements().saturating_sub(2); | 140 | + } |
| 196 | - Ok(result.take::<Vec<PoolQuestion>>(slot)?.into_iter().next()) | 141 | + } |
| 142 | + Ok(approved) | ||
| 143 | + }) | ||
| 144 | + .await | ||
| 197 | } | 145 | } |
| 198 | 146 | ||
| 199 | /// Point the question at a freshly written image blob. Guarded on | 147 | /// Point the question at a freshly written image blob. Guarded on |
| @@ -202,6 +150,10 @@ pub async fn approve( | |||
| 202 | /// loses the race gets `None` (and the caller takes the orphan blob back | 150 | /// loses the race gets `None` (and the caller takes the orphan blob back |
| 203 | /// off disk). Returns the *before* row — its `image_file` is the replaced | 151 | /// off disk). Returns the *before* row — its `image_file` is the replaced |
| 204 | /// blob the caller must remove. | 152 | /// 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. | ||
| 205 | pub async fn set_image( | 157 | pub async fn set_image( |
| 206 | db: &Database, | 158 | db: &Database, |
| 207 | id: &PoolQuestionId, | 159 | id: &PoolQuestionId, |
| @@ -209,19 +161,35 @@ pub async fn set_image( | |||
| 209 | content_type: &FileContentType, | 161 | content_type: &FileContentType, |
| 210 | size: i64, | 162 | size: i64, |
| 211 | ) -> Result<Option<PoolQuestion>, AppError> { | 163 | ) -> Result<Option<PoolQuestion>, AppError> { |
| 212 | - let mut result = db | 164 | + tx_with_retry(db, false, async |tx| { |
| 213 | - .query( | 165 | + let before = sqlx::query_as!( |
| 214 | - "UPDATE $q SET image_file = $file, image_content_type = $ct, image_size = $size \ | 166 | + PoolQuestion, |
| 215 | - WHERE status = $pending RETURN BEFORE", | 167 | + "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE", |
| 168 | + *id | ||
| 216 | ) | 169 | ) |
| 217 | - .bind(("q", id.record())) | 170 | + .fetch_optional(tx) |
| 218 | - .bind(("file", file.to_string())) | 171 | + .await?; |
| 219 | - .bind(("ct", content_type.clone())) | 172 | + let Some(before) = before else { |
| 220 | - .bind(("size", size)) | 173 | + return Ok(None); |
| 221 | - .bind(("pending", STATUS_PENDING)) | 174 | + }; |
| 222 | - .await? | 175 | + let written = sqlx::query!( |
| 223 | - .check()?; | 176 | + r#"UPDATE pool_question |
| 224 | - Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next()) | 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 | ||
| 225 | } | 193 | } |
| 226 | 194 | ||
| 227 | /// Detach the question's image (pending only, like `set_image`). Returns | 195 | /// Detach the question's image (pending only, like `set_image`). Returns |
| @@ -230,16 +198,32 @@ pub async fn clear_image( | |||
| 230 | db: &Database, | 198 | db: &Database, |
| 231 | id: &PoolQuestionId, | 199 | id: &PoolQuestionId, |
| 232 | ) -> Result<Option<PoolQuestion>, AppError> { | 200 | ) -> Result<Option<PoolQuestion>, AppError> { |
| 233 | - let mut result = db | 201 | + tx_with_retry(db, false, async |tx| { |
| 234 | - .query( | 202 | + let before = sqlx::query_as!( |
| 235 | - "UPDATE $q SET image_file = NONE, image_content_type = NONE, image_size = NONE \ | 203 | + PoolQuestion, |
| 236 | - WHERE status = $pending RETURN BEFORE", | 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, | ||
| 237 | ) | 218 | ) |
| 238 | - .bind(("q", id.record())) | 219 | + .execute(tx) |
| 239 | - .bind(("pending", STATUS_PENDING)) | 220 | + .await?; |
| 240 | - .await? | 221 | + if written.rows_affected() == 0 { |
| 241 | - .check()?; | 222 | + return Ok(None); |
| 242 | - Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next()) | 223 | + } |
| 224 | + Ok(Some(before)) | ||
| 225 | + }) | ||
| 226 | + .await | ||
| 243 | } | 227 | } |
| 244 | 228 | ||
| 245 | /// Delete the question and its solutions in one transaction, returning | 229 | /// Delete the question and its solutions in one transaction, returning |
| @@ -247,34 +231,34 @@ pub async fn clear_image( | |||
| 247 | /// caller can take every image blob off disk (solutions carry photos too, | 231 | /// caller can take every image blob off disk (solutions carry photos too, |
| 248 | /// and a row-only sweep would strand theirs forever). | 232 | /// and a row-only sweep would strand theirs forever). |
| 249 | /// | 233 | /// |
| 250 | -/// Rides the retry because a solution offer now writes this very row | 234 | +/// Children before the parent, so the foreign keys never refuse the parent |
| 251 | -/// ([`bump_question_and_write`]): the two contend by design, and a lost | 235 | +/// delete. `cascade = true` because a solution offer committing inside this |
| 252 | -/// round through a bare `check()` was a 500 for a delete that only had to | 236 | +/// window makes the parent delete answer 23503 — a mid-cascade race the |
| 253 | -/// be re-sent. Admissible — a `DELETE` can never answer "already exists". | 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. | ||
| 254 | pub async fn delete( | 240 | pub async fn delete( |
| 255 | db: &Database, | 241 | db: &Database, |
| 256 | id: &PoolQuestionId, | 242 | id: &PoolQuestionId, |
| 257 | ) -> Result<Option<(PoolQuestion, Vec<Solution>)>, AppError> { | 243 | ) -> Result<Option<(PoolQuestion, Vec<Solution>)>, AppError> { |
| 258 | - let (mut result, mut errors) = transaction_with_retry( | 244 | + tx_with_retry(db, true, async |tx| { |
| 259 | - db, | 245 | + let solutions = sqlx::query_as!( |
| 260 | - "BEGIN TRANSACTION; | 246 | + Solution, |
| 261 | - DELETE solution WHERE question = $q RETURN BEFORE; | 247 | + "DELETE FROM solution WHERE question = $1 RETURNING *", |
| 262 | - DELETE $q RETURN BEFORE; | 248 | + *id |
| 263 | - COMMIT TRANSACTION;", | 249 | + ) |
| 264 | - &[("q".into(), id.record().into_value())], | 250 | + .fetch_all(tx) |
| 265 | - &[], | 251 | + .await?; |
| 266 | - ) | 252 | + let question = sqlx::query_as!( |
| 267 | - .await?; | 253 | + PoolQuestion, |
| 268 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | 254 | + "DELETE FROM pool_question WHERE id = $1 RETURNING *", |
| 269 | - return Err(error.into()); | 255 | + *id |
| 270 | - } | 256 | + ) |
| 271 | - // Slots count BEGIN: the solution sweep is slot 1, the question slot 2. | 257 | + .fetch_optional(tx) |
| 272 | - let solutions = result.take::<Vec<Solution>>(1)?; | 258 | + .await?; |
| 273 | - Ok(result | 259 | + Ok(question.map(|question| (question, solutions))) |
| 274 | - .take::<Vec<PoolQuestion>>(2)? | 260 | + }) |
| 275 | - .into_iter() | 261 | + .await |
| 276 | - .next() | ||
| 277 | - .map(|question| (question, solutions))) | ||
| 278 | } | 262 | } |
| 279 | 263 | ||
| 280 | #[cfg(test)] | 264 | #[cfg(test)] |
src/db/solution.rsmodified+127 -78
| @@ -1,54 +1,54 @@ | |||
| 1 | -//! The `solution` table: offers (through the pool question's | 1 | +//! The `solution` table: offers (their question's existence enforced by the |
| 2 | -//! existence-move), the question-scoped reads and page, the grouped counts, | 2 | +//! real foreign key), the question-scoped read and page, the grouped counts, |
| 3 | //! and the unconditional body/image writes of an unmoderated row. The pure | 3 | //! and the unconditional body/image writes of an unmoderated row. The pure |
| 4 | //! entity and newtypes live in [`crate::domain::solution`]; the web layer | 4 | //! entity and newtypes live in [`crate::domain::solution`]; the web layer |
| 5 | //! reaches these through [`crate::service::solution`]. | 5 | //! reaches these through [`crate::service::solution`]. |
| 6 | 6 | ||
| 7 | use std::collections::HashMap; | 7 | use std::collections::HashMap; |
| 8 | 8 | ||
| 9 | -use surrealdb::types::{RecordId, SurrealValue}; | 9 | +use crate::database::{Database, tx_with_retry}; |
| 10 | - | ||
| 11 | -use crate::database::Database; | ||
| 12 | use crate::db::page::PagedList; | 10 | use crate::db::page::PagedList; |
| 13 | -use crate::db::pool_question::bump_question_and_write; | ||
| 14 | use crate::domain::note_file::FileContentType; | 11 | use crate::domain::note_file::FileContentType; |
| 15 | use crate::domain::pool_question::PoolQuestionId; | 12 | use crate::domain::pool_question::PoolQuestionId; |
| 16 | use crate::domain::solution::{Solution, SolutionBody, SolutionId}; | 13 | use crate::domain::solution::{Solution, SolutionBody, SolutionId}; |
| 17 | use crate::error::AppError; | 14 | use crate::error::AppError; |
| 18 | 15 | ||
| 19 | -/// One `GROUP BY question` row of [`counts_for`]. | ||
| 20 | -#[derive(SurrealValue)] | ||
| 21 | -struct SolutionCount { | ||
| 22 | - question: PoolQuestionId, | ||
| 23 | - n: i64, | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | /// Offer the solution. `NotFound` = the question is gone, and nothing was | 16 | /// Offer the solution. `NotFound` = the question is gone, and nothing was |
| 27 | -/// written: the create rides [`bump_question_and_write`], so the question's | 17 | +/// written: the insert's foreign key (`solution_question_fkey`) refuses an |
| 28 | -/// existence is a *write* to its row rather than a read the handler made a | 18 | +/// orphan the old existence-move transaction spent five statements dodging — |
| 29 | -/// moment earlier — a bare create landing inside | 19 | +/// a bare create landing inside |
| 30 | -/// [`crate::db::pool_question::delete`]'s | 20 | +/// [`crate::db::pool_question::delete`]'s window used to be swept by |
| 31 | -/// window was swept by nothing and left a solution no route could ever | 21 | +/// nothing and left a solution no route could ever reach or remove (every |
| 32 | -/// reach or remove (every path to one goes through its question), photo | 22 | +/// path to one goes through its question), photo blob included. |
| 33 | -/// blob included. | ||
| 34 | /// | 23 | /// |
| 35 | -/// Re-sendable despite the `CREATE`: `$id` is a ULID minted once per call | 24 | +/// The author's own foreign key never fires in practice (the request |
| 36 | -/// on a table with no `UNIQUE` index, so a re-send cannot answer "already | 25 | +/// carries a live session user) and stays a database error if it ever does; |
| 37 | -/// exists" — the one thing the retry could not survive. | 26 | +/// only the question's key maps to the 404. |
| 38 | pub async fn insert(db: &Database, solution: Solution) -> Result<Solution, AppError> { | 27 | 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 | 28 | + match sqlx::query_as!( |
| 40 | - let (question, id) = (solution.question.clone(), solution.id.record()); | 29 | + Solution, |
| 41 | - bump_question_and_write( | 30 | + r#"INSERT INTO solution (id, question, author, body, offered_at) |
| 42 | - &question, | 31 | + VALUES ($1, $2, $3, $4, $5) |
| 43 | - "CREATE $id CONTENT $solution", | 32 | + RETURNING *"#, |
| 44 | - vec![ | 33 | + solution.id, |
| 45 | - ("id".into(), id.into_value()), | 34 | + solution.question, |
| 46 | - ("solution".into(), solution.into_value()), | 35 | + solution.author, |
| 47 | - ], | 36 | + solution.body, |
| 48 | - db, | 37 | + solution.offered_at, |
| 49 | ) | 38 | ) |
| 50 | - .await? | 39 | + .fetch_one(db) |
| 51 | - .ok_or_else(|| AppError::Internal("failed to create solution".into())) | 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") | ||
| 52 | } | 52 | } |
| 53 | 53 | ||
| 54 | /// Read a solution only if it belongs to `question` — keeps the nested | 54 | /// Read a solution only if it belongs to `question` — keeps the nested |
| @@ -58,32 +58,40 @@ pub async fn read_for( | |||
| 58 | id: &SolutionId, | 58 | id: &SolutionId, |
| 59 | question: &PoolQuestionId, | 59 | question: &PoolQuestionId, |
| 60 | ) -> Result<Option<Solution>, AppError> { | 60 | ) -> Result<Option<Solution>, AppError> { |
| 61 | - let solution: Option<Solution> = db.select(id.record()).await?; | 61 | + let row = sqlx::query_as!( |
| 62 | - Ok(solution.filter(|solution| &solution.question == question)) | 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) | ||
| 63 | } | 70 | } |
| 64 | 71 | ||
| 65 | /// The question's solutions, oldest first — a discussion reads downward. | 72 | /// The question's solutions, oldest first — a discussion reads downward. |
| 66 | /// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond | 73 | /// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond |
| 67 | -/// offers *stable* across re-queries, not insertion-ordered (ULID low bits | 74 | +/// offers *stable* across re-queries (the ids are write-ordered UUIDv7, so |
| 68 | -/// are random within a millisecond, so same-ms order is arbitrary). | 75 | +/// same-ms rows still sort by mint order). |
| 69 | pub async fn list_for( | 76 | pub async fn list_for( |
| 70 | db: &Database, | 77 | db: &Database, |
| 71 | question: &PoolQuestionId, | 78 | question: &PoolQuestionId, |
| 72 | limit: Option<i64>, | 79 | limit: Option<i64>, |
| 73 | offset: i64, | 80 | offset: i64, |
| 74 | ) -> Result<(Vec<Solution>, i64), AppError> { | 81 | ) -> Result<(Vec<Solution>, i64), AppError> { |
| 82 | + // `.uuid()` feeds the builder its raw bind value — exact, typed. | ||
| 75 | PagedList::new( | 83 | PagedList::new( |
| 76 | - "solution WHERE question = $q", | 84 | + "solution WHERE question = $1", |
| 77 | "ORDER BY offered_at ASC, id ASC", | 85 | "ORDER BY offered_at ASC, id ASC", |
| 78 | ) | 86 | ) |
| 79 | - .bind("q", question.record()) | 87 | + .bind(question.uuid()) |
| 80 | .run(limit, offset, db) | 88 | .run(limit, offset, db) |
| 81 | .await | 89 | .await |
| 82 | } | 90 | } |
| 83 | 91 | ||
| 84 | /// Per-question solution tallies for a page of questions, in one grouped | 92 | /// Per-question solution tallies for a page of questions, in one grouped |
| 85 | /// query — a per-row `count()` would cost a query per question. Keys are | 93 | /// 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 |
| 87 | /// the caller reads misses as zero. | 95 | /// the caller reads misses as zero. |
| 88 | pub async fn counts_for( | 96 | pub async fn counts_for( |
| 89 | db: &Database, | 97 | db: &Database, |
| @@ -92,18 +100,19 @@ pub async fn counts_for( | |||
| 92 | if questions.is_empty() { | 100 | if questions.is_empty() { |
| 93 | return Ok(HashMap::new()); | 101 | return Ok(HashMap::new()); |
| 94 | } | 102 | } |
| 95 | - let ids: Vec<RecordId> = questions.iter().map(|question| question.record()).collect(); | 103 | + let ids: Vec<PoolQuestionId> = questions.iter().copied().collect(); |
| 96 | - let mut result = db | 104 | + let rows = sqlx::query!( |
| 97 | - .query( | 105 | + r#"SELECT question AS "question: PoolQuestionId", count(*) AS n |
| 98 | - "SELECT question, count() AS n FROM solution WHERE question IN $qs GROUP BY question", | 106 | + FROM solution |
| 99 | - ) | 107 | + WHERE question = ANY($1) |
| 100 | - .bind(("qs", ids)) | 108 | + GROUP BY question"#, |
| 101 | - .await? | 109 | + ids, |
| 102 | - .check()?; | 110 | + ) |
| 103 | - Ok(result | 111 | + .fetch_all(db) |
| 104 | - .take::<Vec<SolutionCount>>(0)? | 112 | + .await?; |
| 113 | + Ok(rows | ||
| 105 | .into_iter() | 114 | .into_iter() |
| 106 | - .map(|row| (row.question.key().to_string(), row.n)) | 115 | + .map(|row| (row.question.key(), row.n)) |
| 107 | .collect()) | 116 | .collect()) |
| 108 | } | 117 | } |
| 109 | 118 | ||
| @@ -115,13 +124,15 @@ pub async fn set_body( | |||
| 115 | id: &SolutionId, | 124 | id: &SolutionId, |
| 116 | body: &SolutionBody, | 125 | body: &SolutionBody, |
| 117 | ) -> Result<Option<Solution>, AppError> { | 126 | ) -> Result<Option<Solution>, AppError> { |
| 118 | - let mut result = db | 127 | + let row = sqlx::query_as!( |
| 119 | - .query("UPDATE $s SET body = $b RETURN AFTER") | 128 | + Solution, |
| 120 | - .bind(("s", id.record())) | 129 | + "UPDATE solution SET body = $2 WHERE id = $1 RETURNING *", |
| 121 | - .bind(("b", body.clone())) | 130 | + id, |
| 122 | - .await? | 131 | + body |
| 123 | - .check()?; | 132 | + ) |
| 124 | - Ok(result.take::<Vec<Solution>>(0)?.into_iter().next()) | 133 | + .fetch_optional(db) |
| 134 | + .await?; | ||
| 135 | + Ok(row) | ||
| 125 | } | 136 | } |
| 126 | 137 | ||
| 127 | /// Point the solution at a freshly written image blob. Unconditional for | 138 | /// Point the solution at a freshly written image blob. Unconditional for |
| @@ -129,6 +140,9 @@ pub async fn set_body( | |||
| 129 | /// `image_file` is the replaced blob the caller must remove; `None` means | 140 | /// `image_file` is the replaced blob the caller must remove; `None` means |
| 130 | /// the row was deleted mid-flight (the fresh blob is the caller's orphan | 141 | /// the row was deleted mid-flight (the fresh blob is the caller's orphan |
| 131 | /// to take back off disk). | 142 | /// 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. | ||
| 132 | pub async fn set_image( | 146 | pub async fn set_image( |
| 133 | db: &Database, | 147 | db: &Database, |
| 134 | id: &SolutionId, | 148 | id: &SolutionId, |
| @@ -136,33 +150,68 @@ pub async fn set_image( | |||
| 136 | content_type: &FileContentType, | 150 | content_type: &FileContentType, |
| 137 | size: i64, | 151 | size: i64, |
| 138 | ) -> Result<Option<Solution>, AppError> { | 152 | ) -> Result<Option<Solution>, AppError> { |
| 139 | - let mut result = db | 153 | + tx_with_retry(db, false, async |tx| { |
| 140 | - .query("UPDATE $s SET image_file = $file, image_content_type = $ct, image_size = $size RETURN BEFORE") | 154 | + let before = sqlx::query_as!( |
| 141 | - .bind(("s", id.record())) | 155 | + Solution, |
| 142 | - .bind(("file", file.to_string())) | 156 | + "SELECT * FROM solution WHERE id = $1 FOR UPDATE", |
| 143 | - .bind(("ct", content_type.clone())) | 157 | + *id |
| 144 | - .bind(("size", size)) | 158 | + ) |
| 145 | - .await? | 159 | + .fetch_optional(tx) |
| 146 | - .check()?; | 160 | + .await?; |
| 147 | - Ok(result.take::<Vec<Solution>>(0)?.into_iter().next()) | 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 | ||
| 148 | } | 178 | } |
| 149 | 179 | ||
| 150 | /// Detach the solution's image. Returns the *before* row — its | 180 | /// Detach the solution's image. Returns the *before* row — its |
| 151 | /// `image_file` is the blob the caller must remove. | 181 | /// `image_file` is the blob the caller must remove. |
| 152 | pub async fn clear_image(db: &Database, id: &SolutionId) -> Result<Option<Solution>, AppError> { | 182 | pub async fn clear_image(db: &Database, id: &SolutionId) -> Result<Option<Solution>, AppError> { |
| 153 | - let mut result = db | 183 | + tx_with_retry(db, false, async |tx| { |
| 154 | - .query( | 184 | + let before = sqlx::query_as!( |
| 155 | - "UPDATE $s SET image_file = NONE, image_content_type = NONE, image_size = NONE \ | 185 | + Solution, |
| 156 | - RETURN BEFORE", | 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, | ||
| 157 | ) | 199 | ) |
| 158 | - .bind(("s", id.record())) | 200 | + .execute(tx) |
| 159 | - .await? | 201 | + .await?; |
| 160 | - .check()?; | 202 | + Ok(Some(before)) |
| 161 | - Ok(result.take::<Vec<Solution>>(0)?.into_iter().next()) | 203 | + }) |
| 204 | + .await | ||
| 162 | } | 205 | } |
| 163 | 206 | ||
| 164 | pub async fn delete(db: &Database, solution: Solution) -> Result<Solution, AppError> { | 207 | 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?; | ||
| 166 | deleted.ok_or(AppError::NotFound) | 215 | deleted.ok_or(AppError::NotFound) |
| 167 | } | 216 | } |
| 168 | 217 | ||
src/web/questions.rsmodified+2 -2
| @@ -482,7 +482,7 @@ async fn upload_image( | |||
| 482 | let upload = read_image_upload(&st, &mut multipart).await?; | 482 | let upload = read_image_upload(&st, &mut multipart).await?; |
| 483 | let size = upload.size(); | 483 | let size = upload.size(); |
| 484 | 484 | ||
| 485 | - let file = ulid::Ulid::generate().to_string(); | 485 | + let file = crate::domain::monotonic_id::next_uuid().to_string(); |
| 486 | store_blob(&st, &file, &upload.data, || async { | 486 | store_blob(&st, &file, &upload.data, || async { |
| 487 | match pool_question::set_image(&st.db, question.get_id(), &file, &upload.content_type, size) | 487 | match pool_question::set_image(&st.db, question.get_id(), &file, &upload.content_type, size) |
| 488 | .await? | 488 | .await? |
| @@ -808,7 +808,7 @@ async fn upload_solution_image( | |||
| 808 | let upload = read_image_upload(&st, &mut multipart).await?; | 808 | let upload = read_image_upload(&st, &mut multipart).await?; |
| 809 | let size = upload.size(); | 809 | let size = upload.size(); |
| 810 | 810 | ||
| 811 | - let file = ulid::Ulid::generate().to_string(); | 811 | + let file = crate::domain::monotonic_id::next_uuid().to_string(); |
| 812 | store_blob(&st, &file, &upload.data, || async { | 812 | store_blob(&st, &file, &upload.data, || async { |
| 813 | match solution::set_image(&st.db, solution.get_id(), &file, &upload.content_type, size) | 813 | match solution::set_image(&st.db, solution.get_id(), &file, &upload.content_type, size) |
| 814 | .await? | 814 | .await? |