forge
Explore
Log in

Don't you dare go Hollow

πŸ—ƒοΈ wip: port exam db layer to sqlx (checkpoint)

Browse files at this commit

41359b3353ec48ac579ae00d6ee897447444298eAhmet Kaan GümüşParent: b3ab76f

7 changed files +1551 -1158

src/db/answer_image.rsmodified+146 -136
@@ -4,114 +4,96 @@
44 //! ids and the fresh-blob-name constructor β€” lives in
55 //! [`crate::domain::answer_image`]; the blob bytes stay the web layer's.
66
7-use surrealdb::types::SurrealValue;
7+use sqlx::PgConnection;
88
9-use crate::constant::EXAM_RESULT_COUNT_FIELD;
10-use crate::database::{Database, transaction_with_retry};
11-use crate::domain::answer_image::{AnswerImage, AnswerImageId};
9+use crate::database::{Database, tx_with_retry};
10+use crate::domain::answer_image::AnswerImage;
1211 use crate::domain::course::CourseId;
1312 use crate::domain::exam::ExamId;
1413 use crate::domain::exam_question::ExamQuestionId;
1514 use crate::domain::user::UserId;
1615 use crate::error::AppError;
1716
18-/// What one [`upsert`] transaction returns: the row it stored and
19-/// the blob name it replaced. Both are arrays because SurrealDB drops an object
20-/// key valued `NONE` on the way out, while an empty array survives β€” "nothing
21-/// was replaced" has to be readable, not missing.
22-#[derive(SurrealValue)]
23-struct UpsertOutcome {
24- stored: Vec<AnswerImage>,
25- replaced: Vec<String>,
26-}
27-
28-/// Create or replace the student's drawing for the question β€” the
29-/// deterministic id makes this the whole "one drawing per student per
30-/// question" story β€” handing back what it stored plus the blob name it
31-/// replaced, for the caller to take off disk.
17+/// Create or replace the student's drawing for the question β€” the natural
18+/// (question, user, seq) primary key makes this the whole "one drawing per
19+/// student per question per sitting" story β€” handing back what it stored
20+/// plus the blob name it replaced, for the caller to take off disk.
3221 ///
33-/// The replaced name is read *here*, inside this transaction, not by the
34-/// caller in front of it: two uploads to one (question, user, seq) both
35-/// write this row, so they contend and the loser re-reads the winner's blob
36-/// name, where two pre-reads both saw the *old* blob and left the loser's
37-/// fresh one on disk with nothing pointing at it. Same shape as
22+/// The replaced name is read *inside this transaction*, not by the caller
23+/// in front of it: two uploads to one (question, user, seq) both write this
24+/// row, so they contend and the loser re-reads the winner's blob name,
25+/// where two pre-reads both saw the *old* blob and left the loser's fresh
26+/// one on disk with nothing pointing at it. Same shape as
3827 /// [`crate::db::question_image::upsert`].
3928 ///
4029 /// `NotFound` = the exam is gone, and the drawing was *not* written. The
41-/// write moves the exam's mark counter and puts it straight back, in this
42-/// one transaction, so the exam's existence is something this write
43-/// *writes* rather than something a gate read a moment earlier: a bare
44-/// upsert landing after [`delete`](crate::db::exam::delete)
45-/// removed the exam but before it committed was swept by nothing β€” its
46-/// `DELETE answer_image WHERE exam = $ex` ran on a snapshot predating this
47-/// row β€” and both sides reported success. That stranded the blob as well as
48-/// the row: `delete_exam` collects the names to unlink *before* it calls
49-/// the delete, so bytes written after that snapshot stay on disk forever.
50-/// This is the shape [`crate::db::exam_answer::save`] takes
51-/// for the text half of the same answer sheet, and for the same reason.
52-///
53-/// The restore is by captured value, `NONE` included, so the row is
54-/// byte-identical afterwards and a teacher's PATCH β€” which pins that
55-/// counter β€” is not refused because a student drew. Writing the same value
56-/// back would buy nothing: an `UPDATE` that leaves the document unchanged
57-/// is elided and never reaches the store's write set.
58-///
59-/// Admissible for [`transaction_with_retry`]: the `UPDATE`s, `SELECT`,
60-/// `IF`/`THROW` and `RETURN` can never answer "already exists", and the
61-/// `UPSERT`'s id is bijective with the (question, user, seq) triple this
62-/// table keys β€” a lost round wrote nothing, and re-sending resolves onto
63-/// the same row rather than colliding with it.
30+/// write locks the exam row before upserting, in this one transaction, so
31+/// the exam's existence is something this write *locks* rather than
32+/// something a gate read a moment earlier: a bare upsert landing after
33+/// [`delete`](crate::db::exam::delete) removed the exam but before it
34+/// committed was swept by nothing β€” its `DELETE answer_image WHERE exam`
35+/// ran on a snapshot predating this row β€” and both sides reported success.
36+/// That stranded the blob as well as the row: `delete_exam` collects the
37+/// names to unlink *before* it calls the delete, so bytes written after
38+/// that snapshot stay on disk forever. Locking the key the delete removes
39+/// serializes the pair β€” this is the shape
40+/// [`crate::db::exam_answer::save`] takes for the text half of the same
41+/// answer sheet, and for the same reason.
6442 pub async fn upsert(
6543 db: &Database,
6644 image: AnswerImage,
6745 ) -> Result<(AnswerImage, Option<String>), AppError> {
68- // whole-row-save-ok: image is built in place from the request, never read back, and the (question, user, seq) id is deterministic β€” replacing the row *is* the operation
69- let (exam, id) = (image.exam.record(), image.id.record());
70- let (mut result, mut errors) = transaction_with_retry(
71- db,
72- &format!(
73- "BEGIN TRANSACTION;
74- LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex);
75- LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \
76- ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);
77- IF array::len($touched) = 0 {{ THROW 'no_exam' }};
78- UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was;
79- LET $replaced = (SELECT VALUE file FROM $id);
80- LET $row = (UPSERT $id CONTENT $image RETURN AFTER);
81- RETURN {{ stored: $row, replaced: $replaced }};
82- COMMIT TRANSACTION;"
83- ),
84- &[
85- ("ex".into(), exam.into_value()),
86- ("id".into(), id.into_value()),
87- ("image".into(), image.into_value()),
88- ],
89- &["no_exam"],
46+ tx_with_retry(db, false, async |conn| {
47+ upsert_in(conn, image).await
48+ })
49+ .await
50+}
51+
52+/// The locked exam-row probe plus the upsert, on one connection.
53+pub(crate) async fn upsert_in(
54+ conn: &mut PgConnection,
55+ image: &AnswerImage,
56+) -> Result<(AnswerImage, Option<String>), AppError> {
57+ let touched = sqlx::query!(
58+ r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#,
59+ image.exam as &ExamId,
9060 )
61+ .fetch_optional(&mut *conn)
9162 .await?;
92- // An aborted transaction errors *every* slot, most with a generic "not
93- // executed" β€” only the THROW's own slot names the reason.
94- if errors
95- .values()
96- .any(|error| error.to_string().contains("no_exam"))
97- {
63+ if touched.is_none() {
9864 return Err(AppError::NotFound);
9965 }
100- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
101- return Err(error.into());
102- }
103- // The trailing `RETURN` is the last statement before `COMMIT`, so its
104- // slot follows the statement count rather than a hand-kept number;
105- // `num_statements` counts BEGIN and COMMIT.
106- let slot = result.num_statements().saturating_sub(2);
107- let failed = || AppError::Internal("failed to store answer image".into());
108- let outcome = result
109- .take::<Vec<UpsertOutcome>>(slot)?
110- .into_iter()
111- .next()
112- .ok_or_else(failed)?;
113- let stored = outcome.stored.into_iter().next().ok_or_else(failed)?;
114- Ok((stored, outcome.replaced.into_iter().next()))
66+ let replaced = sqlx::query!(
67+ r#"SELECT file FROM answer_image
68+ WHERE question = $1 AND app_user = $2 AND seq = $3"#,
69+ image.question as &ExamQuestionId,
70+ image.user as &UserId,
71+ image.seq,
72+ )
73+ .fetch_optional(&mut *conn)
74+ .await?
75+ .map(|row| row.file);
76+ let stored = sqlx::query_as!(
77+ AnswerImage,
78+ r#"INSERT INTO answer_image (exam, question, app_user, file, content_type, size, seq)
79+ VALUES ($1, $2, $3, $4, $5, $6, $7)
80+ ON CONFLICT (question, app_user, seq) DO UPDATE
81+ SET file = EXCLUDED.file, content_type = EXCLUDED.content_type,
82+ size = EXCLUDED.size
83+ RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId",
84+ app_user AS "user: UserId", seq, file,
85+ content_type AS "content_type: FileContentType", size"#,
86+ image.exam as &ExamId,
87+ image.question as &ExamQuestionId,
88+ image.user as &UserId,
89+ image.file,
90+ image.content_type,
91+ image.size,
92+ image.seq,
93+ )
94+ .fetch_one(&mut *conn)
95+ .await?;
96+ Ok((stored, replaced))
11597 }
11698
11799 /// The student's drawing for one question in one sitting, if any.
@@ -121,19 +103,33 @@ pub async fn read(
121103 user: &UserId,
122104 seq: i64,
123105 ) -> Result<Option<AnswerImage>, AppError> {
124- Ok(db
125- .select(AnswerImageId::composite(question, user, seq).record())
126- .await?)
106+ Ok(sqlx::query_as!(
107+ AnswerImage,
108+ r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
109+ app_user AS "user: UserId", seq, file,
110+ content_type AS "content_type: FileContentType", size
111+ FROM answer_image
112+ WHERE question = $1 AND app_user = $2 AND seq = $3"#,
113+ question as &ExamQuestionId,
114+ user as &UserId,
115+ seq,
116+ )
117+ .fetch_optional(db)
118+ .await?)
127119 }
128120
129121 /// Every answer drawing of the exam β€” one query for the exam-delete cascade.
130122 pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<AnswerImage>, AppError> {
131- let mut result = db
132- .query("SELECT * FROM answer_image WHERE exam = $ex")
133- .bind(("ex", exam.record()))
134- .await?
135- .check()?;
136- Ok(result.take::<Vec<AnswerImage>>(0)?)
123+ Ok(sqlx::query_as!(
124+ AnswerImage,
125+ r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
126+ app_user AS "user: UserId", seq, file,
127+ content_type AS "content_type: FileContentType", size
128+ FROM answer_image WHERE exam = $1"#,
129+ exam as &ExamId,
130+ )
131+ .fetch_all(db)
132+ .await?)
137133 }
138134
139135 /// One student's answer drawings for a single sitting β€” the parallel to
@@ -145,14 +141,18 @@ pub async fn list_for_exam_user(
145141 user: &UserId,
146142 seq: i64,
147143 ) -> Result<Vec<AnswerImage>, AppError> {
148- let mut result = db
149- .query("SELECT * FROM answer_image WHERE exam = $ex AND user = $usr AND seq = $seq")
150- .bind(("ex", exam.record()))
151- .bind(("usr", user.record()))
152- .bind(("seq", seq))
153- .await?
154- .check()?;
155- Ok(result.take::<Vec<AnswerImage>>(0)?)
144+ Ok(sqlx::query_as!(
145+ AnswerImage,
146+ r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
147+ app_user AS "user: UserId", seq, file,
148+ content_type AS "content_type: FileContentType", size
149+ FROM answer_image WHERE exam = $1 AND app_user = $2 AND seq = $3"#,
150+ exam as &ExamId,
151+ user as &UserId,
152+ seq,
153+ )
154+ .fetch_all(db)
155+ .await?)
156156 }
157157
158158 /// The distinct sittings (`seq`, ascending) this student has any answer
@@ -162,18 +162,15 @@ pub async fn list_seqs_for_user(
162162 exam: &ExamId,
163163 user: &UserId,
164164 ) -> Result<Vec<i64>, AppError> {
165- let mut result = db
166- .query(
167- "SELECT VALUE seq FROM answer_image \
168- WHERE exam = $ex AND user = $usr ORDER BY seq",
169- )
170- .bind(("ex", exam.record()))
171- .bind(("usr", user.record()))
172- .await?
173- .check()?;
174- let mut seqs = result.take::<Vec<i64>>(0)?;
175- seqs.dedup();
176- Ok(seqs)
165+ let rows = sqlx::query!(
166+ r#"SELECT DISTINCT seq FROM answer_image
167+ WHERE exam = $1 AND app_user = $2 ORDER BY seq ASC"#,
168+ exam as &ExamId,
169+ user as &UserId,
170+ )
171+ .fetch_all(db)
172+ .await?;
173+ Ok(rows.into_iter().map(|row| row.seq).collect())
177174 }
178175
179176 /// The blob names behind every answer drawing of every exam of `course` β€”
@@ -182,36 +179,49 @@ pub async fn file_keys_for_course(
182179 db: &Database,
183180 course: &CourseId,
184181 ) -> Result<Vec<String>, AppError> {
185- let mut result = db
186- .query(
187- "SELECT VALUE file FROM answer_image \
188- WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)",
189- )
190- .bind(("course", course.record()))
191- .await?
192- .check()?;
193- Ok(result.take::<Vec<String>>(0)?)
182+ let rows = sqlx::query!(
183+ r#"SELECT ai.file FROM answer_image ai
184+ JOIN exam e ON e.id = ai.exam WHERE e.course = $1"#,
185+ course as &CourseId,
186+ )
187+ .fetch_all(db)
188+ .await?;
189+ Ok(rows.into_iter().map(|row| row.file).collect())
194190 }
195191
196192 pub async fn delete(db: &Database, image: AnswerImage) -> Result<AnswerImage, AppError> {
197- let deleted: Option<AnswerImage> = db.delete(image.id.record()).await?;
193+ let deleted = sqlx::query_as!(
194+ AnswerImage,
195+ r#"DELETE FROM answer_image WHERE question = $1 AND app_user = $2 AND seq = $3
196+ RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId",
197+ app_user AS "user: UserId", seq, file,
198+ content_type AS "content_type: FileContentType", size"#,
199+ image.question as &ExamQuestionId,
200+ image.user as &UserId,
201+ image.seq,
202+ )
203+ .fetch_optional(db)
204+ .await?;
198205 deleted.ok_or(AppError::NotFound)
199206 }
200207
201208 /// Drop one student's answer drawings across an exam β€” a retake starts from
202-/// a blank sheet. Rows only; the caller GCs the blobs. The retake path itself
203-/// wipes rows inside `ExamAttempt::wipe_and_create`'s transaction; this is
204-/// the standalone mirror of [`crate::db::exam_answer::delete_for_exam_user`].
209+/// a blank sheet. Rows only; the caller GCs the blobs. The retake path
210+/// itself wipes nothing: a retake's rows live at their own `seq`, and this
211+/// is the standalone mirror of
212+/// [`crate::db::exam_answer::delete_for_exam_user`].
205213 pub async fn delete_for_exam_user(
206214 db: &Database,
207215 exam: &ExamId,
208216 user: &UserId,
209217 ) -> Result<(), AppError> {
210- db.query("DELETE answer_image WHERE exam = $ex AND user = $usr")
211- .bind(("ex", exam.record()))
212- .bind(("usr", user.record()))
213- .await?
214- .check()?;
218+ sqlx::query!(
219+ r#"DELETE FROM answer_image WHERE exam = $1 AND app_user = $2"#,
220+ exam as &ExamId,
221+ user as &UserId,
222+ )
223+ .execute(db)
224+ .await?;
215225 Ok(())
216226 }
217227
src/db/exam.rsmodified+380 -182
@@ -1,18 +1,14 @@
1-//! The `exam` table: row reads and listings, the count-and-create that pins
2-//! the exam to a live course row, the compare-and-set every PATCH writes
3-//! through, and the cascading delete. The PATCH re-derive and the delete's
4-//! blob-key collection live in [`crate::service::exam`].
1+//! The `exam` table: row reads and listings, the gated create that refuses a
2+//! course that is gone, the compare-and-set every PATCH writes through, and
3+//! the cascading delete. The PATCH re-derive lives in [`crate::service::exam`].
54
6-use surrealdb::types::{RecordId, SurrealValue};
7-
8-use crate::constant::ENROLLMENT_COUNT_FIELD;
9-use crate::database::{Database, transaction_with_retry};
10-use crate::db::cap;
5+use crate::database::{Database, foreign_key_violation, tx_with_retry};
116 use crate::domain::course::CourseId;
127 use crate::domain::exam::{
138 Exam, ExamAttemptLimit, ExamDescription, ExamId, ExamKind, ExamSchedule, ExamTitle,
149 redraft_error,
1510 };
11+use crate::domain::timestamp::Timestamp;
1612 use crate::domain::user::UserId;
1713 use crate::error::AppError;
1814
@@ -33,58 +29,104 @@ pub async fn create(
3329 allow_review: bool,
3430 draft: bool,
3531 ) -> Result<Exam, AppError> {
36- let exam = Exam {
37- id: ExamId::generate(),
38- creator: creator.clone(),
39- course: course.clone(),
32+ // A missing parent is refused by the real foreign keys: a course or a
33+ // creator that is gone is `SQLSTATE 23503`, and this call site's
34+ // parent-gone answer is the same `NotFound` the old existence-proof
35+ // touch (`cap::touch_and_create`, deleted) answered with. The bump that
36+ // touch made and unmade is gone with it β€” an exam was never counted
37+ // anywhere.
38+ let created = sqlx::query_as!(
39+ Exam,
40+ r#"INSERT INTO exam (id, creator, course, title, description, kind, mode,
41+ starts_at, ends_at, duration_ms, max_attempts,
42+ allow_rejoin, allow_review, draft)
43+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
44+ RETURNING id AS "id: ExamId", creator AS "creator: UserId",
45+ course AS "course: CourseId", title AS "title: ExamTitle",
46+ description AS "description: ExamDescription",
47+ kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>",
48+ starts_at AS "starts_at: Option<Timestamp>",
49+ ends_at AS "ends_at: Option<Timestamp>",
50+ duration_ms AS "duration_ms: Option<ExamDuration>",
51+ max_attempts AS "max_attempts: ExamAttemptLimit",
52+ allow_rejoin, allow_review, draft"#,
53+ ExamId::generate(),
54+ creator as &UserId,
55+ course as &CourseId,
4056 title,
4157 description,
4258 kind,
43- mode: schedule.mode,
44- starts_at: schedule.starts_at,
45- ends_at: schedule.ends_at,
46- duration_ms: schedule.duration_ms,
59+ schedule.mode,
60+ schedule.starts_at,
61+ schedule.ends_at,
62+ schedule.duration_ms,
4763 max_attempts,
4864 allow_rejoin,
4965 allow_review,
5066 draft,
51- result_count: None,
52- };
53- // The course row is *written* (bumped and put back), not read: a plain
54- // read does not survive `Course::delete`'s window, and an exam that
55- // outlives its course is unreachable for good β€” every route to one goes
56- // through `course_of`, which answers a 500 no delete can clear, while
57- // `GET /exams` still lists it. See [`cap::touch_and_create`].
58- cap::touch_and_create(
59- &course.record(),
60- ENROLLMENT_COUNT_FIELD,
61- &exam.id.record(),
62- &exam,
63- db,
6467 )
65- .await?
66- .ok_or(AppError::NotFound)
68+ .fetch_one(db)
69+ .await;
70+ match created {
71+ Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound),
72+ Err(err) => Err(err.into()),
73+ Ok(exam) => Ok(exam),
74+ }
6775 }
6876
6977 pub async fn read(db: &Database, id: &ExamId) -> Result<Option<Exam>, AppError> {
70- Ok(db.select(id.record()).await?)
78+ Ok(sqlx::query_as!(
79+ Exam,
80+ r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId",
81+ title AS "title: ExamTitle", description AS "description: ExamDescription",
82+ kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>",
83+ starts_at AS "starts_at: Option<Timestamp>",
84+ ends_at AS "ends_at: Option<Timestamp>",
85+ duration_ms AS "duration_ms: Option<ExamDuration>",
86+ max_attempts AS "max_attempts: ExamAttemptLimit",
87+ allow_rejoin, allow_review, draft
88+ FROM exam WHERE id = $1"#,
89+ id as &ExamId,
90+ )
91+ .fetch_optional(db)
92+ .await?)
7193 }
7294
95+/// The exams, newest first β€” `ORDER BY id` on a UUIDv7 column is creation
96+/// order, the sort the old record ids gave for free.
7397 pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> {
74- let mut result = db
75- .query("SELECT * FROM exam ORDER BY id DESC")
76- .await?
77- .check()?;
78- Ok(result.take::<Vec<Exam>>(0)?)
98+ Ok(sqlx::query_as!(
99+ Exam,
100+ r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId",
101+ title AS "title: ExamTitle", description AS "description: ExamDescription",
102+ kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>",
103+ starts_at AS "starts_at: Option<Timestamp>",
104+ ends_at AS "ends_at: Option<Timestamp>",
105+ duration_ms AS "duration_ms: Option<ExamDuration>",
106+ max_attempts AS "max_attempts: ExamAttemptLimit",
107+ allow_rejoin, allow_review, draft
108+ FROM exam ORDER BY id DESC"#,
109+ )
110+ .fetch_all(db)
111+ .await?)
79112 }
80113
81114 pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Exam>, AppError> {
82- let mut result = db
83- .query("SELECT * FROM exam WHERE course = $course ORDER BY id DESC")
84- .bind(("course", course.record()))
85- .await?
86- .check()?;
87- Ok(result.take::<Vec<Exam>>(0)?)
115+ Ok(sqlx::query_as!(
116+ Exam,
117+ r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId",
118+ title AS "title: ExamTitle", description AS "description: ExamDescription",
119+ kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>",
120+ starts_at AS "starts_at: Option<Timestamp>",
121+ ends_at AS "ends_at: Option<Timestamp>",
122+ duration_ms AS "duration_ms: Option<ExamDuration>",
123+ max_attempts AS "max_attempts: ExamAttemptLimit",
124+ allow_rejoin, allow_review, draft
125+ FROM exam WHERE course = $1 ORDER BY id DESC"#,
126+ course as &CourseId,
127+ )
128+ .fetch_all(db)
129+ .await?)
88130 }
89131
90132 /// Every exam of every course in `courses` (one query) β€” the catalog as one
@@ -93,13 +135,36 @@ pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec
93135 if courses.is_empty() {
94136 return Ok(Vec::new());
95137 }
96- let records: Vec<RecordId> = courses.iter().map(CourseId::record).collect();
97- let mut result = db
98- .query("SELECT * FROM exam WHERE course IN $courses ORDER BY id DESC")
99- .bind(("courses", records))
100- .await?
101- .check()?;
102- Ok(result.take::<Vec<Exam>>(0)?)
138+ let courses = courses.iter().map(CourseId::uuid).collect::<Vec<_>>();
139+ Ok(sqlx::query_as!(
140+ Exam,
141+ r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId",
142+ title AS "title: ExamTitle", description AS "description: ExamDescription",
143+ kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>",
144+ starts_at AS "starts_at: Option<Timestamp>",
145+ ends_at AS "ends_at: Option<Timestamp>",
146+ duration_ms AS "duration_ms: Option<ExamDuration>",
147+ max_attempts AS "max_attempts: ExamAttemptLimit",
148+ allow_rejoin, allow_review, draft
149+ FROM exam WHERE course = ANY($1) ORDER BY id DESC"#,
150+ courses,
151+ )
152+ .fetch_all(db)
153+ .await?)
154+}
155+
156+/// The exam's mark counter, read on its own β€” the one column no struct
157+/// carries and no whole-row rewrite touches. The kind-change gate reads it
158+/// here (pre-flight) and `update_if_unchanged` pins it inside its own
159+/// transaction (write time).
160+pub async fn result_count(db: &Database, id: &ExamId) -> Result<i64, AppError> {
161+ let row = sqlx::query!(
162+ r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#,
163+ id as &ExamId,
164+ )
165+ .fetch_one(db)
166+ .await?;
167+ Ok(row.result_count)
103168 }
104169
105170 // `course` is deliberately not updatable β€” moving an exam between courses
@@ -113,11 +178,23 @@ pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec
113178 /// landed in between and nothing was written: re-read, re-merge, retry.
114179 ///
115180 /// Every column this write replaces is in the guard, which is what makes
116-/// the whole-row `CONTENT` save safe without a lock held across the
117-/// handler's read: the compare-and-set refuses precisely when that save
118-/// would have reverted somebody. `course`/`creator` are not editable and
119-/// ride along unchanged. Same shape as
120-/// [`crate::db::settings::save_if_unchanged`].
181+/// the whole-row save safe without a lock held across the handler's read:
182+/// the compare-and-set refuses precisely when that save would have
183+/// reverted somebody. `course`/`creator` are not editable and ride along
184+/// unchanged. Same shape as [`crate::db::settings::save_if_unchanged`].
185+///
186+/// The mark counter is pinned too, read *inside* this transaction rather
187+/// than carried on the snapshot: a grade increments it, so pinning it is
188+/// what makes "this exam had no marks" β€” the gate the handler refuses a
189+/// kind change on β€” true at *write* time and not merely at read time. A
190+/// mark landing between the read and the guarded write makes the UPDATE
191+/// re-check its `WHERE` against the new row version, find the counter
192+/// moved, and refuse the save β€” the same answer the old pinned snapshot
193+/// gave, without a stale snapshot able to pin a counter it cannot see.
194+///
195+/// The re-draft gate rides in the same transaction, as before: re-drafting
196+/// hides an exam, so it must be refused while any sitting or mark exists,
197+/// and the check has to see the write's own moment, not the handler's.
121198 pub async fn update_if_unchanged(
122199 db: &Database,
123200 mut expected: Exam,
@@ -130,11 +207,6 @@ pub async fn update_if_unchanged(
130207 allow_review: bool,
131208 draft: bool,
132209 ) -> Result<Option<Exam>, AppError> {
133- // Re-drafting hides an exam: it must be refused while any sitting or
134- // mark exists, and that check has to be *in this transaction*. Holding
135- // it under a lock outside would only order the two writers inside one
136- // process β€” and it did not even do that, since grading takes the reader
137- // lease this write does.
138210 let redraft = draft && !expected.draft;
139211 let was = (
140212 expected.title.clone(),
@@ -160,92 +232,114 @@ pub async fn update_if_unchanged(
160232 expected.allow_rejoin = allow_rejoin;
161233 expected.allow_review = allow_review;
162234 expected.draft = draft;
163- // whole-row-save-ok: the WHERE below pins every column this replaces to
164- // the caller's snapshot, so no concurrent write can be reverted
165- //
166- // Sent through the retry loop, not a bare `query`: this row now has a
167- // hot writer. Every answer save touches it to tie itself to the exam
168- // ([`crate::db::exam_answer::save`]), so a teacher
169- // flipping `allow_rejoin` mid-exam can lose a round to a student
170- // typing β€” and a lost round is a re-send, never the 500 a bare `?` on
171- // the conflict would have answered. Re-sending is sound because the
172- // statement is a compare-and-set: the second pass carries the same
173- // pinned snapshot, so it lands only if the row is still what the caller
174- // read, and a rival that really moved it is refused as it was before.
175- // Admissible for the loop β€” an `UPDATE`, an `IF`/`THROW` and a `SELECT`
176- // can never answer "already exists".
177- let (mut result, mut errors) = transaction_with_retry(
178- db,
179- "BEGIN TRANSACTION;
180- IF $redraft AND (
181- array::len((SELECT VALUE id FROM exam_attempt WHERE exam = $id LIMIT 1)) > 0
182- OR array::len((SELECT VALUE id FROM exam_result WHERE exam = $id LIMIT 1)) > 0
183- ) { THROW 'exam_redraft' };
184- UPDATE $id CONTENT $new
185- WHERE title = $was_title AND description = $was_description
186- AND kind = $was_kind AND mode = $was_mode
187- AND starts_at = $was_starts AND ends_at = $was_ends
188- AND duration_ms = $was_duration
189- AND max_attempts = $was_max_attempts
190- AND allow_rejoin = $was_allow_rejoin
191- AND allow_review = $was_allow_review
192- AND draft = $was_draft
193- AND (result_count ?? 0) = $was_results
194- RETURN AFTER;
195- COMMIT TRANSACTION;",
196- &[
197- ("redraft".into(), redraft.into_value()),
198- ("id".into(), expected.id.record().into_value()),
199- ("was_title".into(), was.0.into_value()),
200- ("was_description".into(), was.1.into_value()),
201- ("was_kind".into(), was.2.into_value()),
202- ("was_mode".into(), was.3.into_value()),
203- ("was_starts".into(), was.4.into_value()),
204- ("was_ends".into(), was.5.into_value()),
205- ("was_duration".into(), was.6.into_value()),
206- ("was_max_attempts".into(), was.7.into_value()),
207- ("was_allow_rejoin".into(), was.8.into_value()),
208- ("was_allow_review".into(), was.9.into_value()),
209- ("was_draft".into(), was.10.into_value()),
210- // The mark counter is pinned like every other column this write
211- // replaces, and for a sharper reason: a grade increments it, so
212- // pinning it is what makes "this exam had no marks" β€” the gate
213- // the handler refuses a kind change on β€” true at *write* time
214- // and not merely at read time. A mark landing in between
215- // refuses the save.
216- (
217- "was_results".into(),
218- expected.result_count.unwrap_or(0).into_value(),
219- ),
220- ("new".into(), expected.into_value()),
221- ],
222- &["exam_redraft"],
223- )
235+ let saved = tx_with_retry(db, false, async |conn| {
236+ if redraft {
237+ // `exam_redraft`: the same refusal the handler's pre-flight
238+ // answers, re-made at write time. A sitting or a mark existing
239+ // hides nothing.
240+ let gates = sqlx::query!(
241+ r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat,
242+ EXISTS(SELECT 1 FROM exam_result WHERE exam = $1) AS graded"#,
243+ expected.id as &ExamId,
244+ )
245+ .fetch_one(&mut *conn)
246+ .await?;
247+ if gates.sat || gates.graded {
248+ return Err(redraft_error());
249+ }
250+ }
251+ let was_results = sqlx::query!(
252+ r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#,
253+ expected.id as &ExamId,
254+ )
255+ .fetch_optional(&mut *conn)
256+ .await?
257+ .map(|row| row.result_count)
258+ .unwrap_or(0);
259+ let written = sqlx::query_as!(
260+ Exam,
261+ r#"UPDATE exam SET title = $2, description = $3, kind = $4, mode = $5,
262+ starts_at = $6, ends_at = $7, duration_ms = $8,
263+ max_attempts = $9, allow_rejoin = $10, allow_review = $11,
264+ draft = $12
265+ WHERE id = $1
266+ AND title = $13 AND description = $14 AND kind = $15
267+ AND mode IS NOT DISTINCT FROM $16
268+ AND starts_at IS NOT DISTINCT FROM $17
269+ AND ends_at IS NOT DISTINCT FROM $18
270+ AND duration_ms IS NOT DISTINCT FROM $19
271+ AND max_attempts = $20 AND allow_rejoin = $21 AND allow_review = $22
272+ AND draft = $23
273+ AND result_count = $24
274+ RETURNING id AS "id: ExamId", creator AS "creator: UserId",
275+ course AS "course: CourseId", title AS "title: ExamTitle",
276+ description AS "description: ExamDescription",
277+ kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>",
278+ starts_at AS "starts_at: Option<Timestamp>",
279+ ends_at AS "ends_at: Option<Timestamp>",
280+ duration_ms AS "duration_ms: Option<ExamDuration>",
281+ max_attempts AS "max_attempts: ExamAttemptLimit",
282+ allow_rejoin, allow_review, draft"#,
283+ expected.id as &ExamId,
284+ expected.title,
285+ expected.description,
286+ expected.kind,
287+ expected.mode,
288+ expected.starts_at,
289+ expected.ends_at,
290+ expected.duration_ms,
291+ expected.max_attempts,
292+ expected.allow_rejoin,
293+ expected.allow_review,
294+ expected.draft,
295+ was.0,
296+ was.1,
297+ was.2,
298+ was.3,
299+ was.4,
300+ was.5,
301+ was.6,
302+ was.7,
303+ was.8,
304+ was.9,
305+ was.10,
306+ was_results,
307+ )
308+ .fetch_optional(&mut *conn)
309+ .await?;
310+ Ok(written)
311+ })
224312 .await?;
225- // An aborted transaction errors every slot; only the THROW's names the
226- // marker (the [`crate::db::exam_attempt::write_unfrozen`] treatment).
227- if errors
228- .values()
229- .any(|error| error.to_string().contains("exam_redraft"))
230- {
231- return Err(redraft_error());
232- }
233- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
234- return Err(error.into());
235- }
236- // BEGIN and the IF take a slot each.
237- Ok(result.take::<Vec<Exam>>(2)?.into_iter().next())
313+ Ok(saved)
314+}
315+
316+/// What [`delete`] collects on its way through: the deleted row plus the
317+/// blob keys of the image rows its cascade removed β€” exactly whose files
318+/// the web layer may unlink.
319+pub struct Deleted {
320+ pub exam: Exam,
321+ pub question_image_files: Vec<String>,
322+ pub answer_image_files: Vec<String>,
238323 }
239324
240325 /// Delete the exam and cascade-remove its result, attempt, question,
241326 /// answer, question-image, and answer-image rows β€” all in one transaction,
242327 /// so a failure can't leave an emptied-out exam shell behind. The image
243-/// *blobs* (question and answer) are the web layer's to remove β€” it collects
244-/// their names before calling this.
328+/// *blobs* are the caller's to remove β€” this returns the names, collected
329+/// inside the same transaction that removes the rows.
330+///
331+/// The transaction opens by taking the exam row `FOR UPDATE` β€” the store
332+/// replacement of the writer lease the delete used to hold. Every child
333+/// writer that matters locks the same row first (a sitting create's guard,
334+/// the freeze gate, an answer save ahead of its upsert), so a start or a
335+/// save either finished before the sweep (which then takes its row) or
336+/// finds no exam and is a `404`. Left orphaned, an attempt kept a sitting
337+/// on the student's lifetime counter and could mint a badge β€” awards are
338+/// add-only and never revoked β€” for an exam that never existed.
245339 ///
246340 /// Bank templates saved out of this exam survive it β€” they are a separate,
247-/// reusable library β€” so only their `source_exam` provenance link is cleared,
248-/// in the same transaction, never left pointing at a dead exam.
341+/// reusable library β€” so only their `source_exam` provenance link is
342+/// cleared, in the same transaction, never left pointing at a dead exam.
249343 ///
250344 /// The questions about to be cascaded each hold a reference on their
251345 /// subject, which is what keeps that subject from being deleted under them.
@@ -256,52 +350,156 @@ pub async fn update_if_unchanged(
256350 /// concurrent `remove_result` in the gap would be released twice β€” once by
257351 /// each β€” which on a kind another exam still uses reads as one mark too
258352 /// few, and that is a kind wrongly free to leave the settings.
259-pub async fn delete(db: &Database, target: Exam) -> Result<Exam, AppError> {
260- let (mut result, mut errors) = transaction_with_retry(
353+pub async fn delete(db: &Database, target: Exam) -> Result<Deleted, AppError> {
354+ tx_with_retry(
355+ db,
356+ true,
357+ async |conn| {
358+ // The row lock every other exam-child writer contends on.
359+ let locked = sqlx::query!(
360+ r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#,
361+ target.id as &ExamId,
362+ )
363+ .fetch_optional(&mut *conn)
364+ .await?;
365+ if locked.is_none() {
366+ return Err(AppError::NotFound);
367+ }
368+ // The blob names, collected *before* the rows go β€” inside the
369+ // lock, so an image row written after this snapshot cannot
370+ // strand its bytes on disk even though the row itself would be
371+ // refused.
372+ let image_files = sqlx::query!(
373+ r#"SELECT file FROM question_image WHERE exam = $1"#,
374+ target.id as &ExamId,
375+ )
376+ .fetch_all(&mut *conn)
377+ .await?
378+ .into_iter()
379+ .map(|row| row.file)
380+ .collect();
381+ let answer_image_files = sqlx::query!(
382+ r#"SELECT file FROM answer_image WHERE exam = $1"#,
383+ target.id as &ExamId,
384+ )
385+ .fetch_all(&mut *conn)
386+ .await?
387+ .into_iter()
388+ .map(|row| row.file)
389+ .collect();
390+ // The marks give their kind references back, counted per kind
391+ // off the results this exam still has. The ref row always
392+ // exists here: a mark's own claim creates it before any result
393+ // can land.
394+ sqlx::query!(
395+ r#"WITH kinds AS (
396+ SELECT e.kind AS kind, count(*) AS n
397+ FROM exam_result r JOIN exam e ON e.id = r.exam
398+ WHERE r.exam = $1
399+ GROUP BY e.kind)
400+ UPDATE kind_ref k SET count = GREATEST(k.count - c.n, 0)
401+ FROM kinds c WHERE k.name = c.kind"#,
402+ target.id as &ExamId,
403+ )
404+ .execute(&mut *conn)
405+ .await?;
406+ sqlx::query!(r#"DELETE FROM exam_result WHERE exam = $1"#, target.id as &ExamId)
407+ .execute(&mut *conn)
408+ .await?;
409+ sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = $1"#, target.id as &ExamId)
410+ .execute(&mut *conn)
411+ .await?;
412+ sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = $1"#, target.id as &ExamId)
413+ .execute(&mut *conn)
414+ .await?;
415+ sqlx::query!(r#"DELETE FROM answer_image WHERE exam = $1"#, target.id as &ExamId)
416+ .execute(&mut *conn)
417+ .await?;
418+ sqlx::query!(r#"DELETE FROM question_image WHERE exam = $1"#, target.id as &ExamId)
419+ .execute(&mut *conn)
420+ .await?;
421+ // The cascaded questions give their subject references back,
422+ // counted per subject off the rows still present β€” before the
423+ // questions themselves go.
424+ sqlx::query!(
425+ r#"WITH subs AS (
426+ SELECT subject, count(*) AS n
427+ FROM exam_question WHERE exam = $1
428+ GROUP BY subject)
429+ UPDATE subject s SET exam_question_count = GREATEST(s.exam_question_count - c.n, 0)
430+ FROM subs c WHERE s.id = c.subject"#,
431+ target.id as &ExamId,
432+ )
433+ .execute(&mut *conn)
434+ .await?;
435+ sqlx::query!(r#"DELETE FROM exam_question WHERE exam = $1"#, target.id as &ExamId)
436+ .execute(&mut *conn)
437+ .await?;
438+ sqlx::query!(
439+ r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = $1"#,
440+ target.id as &ExamId,
441+ )
442+ .execute(&mut *conn)
443+ .await?;
444+ let deleted = sqlx::query_as!(
445+ Exam,
446+ r#"DELETE FROM exam WHERE id = $1
447+ RETURNING id AS "id: ExamId", creator AS "creator: UserId",
448+ course AS "course: CourseId", title AS "title: ExamTitle",
449+ description AS "description: ExamDescription",
450+ kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>",
451+ starts_at AS "starts_at: Option<Timestamp>",
452+ ends_at AS "ends_at: Option<Timestamp>",
453+ duration_ms AS "duration_ms: Option<ExamDuration>",
454+ max_attempts AS "max_attempts: ExamAttemptLimit",
455+ allow_rejoin, allow_review, draft"#,
456+ target.id as &ExamId,
457+ )
458+ .fetch_optional(&mut *conn)
459+ .await?;
460+ let Some(exam) = deleted else {
461+ return Err(AppError::NotFound);
462+ };
463+ Ok(Deleted {
464+ exam,
465+ question_image_files: image_files,
466+ answer_image_files,
467+ })
468+ },
469+ )
470+ .await
471+}
472+
473+#[cfg(test)]
474+use crate::domain::settings::ExamKindDef;
475+
476+/// An unscheduled published exam β€” the minimum any test that writes a *child*
477+/// of an exam needs, in any module: every such write moves the exam row (see
478+/// [`crate::db::exam_attempt::write_unfrozen_with`]
479+/// and [`crate::db::exam_answer::save`]), so a minted id whose
480+/// row was never created is a 404 rather than a silent orphan.
481+#[cfg(test)]
482+pub(crate) async fn published_exam(db: &Database) -> Exam {
483+ let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
484+ .get_exam_kinds()
485+ .to_vec();
486+ create(
261487 db,
262- "BEGIN TRANSACTION;
263- FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result
264- WHERE exam = $ex GROUP BY kind) ?? []) {
265- UPDATE type::record('kind_ref', $row.kind) SET count =
266- math::max([(count ?? 0) - $row.n, 0])
267- };
268- DELETE exam_result WHERE exam = $ex;
269- DELETE exam_attempt WHERE exam = $ex;
270- DELETE exam_answer WHERE exam = $ex;
271- DELETE answer_image WHERE exam = $ex;
272- DELETE question_image WHERE exam = $ex;
273- FOR $row IN ((SELECT subject, count() AS n FROM exam_question
274- WHERE exam = $ex GROUP BY subject) ?? []) {
275- UPDATE $row.subject SET exam_question_count =
276- math::max([(exam_question_count ?? 0) - $row.n, 0])
277- };
278- DELETE exam_question WHERE exam = $ex;
279- UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex;
280- LET $before = (DELETE $ex RETURN BEFORE);
281- RETURN $before;
282- COMMIT TRANSACTION;",
283- &[("ex".into(), target.id.record().into_value())],
284- // No THROW of its own: an unconditional cascade, so the only error
285- // worth telling apart is a lost round, and `check()` β€” which took
286- // the *first* error in the batch β€” could not. It reported a
287- // sibling's "not executed" and made a retryable round a 500.
288- &[],
488+ &UserId::generate(),
489+ &crate::db::course::a_test_course(db).await,
490+ ExamTitle::try_new("midterm").unwrap(),
491+ ExamDescription::try_new("").unwrap(),
492+ ExamKind::try_new("midterm", &allowed).unwrap(),
493+ ExamSchedule::try_new(None, None, None, None).unwrap(),
494+ ExamAttemptLimit::try_new(1).unwrap(),
495+ true,
496+ false,
497+ false,
289498 )
290- .await?;
291- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
292- return Err(error.into());
293- }
294- // The deleted row comes back through the transaction's trailing
295- // `RETURN`, never a hand-counted slot: the old `take(8)` turned a
296- // successful delete into a 404 the moment a cascade statement was
297- // inserted above it (it already had to be bumped once). `RETURN` is
298- // always the last statement before `COMMIT`, so its slot is derived
299- // from the statement count and every insertion above it shifts it
300- // along. `num_statements` counts BEGIN and COMMIT too, hence -2.
301- let slot = result.num_statements().saturating_sub(2);
302- let deleted: Option<Exam> = result.take::<Vec<Exam>>(slot)?.into_iter().next();
303- deleted.ok_or(AppError::NotFound)
499+ .await
500+ .unwrap()
304501 }
502+
305503 #[cfg(test)]
306504 use crate::domain::settings::ExamKindDef;
307505
src/db/exam_answer.rsmodified+127 -127
@@ -3,13 +3,12 @@
33 //! retake and the cascades use. The sitting key shape and the payload
44 //! validation's pure half live in [`crate::domain::exam_answer`].
55
6-use surrealdb::types::SurrealValue;
6+use sqlx::PgConnection;
77
8-use crate::constant::EXAM_RESULT_COUNT_FIELD;
9-use crate::database::{Database, transaction_with_retry};
8+use crate::database::{Database, tx_with_retry};
109 use crate::domain::exam::ExamId;
11-use crate::domain::exam_answer::{AnswerText, ExamAnswer, ExamAnswerId};
12-use crate::domain::exam_question::{ExamQuestion, ExamQuestionId};
10+use crate::domain::exam_answer::{AnswerText, ExamAnswer};
11+use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId};
1312 use crate::domain::timestamp::Timestamp;
1413 use crate::domain::user::UserId;
1514 use crate::error::{AppError, ValidationError};
@@ -64,92 +63,66 @@ pub async fn save(
6463 (None, Some(AnswerText::try_new(&text)?))
6564 }
6665 };
67- let answer = ExamAnswer {
68- id: ExamAnswerId::composite(question.get_id(), user, seq),
69- exam: question.get_exam().clone(),
70- question: question.get_id().clone(),
71- user: user.clone(),
72- seq,
73- selected,
74- text,
75- updated_at: Timestamp::now(),
76- };
77- // The save writes the *exam row* as well as the answer, in one
66+ // The save locks the *exam row* before upserting the answer, in one
7867 // transaction, and that is what ties the answer's fate to its exam:
79- // reading the exam does not survive [`crate::db::exam::delete`]'s
80- // window β€” a save landing after its `DELETE exam_answer WHERE exam = $ex`
81- // but before the commit reads an exam that is still there (uncommitted)
82- // while the sweep ran on a snapshot predating this row, so both commit
83- // and the answer outlives the exam (measured 4 of 4 raced rounds).
84- // Writing the key the delete removes makes the two collide, and the
85- // store refuses one of them. It is the shape
86- // [`crate::domain::menu::bump_menu_and_write`] uses, and the one a mark
87- // already uses on this very row
88- // ([`crate::db::exam_result::grade`]).
89- //
90- // The bump-and-restore is not a flourish, it is the whole instrument.
91- // The exam carries no revision to bump and must not grow one β€” its save
92- // is a whole-row `CONTENT` write, so a column this struct did not know
93- // about would be wiped by the next PATCH β€” so this touches the one
94- // counter it already has and puts it back. Writing the *same* value is
95- // not enough: an `UPDATE` that leaves the document unchanged is elided
96- // and never reaches the store's write set, which the race test proved
97- // (green on the raced delete, red the moment the value moves for real).
98- // The restore is by captured value, `NONE` included, so the row is
99- // byte-identical afterwards: the boot backfill still finds the rows it
100- // keys on (`WHERE result_count = NONE`), the PATCH's
101- // `(result_count ?? 0) = $was_results` still passes, and no teacher's
102- // edit is refused because a student typed. Both statements are inside
103- // the transaction, so a crash between them cannot leave the counter up.
104- // No `cap::counter_lock` either: no counter moves here, and the hottest
105- // write path in the app should not queue behind one.
106- //
107- // Admissible for `transaction_with_retry`: the `UPDATE`s, `SELECT`,
108- // `IF`/`THROW` and `RETURN` can never answer "already exists", and the
109- // `UPSERT`'s id is bijective with the (question, user, seq) triple
110- // `exam_answer` keys β€” a lost round wrote nothing, and re-sending
111- // resolves onto the same row rather than colliding with it.
112- let (mut result, mut errors) = transaction_with_retry(
113- db,
114- &format!(
115- "BEGIN TRANSACTION;
116- LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex);
117- LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \
118- ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);
119- IF array::len($touched) = 0 {{ THROW 'no_exam' }};
120- UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was;
121- LET $row = (UPSERT $id CONTENT $answer RETURN AFTER);
122- RETURN $row[0];
123- COMMIT TRANSACTION;"
124- ),
125- &[
126- ("ex".into(), answer.exam.record().into_value()),
127- ("id".into(), answer.id.record().into_value()),
128- ("answer".into(), answer.into_value()),
129- ],
130- &["no_exam"],
68+ // reading the exam does not survive
69+ // [`crate::db::exam::delete`]'s window β€” a save landing after its
70+ // cascade swept the answers but before it committed would have read an
71+ // exam that was still there and written an orphan no sweep would ever
72+ // visit. Locking the key the delete removes first makes the two
73+ // serialize: the save either lands before the sweep (which then takes
74+ // the row too) or finds no exam and answers the same `404` the old
75+ // `no_exam` THROW did. Real foreign keys stand behind the lock β€” a
76+ // child insert whose parent is gone refuses itself β€” which is what
77+ // retired the bump-and-restore this used to ride on.
78+ tx_with_retry(db, false, async |conn| {
79+ save_in(conn, question, user, seq, selected, text).await
80+ })
81+ .await
82+}
83+
84+/// The locked exam-row probe plus the upsert, on one connection β€” split out
85+/// so the exam room's room-bound save shares the exact statements.
86+pub(crate) async fn save_in(
87+ conn: &mut PgConnection,
88+ question: &ExamQuestion,
89+ user: &UserId,
90+ seq: i64,
91+ selected: Option<ChoiceId>,
92+ text: Option<AnswerText>,
93+) -> Result<ExamAnswer, AppError> {
94+ let touched = sqlx::query!(
95+ r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#,
96+ question.get_exam() as &ExamId,
13197 )
98+ .fetch_optional(&mut *conn)
13299 .await?;
133- // An aborted transaction errors *every* slot, most with a generic "not
134- // executed" β€” only the THROW's own slot names the reason.
135- if errors
136- .values()
137- .any(|error| error.to_string().contains("no_exam"))
138- {
100+ if touched.is_none() {
139101 return Err(AppError::NotFound);
140102 }
141- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
142- return Err(error.into());
143- }
144- // The trailing `RETURN` is the last statement before `COMMIT`, so its
145- // slot follows the statement count rather than a hand-kept number (the
146- // `db::exam::delete` treatment); `num_statements` counts BEGIN and COMMIT.
147- let slot = result.num_statements().saturating_sub(2);
148- result
149- .take::<Vec<ExamAnswer>>(slot)?
150- .into_iter()
151- .next()
152- .ok_or_else(|| AppError::Internal("failed to save exam answer".into()))
103+ let now = Timestamp::now();
104+ sqlx::query_as!(
105+ ExamAnswer,
106+ r#"INSERT INTO exam_answer (exam, question, app_user, selected, text, updated_at, seq)
107+ VALUES ($1, $2, $3, $4, $5, $6, $7)
108+ ON CONFLICT (question, app_user, seq) DO UPDATE
109+ SET selected = EXCLUDED.selected, text = EXCLUDED.text,
110+ updated_at = EXCLUDED.updated_at
111+ RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId",
112+ app_user AS "user: UserId", seq,
113+ selected AS "selected: Option<ChoiceId>",
114+ text AS "text: Option<AnswerText>",
115+ updated_at AS "updated_at: Timestamp""#,
116+ question.get_exam() as &ExamId,
117+ question.get_id() as &ExamQuestionId,
118+ user as &UserId,
119+ seq,
120+ selected,
121+ text,
122+ now,
123+ )
124+ .fetch_one(&mut *conn)
125+ .await
153126 }
154127
155128 /// One student's stored answer for a question in sitting `seq`, if any.
@@ -159,9 +132,21 @@ pub async fn read(
159132 user: &UserId,
160133 seq: i64,
161134 ) -> Result<Option<ExamAnswer>, AppError> {
162- Ok(db
163- .select(ExamAnswerId::composite(question, user, seq).record())
164- .await?)
135+ Ok(sqlx::query_as!(
136+ ExamAnswer,
137+ r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
138+ app_user AS "user: UserId", seq,
139+ selected AS "selected: Option<ChoiceId>",
140+ text AS "text: Option<AnswerText>",
141+ updated_at AS "updated_at: Timestamp"
142+ FROM exam_answer
143+ WHERE question = $1 AND app_user = $2 AND seq = $3"#,
144+ question as &ExamQuestionId,
145+ user as &UserId,
146+ seq,
147+ )
148+ .fetch_optional(db)
149+ .await?)
165150 }
166151
167152 /// Drop one student's answer to a single question in sitting `seq`.
@@ -171,14 +156,19 @@ pub async fn delete(
171156 user: &UserId,
172157 seq: i64,
173158 ) -> Result<(), AppError> {
174- let _: Option<ExamAnswer> = db
175- .delete(ExamAnswerId::composite(question, user, seq).record())
176- .await?;
159+ sqlx::query!(
160+ r#"DELETE FROM exam_answer WHERE question = $1 AND app_user = $2 AND seq = $3"#,
161+ question as &ExamQuestionId,
162+ user as &UserId,
163+ seq,
164+ )
165+ .execute(db)
166+ .await?;
177167 Ok(())
178168 }
179169
180170 /// One student's answers for a single sitting (`seq`) across an exam, in
181-/// question (ULID) order β€” the live-sitting read-back and, for a past
171+/// question (id) order β€” the live-sitting read-back and, for a past
182172 /// `seq`, that attempt's answer sheet.
183173 pub async fn list_for_exam_user(
184174 db: &Database,
@@ -186,17 +176,22 @@ pub async fn list_for_exam_user(
186176 user: &UserId,
187177 seq: i64,
188178 ) -> Result<Vec<ExamAnswer>, AppError> {
189- let mut result = db
190- .query(
191- "SELECT * FROM exam_answer WHERE exam = $ex AND user = $usr AND seq = $seq
192- ORDER BY question ASC",
193- )
194- .bind(("ex", exam.record()))
195- .bind(("usr", user.record()))
196- .bind(("seq", seq))
197- .await?
198- .check()?;
199- Ok(result.take::<Vec<ExamAnswer>>(0)?)
179+ Ok(sqlx::query_as!(
180+ ExamAnswer,
181+ r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
182+ app_user AS "user: UserId", seq,
183+ selected AS "selected: Option<ChoiceId>",
184+ text AS "text: Option<AnswerText>",
185+ updated_at AS "updated_at: Timestamp"
186+ FROM exam_answer
187+ WHERE exam = $1 AND app_user = $2 AND seq = $3
188+ ORDER BY question ASC"#,
189+ exam as &ExamId,
190+ user as &UserId,
191+ seq,
192+ )
193+ .fetch_all(db)
194+ .await?)
200195 }
201196
202197 /// The distinct sittings a student has any answer for at `exam`, ascending
@@ -206,28 +201,31 @@ pub async fn list_seqs_for_user(
206201 exam: &ExamId,
207202 user: &UserId,
208203 ) -> Result<Vec<i64>, AppError> {
209- let mut result = db
210- .query(
211- "SELECT VALUE seq FROM exam_answer WHERE exam = $ex AND user = $usr
212- ORDER BY seq ASC",
213- )
214- .bind(("ex", exam.record()))
215- .bind(("usr", user.record()))
216- .await?
217- .check()?;
218- let mut seqs = result.take::<Vec<i64>>(0)?;
219- seqs.dedup();
220- Ok(seqs)
204+ let rows = sqlx::query!(
205+ r#"SELECT DISTINCT seq FROM exam_answer
206+ WHERE exam = $1 AND app_user = $2 ORDER BY seq ASC"#,
207+ exam as &ExamId,
208+ user as &UserId,
209+ )
210+ .fetch_all(db)
211+ .await?;
212+ Ok(rows.into_iter().map(|row| row.seq).collect())
221213 }
222214
223215 /// Every answer of an exam β€” the live monitor aggregates these per student.
224216 pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamAnswer>, AppError> {
225- let mut result = db
226- .query("SELECT * FROM exam_answer WHERE exam = $ex ORDER BY question ASC")
227- .bind(("ex", exam.record()))
228- .await?
229- .check()?;
230- Ok(result.take::<Vec<ExamAnswer>>(0)?)
217+ Ok(sqlx::query_as!(
218+ ExamAnswer,
219+ r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
220+ app_user AS "user: UserId", seq,
221+ selected AS "selected: Option<ChoiceId>",
222+ text AS "text: Option<AnswerText>",
223+ updated_at AS "updated_at: Timestamp"
224+ FROM exam_answer WHERE exam = $1 ORDER BY question ASC"#,
225+ exam as &ExamId,
226+ )
227+ .fetch_all(db)
228+ .await?)
231229 }
232230
233231 /// Drop one student's answers across an exam β€” a retake starts from a
@@ -237,11 +235,13 @@ pub async fn delete_for_exam_user(
237235 exam: &ExamId,
238236 user: &UserId,
239237 ) -> Result<(), AppError> {
240- db.query("DELETE exam_answer WHERE exam = $ex AND user = $usr")
241- .bind(("ex", exam.record()))
242- .bind(("usr", user.record()))
243- .await?
244- .check()?;
238+ sqlx::query!(
239+ r#"DELETE FROM exam_answer WHERE exam = $1 AND app_user = $2"#,
240+ exam as &ExamId,
241+ user as &UserId,
242+ )
243+ .execute(db)
244+ .await?;
245245 Ok(())
246246 }
247247
src/db/exam_attempt.rsmodified+286 -202
@@ -1,31 +1,61 @@
11 //! The `exam_attempt` table: sitting reads, the two field-scoped writes
2-//! (`finished_at`, `left_at`), and the `write_unfrozen` transaction gateway
3-//! that ties exam-child writes to their exam row.
2+//! (`finished_at`, `left_at`), the guarded sitting create, and the freeze
3+//! gate β€” the in-transaction check every exam-child write runs before it
4+//! touches anything.
45
5-use surrealdb::types::{RecordId, SurrealValue};
6+use sqlx::PgConnection;
67
7-use crate::constant::EXAM_RESULT_COUNT_FIELD;
8-use crate::database::{Database, transaction_with_retry};
8+use crate::database::{Database, tx_with_retry, unique_violation};
9+use crate::db::cap::{self, Claimed};
910 use crate::domain::exam::ExamId;
1011 use crate::domain::exam_attempt::{ExamAttempt, ExamAttemptId};
1112 use crate::domain::timestamp::Timestamp;
1213 use crate::domain::user::UserId;
1314 use crate::error::AppError;
1415
15-/// The `THROW` marker the freeze gate aborts with, and the one 409 both it and
16-/// the handler's pre-flight check answer with β€” a client cannot tell which of
17-/// the two refused.
18-const FROZEN_MARK: &str = "questions_frozen";
19-
20-/// The `THROW` marker the exam-existence touch aborts with β€” the exam row this
21-/// write hangs off is gone, so the write is a 404 and nothing lands.
22-const GONE_MARK: &str = "no_exam";
23-
24-/// The 409 the freeze gate's marker means.
16+/// The 409 the freeze gate answers β€” the same one the handlers' pre-flight
17+/// check ([`crate::service::exam_question::ensure_questions_editable`])
18+/// answers, so a client cannot tell which of the two refused.
2519 fn frozen_error() -> AppError {
2620 AppError::Conflict("cannot change questions after attempts have started")
2721 }
2822
23+/// The freeze gate, run inside a caller's transaction on that caller's own
24+/// connection: take the exam row `FOR UPDATE`, then refuse unless the exam
25+/// still exists and nobody has started an attempt.
26+///
27+/// This is the whole of the old `write_unfrozen` machinery β€” the
28+/// `questions_frozen` THROW and the bump-and-restore existence touch β€” with
29+/// Postgres doing the work the tricks stood in for. The row lock makes the
30+/// check-and-write one unit against [`crate::db::exam::delete`] (which locks
31+/// the same row before its cascade) and against a sitting create (whose
32+/// guard below locks it too): a question edit can no longer sail past an
33+/// attempt that started in the gate's gap, and a child whose exam died
34+/// mid-flight finds no row here and is the same 404 the old `no_exam` THROW
35+/// answered with. Real foreign keys retire the bump-and-restore: the child
36+/// inserts themselves refuse a parent that is gone.
37+pub(crate) async fn freeze_gate(conn: &mut PgConnection, exam: &ExamId) -> Result<(), AppError> {
38+ let row = sqlx::query!(
39+ r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#,
40+ exam as &ExamId,
41+ )
42+ .fetch_optional(&mut *conn)
43+ .await?;
44+ if row.is_none() {
45+ return Err(AppError::NotFound);
46+ }
47+ let sat = sqlx::query!(
48+ r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat"#,
49+ exam as &ExamId,
50+ )
51+ .fetch_one(&mut *conn)
52+ .await?;
53+ if sat.sat {
54+ return Err(frozen_error());
55+ }
56+ Ok(())
57+}
58+
2959 /// Stamp the submission time. The caller has already checked the deadline
3060 /// and that the attempt isn't finished.
3161 ///
@@ -36,17 +66,23 @@ fn frozen_error() -> AppError {
3666 /// A whole-row write from the pre-read snapshot would carry its stale
3767 /// `left_at` back over that stamp, erasing the recorded walk-out.
3868 pub async fn finish(db: &Database, attempt: ExamAttempt) -> Result<ExamAttempt, AppError> {
39- let mut result = db
40- .query("UPDATE $id SET finished_at = $at RETURN AFTER")
41- .bind(("id", attempt.id.record()))
42- .bind(("at", Some(Timestamp::now())))
43- .await?
44- .check()?;
45- result
46- .take::<Vec<ExamAttempt>>(0)?
47- .into_iter()
48- .next()
49- .ok_or(AppError::NotFound)
69+ let id = attempt.get_id();
70+ let updated = sqlx::query_as!(
71+ ExamAttempt,
72+ r#"UPDATE exam_attempt SET finished_at = $1
73+ WHERE exam = $2 AND app_user = $3 AND seq = $4
74+ RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq,
75+ started_at AS "started_at: Timestamp",
76+ finished_at AS "finished_at: Option<Timestamp>",
77+ left_at AS "left_at: Option<Timestamp>""#,
78+ Timestamp::now(),
79+ id.exam,
80+ id.user,
81+ id.seq,
82+ )
83+ .fetch_optional(db)
84+ .await?;
85+ updated.ok_or(AppError::NotFound)
5086 }
5187
5288 /// Stamp (or clear) the walked-out marker. The exam room sets it when the
@@ -63,23 +99,73 @@ pub async fn set_left(
6399 attempt: ExamAttempt,
64100 left_at: Option<Timestamp>,
65101 ) -> Result<ExamAttempt, AppError> {
66- let mut result = db
67- .query("UPDATE $id SET left_at = $left RETURN AFTER")
68- .bind(("id", attempt.id.record()))
69- .bind(("left", left_at))
70- .await?
71- .check()?;
72- result
73- .take::<Vec<ExamAttempt>>(0)?
74- .into_iter()
75- .next()
76- .ok_or(AppError::NotFound)
102+ let id = attempt.get_id();
103+ let updated = sqlx::query_as!(
104+ ExamAttempt,
105+ r#"UPDATE exam_attempt SET left_at = $1
106+ WHERE exam = $2 AND app_user = $3 AND seq = $4
107+ RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq,
108+ started_at AS "started_at: Timestamp",
109+ finished_at AS "finished_at: Option<Timestamp>",
110+ left_at AS "left_at: Option<Timestamp>""#,
111+ left_at,
112+ id.exam,
113+ id.user,
114+ id.seq,
115+ )
116+ .fetch_optional(db)
117+ .await?;
118+ updated.ok_or(AppError::NotFound)
119+}
120+
121+/// Stamp `left_at` on one sitting, but only while it is genuinely in
122+/// progress: nothing stamped yet, nothing submitted, and the exam's *live*
123+/// schedule has not run past the sitting's deadline. One conditional
124+/// statement β€” the exam-room teardown's whole stamp, with the re-derive
125+/// [`crate::domain::exam_attempt::ExamAttempt::status`] used to do folded
126+/// into the `WHERE` (joined to `exam` so a deleted exam's sitting is simply
127+/// not stamped, and concurrent last-outs are harmless: only the first finds
128+/// `left_at IS NULL`).
129+pub async fn stamp_left_if_running(
130+ db: &Database,
131+ attempt_id: &ExamAttemptId,
132+ now: Timestamp,
133+) -> Result<(), AppError> {
134+ sqlx::query!(
135+ r#"UPDATE exam_attempt a SET left_at = $4
136+ FROM exam e
137+ WHERE e.id = a.exam
138+ AND a.exam = $1 AND a.app_user = $2 AND a.seq = $3
139+ AND a.left_at IS NULL AND a.finished_at IS NULL
140+ AND (e.duration_ms IS NULL OR $4 < a.started_at + e.duration_ms)
141+ AND (e.duration_ms IS NOT NULL OR e.ends_at IS NULL OR $4 < e.ends_at)"#,
142+ attempt_id.exam,
143+ attempt_id.user,
144+ attempt_id.seq,
145+ now,
146+ )
147+ .execute(db)
148+ .await?;
149+ Ok(())
77150 }
78151
79152 /// One sitting by id β€” the exam room re-reads its own attempt this way,
80153 /// so a retake started elsewhere can never be mistaken for it.
81154 pub async fn read(db: &Database, id: &ExamAttemptId) -> Result<Option<ExamAttempt>, AppError> {
82- Ok(db.select(id.record()).await?)
155+ Ok(sqlx::query_as!(
156+ ExamAttempt,
157+ r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
158+ started_at AS "started_at: Timestamp",
159+ finished_at AS "finished_at: Option<Timestamp>",
160+ left_at AS "left_at: Option<Timestamp>"
161+ FROM exam_attempt
162+ WHERE exam = $1 AND app_user = $2 AND seq = $3"#,
163+ id.exam,
164+ id.user,
165+ id.seq,
166+ )
167+ .fetch_optional(db)
168+ .await?)
83169 }
84170
85171 /// The student's current sitting β€” the highest `seq` for the pair. All
@@ -89,16 +175,21 @@ pub async fn read_latest_for_user(
89175 exam: &ExamId,
90176 user: &UserId,
91177 ) -> Result<Option<ExamAttempt>, AppError> {
92- let mut result = db
93- .query(
94- "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr
95- ORDER BY seq DESC LIMIT 1",
96- )
97- .bind(("ex", exam.record()))
98- .bind(("usr", user.record()))
99- .await?
100- .check()?;
101- Ok(result.take::<Vec<ExamAttempt>>(0)?.into_iter().next())
178+ Ok(sqlx::query_as!(
179+ ExamAttempt,
180+ r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
181+ started_at AS "started_at: Timestamp",
182+ finished_at AS "finished_at: Option<Timestamp>",
183+ left_at AS "left_at: Option<Timestamp>"
184+ FROM exam_attempt
185+ WHERE exam = $1 AND app_user = $2
186+ ORDER BY seq DESC
187+ LIMIT 1"#,
188+ exam as &ExamId,
189+ user as &UserId,
190+ )
191+ .fetch_optional(db)
192+ .await?)
102193 }
103194
104195 /// Every sitting of `user` at `exam`, newest first.
@@ -107,187 +198,180 @@ pub async fn list_for_user(
107198 exam: &ExamId,
108199 user: &UserId,
109200 ) -> Result<Vec<ExamAttempt>, AppError> {
110- let mut result = db
111- .query(
112- "SELECT * FROM exam_attempt WHERE exam = $ex AND user = $usr
113- ORDER BY seq DESC",
114- )
115- .bind(("ex", exam.record()))
116- .bind(("usr", user.record()))
117- .await?
118- .check()?;
119- Ok(result.take::<Vec<ExamAttempt>>(0)?)
201+ Ok(sqlx::query_as!(
202+ ExamAttempt,
203+ r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
204+ started_at AS "started_at: Timestamp",
205+ finished_at AS "finished_at: Option<Timestamp>",
206+ left_at AS "left_at: Option<Timestamp>"
207+ FROM exam_attempt
208+ WHERE exam = $1 AND app_user = $2
209+ ORDER BY seq DESC"#,
210+ exam as &ExamId,
211+ user as &UserId,
212+ )
213+ .fetch_all(db)
214+ .await?)
120215 }
121216
122217 /// Every sitting of `user` nobody has submitted yet, across all exams. Only
123218 /// the *candidates* for "in progress": a deadline comes off the exam's live
124219 /// schedule, so the caller still judges [`ExamAttempt::status`] per exam rather
125-/// than re-spelling that rule in SurrealQL.
220+/// than re-spelling that rule in SQL.
126221 pub async fn list_unfinished_for_user(
127222 db: &Database,
128223 user: &UserId,
129224 ) -> Result<Vec<ExamAttempt>, AppError> {
130- let mut result = db
131- .query("SELECT * FROM exam_attempt WHERE user = $usr AND finished_at = NONE")
132- .bind(("usr", user.record()))
133- .await?
134- .check()?;
135- Ok(result.take::<Vec<ExamAttempt>>(0)?)
225+ Ok(sqlx::query_as!(
226+ ExamAttempt,
227+ r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
228+ started_at AS "started_at: Timestamp",
229+ finished_at AS "finished_at: Option<Timestamp>",
230+ left_at AS "left_at: Option<Timestamp>"
231+ FROM exam_attempt
232+ WHERE app_user = $1 AND finished_at IS NULL
233+ ORDER BY started_at, exam"#,
234+ user as &UserId,
235+ )
236+ .fetch_all(db)
237+ .await?)
136238 }
137239
138240 pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamAttempt>, AppError> {
139- let mut result = db
140- .query("SELECT * FROM exam_attempt WHERE exam = $ex ORDER BY id DESC")
141- .bind(("ex", exam.record()))
142- .await?
143- .check()?;
144- Ok(result.take::<Vec<ExamAttempt>>(0)?)
241+ Ok(sqlx::query_as!(
242+ ExamAttempt,
243+ r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
244+ started_at AS "started_at: Timestamp",
245+ finished_at AS "finished_at: Option<Timestamp>",
246+ left_at AS "left_at: Option<Timestamp>"
247+ FROM exam_attempt
248+ WHERE exam = $1
249+ ORDER BY started_at DESC, seq DESC"#,
250+ exam as &ExamId,
251+ )
252+ .fetch_all(db)
253+ .await?)
145254 }
146255
147256 /// Whether anyone has started this exam β€” the gate that freezes `mode`
148257 /// edits once an attempt exists.
149258 pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result<bool, AppError> {
150- let mut result = db
151- .query("SELECT VALUE id FROM exam_attempt WHERE exam = $ex LIMIT 1")
152- .bind(("ex", exam.record()))
153- .await?
154- .check()?;
155- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
156-}
157-
158-/// Send `statements` wrapped in a transaction that refuses to run them at
159-/// all once `exam` has an attempt β€” the freeze gate, made atomic with the
160-/// write it guards instead of merely preceding it. `freeze_exam` is bound
161-/// here; the caller binds the rest and reads its own results from
162-/// [`FROZEN_SLOT`] onwards.
163-///
164-/// The same transaction *writes* the exam row β€” bumping its mark counter
165-/// and putting it straight back β€” which is what ties every child written
166-/// through here to its exam. The freeze gate only *reads* `exam_attempt`,
167-/// and a read does not survive [`delete`](crate::db::exam::delete)'s
168-/// window: a question or picture landing after that delete removed the exam
169-/// but before it committed reads a row that is still there, while the
170-/// cascade's `DELETE exam_question WHERE exam = $ex` ran on a snapshot
171-/// predating this insert β€” so both commit and the child outlives the exam,
172-/// with neither caller told anything. Writing a key the delete also writes
173-/// makes the two collide and the store refuses one side. It is the shape
174-/// [`crate::db::exam_answer::save`] and
175-/// [`crate::db::menu::bump_menu_and_write`] already use.
176-///
177-/// An orphan here is not merely untidy: an `exam_question` that outlives
178-/// its exam keeps the reference it claimed on its subject (the cascade's
179-/// per-subject decrement counted the rows it could see), and
180-/// [`crate::db::subject::delete`] is gated on that count
181-/// reading zero β€” a subject nobody can ever delete again.
182-///
183-/// The bump is restored *by captured value*, `NONE` included, so the row is
184-/// byte-identical afterwards: the boot backfill still finds the rows it
185-/// keys on (`WHERE result_count = NONE`) and a teacher's PATCH, which pins
186-/// that counter, is not refused because somebody added a question. Writing
187-/// the same value back would not do β€” an `UPDATE` that leaves the document
188-/// unchanged is elided and never reaches the store's write set, so it
189-/// collides with nothing.
190-///
191-/// This replaces a process-wide `EXAM_LOCK.write()` held across the check
192-/// and the write. That lock ordered the two requests but still read the
193-/// attempt table a round trip before it wrote; the gate checks inside the
194-/// writing statement, so a question edit can no longer sail past an attempt
195-/// that started in that gap.
196-///
197-/// The send lives here rather than at the five call sites because a lost
198-/// round has to be re-sent, and only whoever owns the send can re-send: the
199-/// gate reads the very table its rival writes, so the two contend by design
200-/// and a raced edit used to answer 500. The refusal outranks the conflict β€”
201-/// `FROZEN_MARK` is a decision and stays the 409 the pre-flight check
202-/// answers with, and only exhausting the tries becomes a 500. See
203-/// [`transaction_with_retry`] for why the whole error map is scanned: an
204-/// aborted transaction errors *every* slot and all but one say a generic
205-/// "not executed".
206-///
207-/// Returning only on an empty error map is what keeps [`FROZEN_SLOT`]
208-/// (and any slot counted off `num_statements`) correct β€” `take_errors`
209-/// `swap_remove`s errored slots, so a fixed slot read is meaningless once
210-/// anything failed.
211-//
212-// corner-cut: the count and a concurrent `CREATE exam_attempt` are still not
213-// serialized against each other β€” SurrealDB does not conflict-check a
214-// cross-record count (the write skew `db::cap` exists for), so an
215-// attempt landing in the same instant as an edit can still interleave
216-// either way. The mutex this replaces closed that inside one process only,
217-// and there are two, so nothing is lost. Closing it properly means the
218-// cap.rs shape: an attempt counter on the exam row, incremented by the
219-// attempt create, and the write conditioned on `count ?? 0 = 0`.
220-pub async fn write_unfrozen(
221- db: &Database,
222- exam: &ExamId,
223- statements: &str,
224- bindings: Vec<(String, surrealdb::types::Value)>,
225-) -> Result<surrealdb::IndexedResults, AppError> {
226- write_unfrozen_with(db, exam, statements, bindings, Vec::new()).await
259+ let row = sqlx::query!(
260+ r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat"#,
261+ exam as &ExamId,
262+ )
263+ .fetch_one(db)
264+ .await?;
265+ Ok(row.sat)
227266 }
228267
229-/// [`write_unfrozen`] for statements that carry gates of their own:
230-/// each `(marker, refusal)` names a `THROW` the caller's SQL aborts with and
231-/// the error it means. The markers are handed to [`transaction_with_retry`]
232-/// too, so an abort on one is a refusal rather than a round to re-send.
233-///
234-/// The freeze still outranks every one of them: a caller folding a counter
235-/// claim in here is refused as frozen even when its own gate would also have
236-/// fired, which is the answer the pre-flight check has always given.
237-pub async fn write_unfrozen_with(
238- db: &Database,
268+/// The sitting-create guard: the exam row locked `FOR UPDATE` and
269+/// re-judged *inside the inserting transaction* β€” draft (a 404, a draft is
270+/// invisible to students), no mode (a 409: visible, nothing to sit), the
271+/// window not yet open, the window already closed. This is what the old
272+/// writer lease `EXAM_LOCK` used to buy the sittable/window gates: they are
273+/// now judged against the locked row the attempt lands under, so a mode
274+/// change or re-draft cannot slip between a gate and the insert. The
275+/// refusal texts are [`crate::service::exam_attempt`]'s own β€” the same
276+/// words that pre-flight answers, so a client cannot tell which fired.
277+pub(crate) async fn guard_start(
278+ conn: &mut PgConnection,
239279 exam: &ExamId,
240- statements: &str,
241- bindings: Vec<(String, surrealdb::types::Value)>,
242- refusals: Vec<(&str, AppError)>,
243-) -> Result<surrealdb::IndexedResults, AppError> {
244- let sql = format!(
245- "BEGIN TRANSACTION;
246- IF array::len((SELECT VALUE id FROM exam_attempt \
247- WHERE exam = $freeze_exam LIMIT 1)) > 0 {{ THROW '{FROZEN_MARK}' }};
248- LET $was_results = \
249- (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $freeze_exam);
250- LET $touched = (UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = \
251- ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);
252- IF array::len($touched) = 0 {{ THROW '{GONE_MARK}' }};
253- UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = $was_results;
254- {statements}
255- COMMIT TRANSACTION;"
256- );
257- let mut bound = vec![("freeze_exam".into(), exam.record().into_value())];
258- bound.extend(bindings);
259- let mut marks = vec![FROZEN_MARK, GONE_MARK];
260- marks.extend(refusals.iter().map(|(marker, _)| *marker));
261- let (result, mut errors) = transaction_with_retry(db, &sql, &bound, &marks).await?;
262- let thrown = |marker: &str| {
263- errors
264- .values()
265- .any(|error| error.to_string().contains(marker))
280+ now: Timestamp,
281+) -> Result<(), AppError> {
282+ let row = sqlx::query!(
283+ r#"SELECT draft AS "draft: bool", mode AS "mode: Option<ExamMode>",
284+ starts_at AS "starts_at: Option<Timestamp>",
285+ ends_at AS "ends_at: Option<Timestamp>"
286+ FROM exam WHERE id = $1 FOR UPDATE"#,
287+ exam as &ExamId,
288+ )
289+ .fetch_optional(&mut *conn)
290+ .await?;
291+ let Some(row) = row else {
292+ return Err(AppError::NotFound);
266293 };
267- if thrown(FROZEN_MARK) {
268- return Err(frozen_error());
269- }
270- // The exam is gone: the same 404 every one of these writes' handlers
271- // answers a missing exam with, and it outranks the callers' own gates
272- // for the freeze's reason β€” there is nothing left to refuse *about*.
273- if thrown(GONE_MARK) {
294+ if row.draft {
274295 return Err(AppError::NotFound);
275296 }
276- for (marker, refusal) in refusals {
277- if thrown(marker) {
278- return Err(refusal);
279- }
297+ if row.mode.is_none() {
298+ return Err(AppError::Conflict(
299+ "this exam is not scheduled β€” there is nothing to sit (give it a mode: sync, async, or open)",
300+ ));
301+ }
302+ if row.starts_at.is_some_and(|starts_at| now < starts_at) {
303+ return Err(AppError::Conflict("the exam has not started yet"));
280304 }
281- match errors.drain().map(|(_, error)| error).next() {
282- Some(error) => Err(error.into()),
283- None => Ok(result),
305+ if row.ends_at.is_some_and(|ends_at| now >= ends_at) {
306+ return Err(AppError::Conflict("the exam has already ended"));
284307 }
308+ Ok(())
285309 }
286310
287-/// The first slot a [`write_unfrozen`] caller's own statements land
288-/// in: `BEGIN`, the freeze `IF`, and the exam touch's two `LET`s, `IF` and
289-/// restoring `UPDATE` take one each.
290-pub const FROZEN_SLOT: usize = 6;
311+/// Insert the sitting row, claiming the student's `exam_sat_total` in the
312+/// same statement when β€” and only when β€” this is a first sitting (`seq ==
313+/// 1`): that counter is *exams sat*, not sittings, and a retake counts
314+/// nothing. The claim-CTE recipe ([`cap`]): bump the counter row, insert
315+/// the child only if the bump landed, and let the sitting's natural
316+/// composite primary key (`exam_attempt_exam_user_seq`) answer "another
317+/// writer started this very sitting first" as `Claimed::Duplicate`. The
318+/// bump rides the insert's own transaction, so a refused insert takes its
319+/// increment straight back.
320+///
321+/// `Claimed::Full` here can only mean the student's account row is missing
322+/// β€” nothing caps sittings β€” which the caller surfaces as its own internal.
323+pub(crate) async fn create_in(
324+ conn: &mut PgConnection,
325+ attempt: &ExamAttempt,
326+ count_sitting: bool,
327+) -> Result<Claimed<ExamAttempt>, AppError> {
328+ let bump = i64::from(count_sitting);
329+ let created = sqlx::query_as!(
330+ ExamAttempt,
331+ r#"WITH seat AS (
332+ UPDATE app_user SET exam_sat_total = app_user.exam_sat_total + $4
333+ WHERE id = $2
334+ RETURNING 1)
335+ INSERT INTO exam_attempt (exam, app_user, seq, started_at, finished_at, left_at)
336+ SELECT $1, $2, $3, $5, NULL, NULL WHERE EXISTS (SELECT 1 FROM seat)
337+ RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq,
338+ started_at AS "started_at: Timestamp",
339+ finished_at AS "finished_at: Option<Timestamp>",
340+ left_at AS "left_at: Option<Timestamp>""#,
341+ attempt.exam,
342+ attempt.user,
343+ attempt.seq,
344+ bump,
345+ attempt.started_at,
346+ )
347+ .fetch_optional(&mut *conn)
348+ .await;
349+ match created {
350+ Err(err) if unique_violation(&err) == Some("exam_attempt_exam_user_seq") => {
351+ Ok(Claimed::Duplicate)
352+ }
353+ Err(err) => Err(err.into()),
354+ Ok(None) => Ok(Claimed::Full),
355+ Ok(Some(attempt)) => Ok(Claimed::Made(attempt)),
356+ }
357+}
358+
359+/// The sitting create as one transaction: [`guard_start`], then
360+/// [`create_in`]. Retried while Postgres answers "contended"; a duplicate
361+/// or a missing student row is a verdict, not a conflict, and is never
362+/// re-sent.
363+pub async fn create(
364+ db: &Database,
365+ attempt: &ExamAttempt,
366+ count_sitting: bool,
367+ now: Timestamp,
368+) -> Result<Claimed<ExamAttempt>, AppError> {
369+ tx_with_retry(db, false, async |conn| {
370+ guard_start(conn, &attempt.exam, now).await?;
371+ create_in(conn, attempt, count_sitting).await
372+ })
373+ .await
374+}
291375
292376 #[cfg(test)]
293377 mod tests {
src/db/exam_question.rsmodified+232 -206
@@ -6,27 +6,19 @@
66
77 use std::collections::HashSet;
88
9-use surrealdb::types::{RecordId, SurrealValue};
9+use sqlx::PgConnection;
1010
11-use crate::constant::SUBJECT_QUESTION_COUNT_FIELD;
12-use crate::database::Database;
13-use crate::db::cap;
14-use crate::db::page::PagedList;
11+use crate::database::{Database, tx_with_retry};
12+use crate::db::exam_attempt::freeze_gate;
13+use crate::db::page::{PagedList, Param};
1514 use crate::domain::bank_question::BankQuestionId;
1615 use crate::domain::exam::ExamId;
1716 use crate::domain::exam_question::{
18- ExamQuestion, ExamQuestionId, QuestionPoints, QuestionSpec, QuestionText,
17+ Choice, ExamQuestion, ExamQuestionId, QuestionPoints, QuestionSpec, QuestionText,
1918 };
2019 use crate::domain::subject::SubjectId;
2120 use crate::error::{AppError, ValidationError};
22-
23-/// The `THROW` markers the folded counter moves abort with: the subject the
24-/// reference was to be claimed on is gone, the question being patched is gone,
25-/// and the subject this move started from is no longer the one the handler
26-/// read. File-local like every other marker set (`cap`'s, `subject`'s).
27-const SUBJECT_MARK: &str = "question_subject_gone";
28-const ROW_MARK: &str = "question_row_gone";
29-const STALE_MARK: &str = "question_stale_move";
21+use sqlx::types::Json;
3022
3123 /// The one answer for a subject that isn't there β€” a claim missing it and the
3224 /// web layer's pre-flight lookup missing it are the same 400.
@@ -72,7 +64,6 @@ async fn insert(
7264 spec: QuestionSpec,
7365 from_bank: Option<BankQuestionId>,
7466 ) -> Result<ExamQuestion, AppError> {
75- let counted = subject.record();
7667 let question = ExamQuestion {
7768 id: ExamQuestionId::generate(),
7869 exam: exam.clone(),
@@ -89,61 +80,87 @@ async fn insert(
8980 // The freeze gate and the subject's reference ride in the same
9081 // transaction as the insert: a question cannot appear under an exam
9182 // somebody has already started, and the claim that accounts for it
92- // cannot outlive a row that never landed. Claiming in its own query
93- // (with a release on failure, as this did) leaves a window where a
94- // crash strands the count β€” and the subject delete is conditioned on
95- // that count reading zero, so a stranded one makes the subject
96- // undeletable forever. A missed claim means the subject is already gone
97- // β€” the same 400 the web layer's pre-flight check answers with.
83+ // cannot outlive a row that never landed. A missed claim means the
84+ // subject is already gone β€” the same 400 the web layer's pre-flight
85+ // check answers with.
9886 //
99- // Re-sendable despite the `CREATE`: a lost round aborts having written
100- // nothing and `$id` is a ULID minted once per call, so the re-send
101- // cannot answer "already exists" (there is no UNIQUE index on
102- // `exam_question`) β€” the one thing the retry cannot survive.
103- let id = question.id.record();
104- // One counter write in flight at a time, like every other counter write.
105- let _guard = cap::counter_lock().await;
106- let mut result = crate::db::exam_attempt::write_unfrozen_with(
107- db,
108- exam,
109- &format!(
110- "LET $seat = (UPDATE $subject SET {SUBJECT_QUESTION_COUNT_FIELD} = \
111- ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);
112- IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }};
113- CREATE $id CONTENT $question;"
114- ),
115- vec![
116- ("subject".into(), counted.into_value()),
117- ("id".into(), id.into_value()),
118- ("question".into(), question.into_value()),
119- ],
120- vec![(SUBJECT_MARK, dead_subject())],
87+ // The id is a freshly minted UUIDv7, so no rival can aim at it: the
88+ // only possible duplicate key is one this call minted, which is none.
89+ tx_with_retry(db, false, async |conn| {
90+ freeze_gate(conn, exam).await?;
91+ claim_subject_and_insert(conn, &question).await
92+ })
93+ .await
94+}
95+
96+/// The subject's reference claim and the row insert as one statement β€” the
97+/// counter and the row commit together, and zero rows out means the subject
98+/// was already gone (the claim's `UPDATE` found nothing to increment). The
99+/// same verdict as the old `question_subject_gone` THROW, which nothing
100+/// else could reach: the insert is refused with its claim, atomically.
101+async fn claim_subject_and_insert(
102+ conn: &mut PgConnection,
103+ question: &ExamQuestion,
104+) -> Result<ExamQuestion, AppError> {
105+ let created = sqlx::query_as!(
106+ ExamQuestion,
107+ r#"WITH seat AS (
108+ UPDATE subject SET exam_question_count = subject.exam_question_count + 1
109+ WHERE id = $1
110+ RETURNING 1)
111+ INSERT INTO exam_question (id, exam, subject, text, kind, points,
112+ choices, correct, from_bank, banked_as)
113+ SELECT $2, $3, $1, $4, $5, $6, $7, $8, $9, NULL
114+ WHERE EXISTS (SELECT 1 FROM seat)
115+ RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId",
116+ subject AS "subject: SubjectId", text AS "text: QuestionText",
117+ kind AS "kind: QuestionKind", points AS "points: QuestionPoints",
118+ choices AS "choices: Option<Json<Vec<Choice>>>",
119+ correct AS "correct: Option<ChoiceId>",
120+ from_bank AS "from_bank: Option<BankQuestionId>",
121+ banked_as AS "banked_as: Option<BankQuestionId>""#,
122+ question.subject,
123+ question.id,
124+ question.exam,
125+ question.text,
126+ question.kind,
127+ question.points,
128+ question.choices,
129+ question.correct,
130+ question.from_bank,
121131 )
132+ .fetch_optional(&mut *conn)
122133 .await?;
123- // Counted off the statements that actually ran rather than a fixed
124- // slot, so folding another gate in above can never mis-read the row.
125- let slot = result.num_statements().saturating_sub(2);
126- result
127- .take::<Vec<ExamQuestion>>(slot)?
128- .into_iter()
129- .next()
130- .ok_or_else(|| AppError::Internal("failed to create exam question".into()))
134+ created.ok_or_else(dead_subject)
131135 }
132136
133137 pub async fn read(db: &Database, id: &ExamQuestionId) -> Result<Option<ExamQuestion>, AppError> {
134- Ok(db.select(id.record()).await?)
138+ Ok(sqlx::query_as!(
139+ ExamQuestion,
140+ r#"SELECT id AS "id: ExamQuestionId", exam AS "exam: ExamId",
141+ subject AS "subject: SubjectId", text AS "text: QuestionText",
142+ kind AS "kind: QuestionKind", points AS "points: QuestionPoints",
143+ choices AS "choices: Option<Json<Vec<Choice>>>",
144+ correct AS "correct: Option<ChoiceId>",
145+ from_bank AS "from_bank: Option<BankQuestionId>",
146+ banked_as AS "banked_as: Option<BankQuestionId>"
147+ FROM exam_question WHERE id = $1"#,
148+ id as &ExamQuestionId,
149+ )
150+ .fetch_optional(db)
151+ .await?)
135152 }
136153
137-/// The exam's questions in presentation order (ULID ids sort by creation).
154+/// The exam's questions in presentation order (UUIDv7 ids sort by creation).
138155 pub async fn list_for_exam(
139156 db: &Database,
140157 exam: &ExamId,
141158 limit: Option<i64>,
142159 offset: i64,
143160 ) -> Result<(Vec<ExamQuestion>, i64), AppError> {
144- PagedList::new("exam_question WHERE exam = $ex", "ORDER BY id ASC")
145- .bind("ex", exam.record())
146- .run(limit, offset, db)
161+ PagedList::new("exam_question WHERE exam = $1", "ORDER BY id ASC")
162+ .bind(Param::Uuid(exam.uuid()))
163+ .run::<ExamQuestion>(limit, offset, db)
147164 .await
148165 }
149166
@@ -166,8 +183,7 @@ pub async fn list_for_exam(
166183 ///
167184 /// So: collect every template id reachable from a live exam by either
168185 /// column, then name any of `exam`'s questions pointing at one by either
169-/// column. `$shared` is built from `!= NONE` filters, so it never holds a
170-/// `NONE` for an unlinked question's absent column to match against.
186+/// column.
171187 pub async fn list_shared_with(
172188 db: &Database,
173189 exam: &ExamId,
@@ -176,27 +192,26 @@ pub async fn list_shared_with(
176192 if live.is_empty() {
177193 return Ok(HashSet::new());
178194 }
179- let mut result = db
180- .query(
181- "LET $shared = array::union(
182- (SELECT VALUE from_bank FROM exam_question
183- WHERE exam IN $live AND from_bank != NONE),
184- (SELECT VALUE banked_as FROM exam_question
185- WHERE exam IN $live AND banked_as != NONE));
186- SELECT VALUE id FROM exam_question
187- WHERE exam = $ex AND (from_bank IN $shared OR banked_as IN $shared)",
188- )
189- .bind(("ex", exam.record()))
190- .bind((
191- "live",
192- live.iter().map(ExamId::record).collect::<Vec<RecordId>>(),
193- ))
194- .await?
195- .check()?;
196- Ok(result
197- .take::<Vec<ExamQuestionId>>(1)?
198- .iter()
199- .map(|id| id.key().to_string())
195+ let live = live.iter().map(ExamId::uuid).collect::<Vec<_>>();
196+ let rows = sqlx::query!(
197+ r#"WITH shared AS (
198+ SELECT from_bank AS t FROM exam_question
199+ WHERE exam = ANY($1) AND from_bank IS NOT NULL
200+ UNION
201+ SELECT banked_as FROM exam_question
202+ WHERE exam = ANY($1) AND banked_as IS NOT NULL)
203+ SELECT q.id AS "id: ExamQuestionId" FROM exam_question q
204+ WHERE q.exam = $2
205+ AND (q.from_bank IN (SELECT t FROM shared)
206+ OR q.banked_as IN (SELECT t FROM shared))"#,
207+ live,
208+ exam as &ExamId,
209+ )
210+ .fetch_all(db)
211+ .await?;
212+ Ok(rows
213+ .into_iter()
214+ .map(|row| row.id.key())
200215 .collect())
201216 }
202217
@@ -208,7 +223,7 @@ pub async fn list_shared_with(
208223 /// `from_bank`/`banked_as`, which [`link_banked_as`] writes from a
209224 /// *different* request: re-stating this snapshot's copy of them would
210225 /// revert a to-bank save that landed in between. That is exactly what the
211-/// caller's `EXAM_LOCK.write()` used to order (inside one process), and
226+/// caller's old `EXAM_LOCK.write()` used to order (inside one process), and
212227 /// naming the columns removes the need for any ordering at all.
213228 pub async fn update(
214229 db: &Database,
@@ -225,8 +240,7 @@ pub async fn update(
225240 // undeletable forever).
226241 //
227242 // The two are armed on *different* conditions, which is the whole of
228- // the rule ([`crate::db::field_update::FieldUpdate::refcount`] states
229- // it the same way): the counter statements only when the link actually
243+ // the rule: the counter statements only when the link actually
230244 // changes, but the CAS whenever this write *carries* the link β€” and it
231245 // always does, because the handler fills an omitted `subject_id` from
232246 // the row it read (`web::exams::questions`), so `subject` is in the
@@ -235,88 +249,81 @@ pub async fn update(
235249 // subject its own stale snapshot held, sent while a rival's move
236250 // already landed, writes that stale subject straight back over the
237251 // winner β€” a revert with the counters left pointing at the move.
238- let retag =
239- (subject != question.subject).then(|| (subject.record(), question.subject.record()));
240- let write = "UPDATE $id SET subject = $subject, text = $text, points = $points,
241- kind = $kind, choices = $choices, correct = $correct";
242- let mut bindings = vec![
243- ("id".into(), question.id.record().into_value()),
244- ("subject".into(), subject.record().into_value()),
245- ("text".into(), text.into_value()),
246- ("points".into(), points.into_value()),
247- ("kind".into(), spec.kind.into_value()),
248- ("choices".into(), spec.choices.into_value()),
249- ("correct".into(), spec.correct.into_value()),
250- ];
251- let mut statements: Vec<String> = Vec::new();
252- let mut refusals: Vec<(&str, AppError)> = Vec::new();
253- if let Some((next, previous)) = &retag {
254- statements.push(format!(
255- "UPDATE $ref_release SET {SUBJECT_QUESTION_COUNT_FIELD} = \
256- math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0])"
257- ));
258- statements.push(format!(
259- "LET $seat = (UPDATE $ref_claim SET {SUBJECT_QUESTION_COUNT_FIELD} = \
260- ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id)"
261- ));
262- statements.push(format!(
263- "IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}"
264- ));
265- bindings.push(("ref_claim".into(), next.clone().into_value()));
266- bindings.push(("ref_release".into(), previous.clone().into_value()));
267- refusals.push((SUBJECT_MARK, dead_subject()));
268- }
269- // The CAS: the row write matches only while the question still sits on
270- // the subject this handler read. A genuine no-op re-state passes it
271- // trivially (the row holds exactly what is expected); a stale one β€”
272- // whether it moves the link or restates it β€” matches nothing, aborts
273- // the whole transaction, and so claims nothing and answers 409.
274- bindings.push((
275- "ref_expected".into(),
276- question.subject.record().into_value(),
277- ));
278- statements.push(format!(
279- "LET $row = ({write} WHERE subject = $ref_expected RETURN AFTER)"
280- ));
281- statements.push(format!(
282- "IF array::len($row) = 0 {{ \
283- LET $live = (UPDATE $id WHERE subject != $ref_expected RETURN VALUE id); \
284- IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} \
285- ELSE {{ THROW '{STALE_MARK}' }} }}"
286- ));
287- statements.push("RETURN $row".into());
288- refusals.push((
289- STALE_MARK,
290- AppError::Conflict(
291- "the subject this question was read on changed since; re-read and retry",
292- ),
293- ));
294- // The row is gone: the same 404 an empty write answers with, so the
295- // deleted-row case is unchanged.
296- refusals.push((ROW_MARK, AppError::NotFound));
297- let statements = format!("{};", statements.join("; "));
298- // One counter write in flight at a time β€” only a move writes one.
299- let _guard = match &retag {
300- Some(_) => Some(cap::counter_lock().await),
301- None => None,
302- };
303- let mut result = crate::db::exam_attempt::write_unfrozen_with(
304- db,
305- &question.exam,
306- &statements,
307- bindings,
308- refusals,
309- )
310- .await?;
311- // Read off the trailing `RETURN` rather than a fixed slot: a re-tag
312- // arms three more statements than a plain PATCH does (and an `IF`
313- // block is one slot whether or not it is taken).
314- let slot = result.num_statements().saturating_sub(2);
315- result
316- .take::<Vec<ExamQuestion>>(slot)?
317- .into_iter()
318- .next()
319- .ok_or(AppError::NotFound)
252+ let retag = (subject != question.subject).then(|| (subject, question.subject.clone()));
253+ tx_with_retry(db, false, async |conn| {
254+ // Freeze first, as always: it outranks every caller gate, and a
255+ // frozen exam answers the same 409 the pre-flight check gave.
256+ freeze_gate(conn, &question.exam).await?;
257+ if let Some((next, previous)) = &retag {
258+ sqlx::query!(
259+ r#"UPDATE subject SET exam_question_count =
260+ GREATEST(exam_question_count - 1, 0)
261+ WHERE id = $1"#,
262+ previous as &SubjectId,
263+ )
264+ .execute(&mut *conn)
265+ .await?;
266+ let claimed = sqlx::query!(
267+ r#"UPDATE subject SET exam_question_count = subject.exam_question_count + 1
268+ WHERE id = $1 RETURNING 1"#,
269+ next as &SubjectId,
270+ )
271+ .fetch_optional(&mut *conn)
272+ .await?;
273+ if claimed.is_none() {
274+ return Err(dead_subject());
275+ }
276+ }
277+ // The CAS: the row write matches only while the question still sits on
278+ // the subject this handler read. A genuine no-op re-state passes it
279+ // trivially (the row holds exactly what is expected); a stale one β€”
280+ // whether it moves the link or restates it β€” matches nothing, aborts
281+ // the whole transaction, and so claims nothing and answers 409.
282+ let written = sqlx::query_as!(
283+ ExamQuestion,
284+ r#"UPDATE exam_question
285+ SET subject = $2, text = $3, points = $4, kind = $5,
286+ choices = $6, correct = $7
287+ WHERE id = $1 AND subject = $8
288+ RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId",
289+ subject AS "subject: SubjectId", text AS "text: QuestionText",
290+ kind AS "kind: QuestionKind", points AS "points: QuestionPoints",
291+ choices AS "choices: Option<Json<Vec<Choice>>>",
292+ correct AS "correct: Option<ChoiceId>",
293+ from_bank AS "from_bank: Option<BankQuestionId>",
294+ banked_as AS "banked_as: Option<BankQuestionId>""#,
295+ question.id as &ExamQuestionId,
296+ subject,
297+ text,
298+ points,
299+ spec.kind,
300+ spec.choices,
301+ spec.correct,
302+ question.subject as &SubjectId,
303+ )
304+ .fetch_optional(&mut *conn)
305+ .await?;
306+ let Some(written) = written else {
307+ // The row is gone, or it moved under the snapshot. The same
308+ // 404 an empty write used to answer with distinguishes the
309+ // deleted-row case; anything still standing is a stale read,
310+ // which is the 409.
311+ let live = sqlx::query!(
312+ r#"SELECT EXISTS(SELECT 1 FROM exam_question WHERE id = $1) AS live"#,
313+ question.id as &ExamQuestionId,
314+ )
315+ .fetch_one(&mut *conn)
316+ .await?;
317+ if !live.live {
318+ return Err(AppError::NotFound);
319+ }
320+ return Err(AppError::Conflict(
321+ "the subject this question was read on changed since; re-read and retry",
322+ ));
323+ };
324+ Ok(written)
325+ })
326+ .await
320327 }
321328
322329 /// Point the question's `banked_as` at the bank template it was just saved
@@ -330,26 +337,28 @@ pub async fn update(
330337 /// Field-scoped write, unlike [`update`]: the caller awaits a bank
331338 /// insert plus the whole blob-copy loop between reading this row and
332339 /// linking it, so the row it holds is long stale by now β€” a whole-row save
333-/// would silently revert whatever landed in that window. (The caller takes
334-/// `EXAM_LOCK.read()` around this call, which is what keeps
335-/// [`update`]'s whole-row save from clobbering the link in the other
336-/// direction; the lease guards the ordering, not the staleness.)
340+/// would silently revert whatever landed in that window.
337341 pub async fn link_banked_as(
338342 db: &Database,
339343 question: ExamQuestion,
340344 template: BankQuestionId,
341345 ) -> Result<ExamQuestion, AppError> {
342- let mut result = db
343- .query("UPDATE $id SET banked_as = $bank RETURN AFTER")
344- .bind(("id", question.id.record()))
345- .bind(("bank", template.record()))
346- .await?
347- .check()?;
348- result
349- .take::<Vec<ExamQuestion>>(0)?
350- .into_iter()
351- .next()
352- .ok_or(AppError::NotFound)
346+ let linked = sqlx::query_as!(
347+ ExamQuestion,
348+ r#"UPDATE exam_question SET banked_as = $2 WHERE id = $1
349+ RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId",
350+ subject AS "subject: SubjectId", text AS "text: QuestionText",
351+ kind AS "kind: QuestionKind", points AS "points: QuestionPoints",
352+ choices AS "choices: Option<Json<Vec<Choice>>>",
353+ correct AS "correct: Option<ChoiceId>",
354+ from_bank AS "from_bank: Option<BankQuestionId>",
355+ banked_as AS "banked_as: Option<BankQuestionId>""#,
356+ question.id as &ExamQuestionId,
357+ template as &BankQuestionId,
358+ )
359+ .fetch_optional(db)
360+ .await?;
361+ linked.ok_or(AppError::NotFound)
353362 }
354363
355364 /// Delete the question and cascade-remove its answers and image rows, so
@@ -359,33 +368,50 @@ pub async fn link_banked_as(
359368 /// delete β€” and the cascade now shares that transaction too, so a failure
360369 /// mid-way can no longer strand answers whose question survived.
361370 pub async fn delete(db: &Database, question: ExamQuestion) -> Result<ExamQuestion, AppError> {
362- let mut result = crate::db::exam_attempt::write_unfrozen(
363- db,
364- &question.exam,
365- &format!(
366- "DELETE exam_answer WHERE question = $q;
367- DELETE question_image WHERE question = $q;
368- LET $gone = (DELETE $q RETURN BEFORE);
369- FOR $sub IN ($gone.subject ?? []) {{
370- UPDATE $sub SET {SUBJECT_QUESTION_COUNT_FIELD} =
371- math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0])
372- }};
373- RETURN $gone;"
374- ),
375- vec![("q".into(), question.id.record().into_value())],
376- )
377- .await?;
378- // The subject's reference is given back inside this same transaction,
379- // driven off what the delete actually removed β€” a question that wasn't
380- // there decrements nothing. Read through the trailing `RETURN` rather
381- // than a hand-counted slot, so inserting a cascade statement above can
382- // never turn a delete into a 404 (see [`crate::domain::exam::Exam`]).
383- let slot = result.num_statements().saturating_sub(2);
384- result
385- .take::<Vec<ExamQuestion>>(slot)?
386- .into_iter()
387- .next()
388- .ok_or(AppError::NotFound)
371+ tx_with_retry(db, false, async |conn| {
372+ freeze_gate(conn, &question.exam).await?;
373+ sqlx::query!(
374+ r#"DELETE FROM exam_answer WHERE question = $1"#,
375+ question.id as &ExamQuestionId,
376+ )
377+ .execute(&mut *conn)
378+ .await?;
379+ sqlx::query!(
380+ r#"DELETE FROM question_image WHERE question = $1"#,
381+ question.id as &ExamQuestionId,
382+ )
383+ .execute(&mut *conn)
384+ .await?;
385+ let deleted = sqlx::query_as!(
386+ ExamQuestion,
387+ r#"DELETE FROM exam_question WHERE id = $1
388+ RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId",
389+ subject AS "subject: SubjectId", text AS "text: QuestionText",
390+ kind AS "kind: QuestionKind", points AS "points: QuestionPoints",
391+ choices AS "choices: Option<Json<Vec<Choice>>>",
392+ correct AS "correct: Option<ChoiceId>",
393+ from_bank AS "from_bank: Option<BankQuestionId>",
394+ banked_as AS "banked_as: Option<BankQuestionId>""#,
395+ question.id as &ExamQuestionId,
396+ )
397+ .fetch_optional(&mut *conn)
398+ .await?;
399+ // The subject's reference is given back inside this same transaction,
400+ // driven off what the delete actually removed β€” a question that wasn't
401+ // there decrements nothing.
402+ if let Some(deleted) = &deleted {
403+ sqlx::query!(
404+ r#"UPDATE subject SET exam_question_count =
405+ GREATEST(exam_question_count - 1, 0)
406+ WHERE id = $1"#,
407+ deleted.subject as &SubjectId,
408+ )
409+ .execute(&mut *conn)
410+ .await?;
411+ }
412+ deleted.ok_or(AppError::NotFound)
413+ })
414+ .await
389415 }
390416
391417 #[cfg(test)]
src/db/exam_result.rsmodified+245 -211
@@ -1,50 +1,42 @@
11 //! The `exam_result` table: the mark's claim-riding upsert, the per-sitting
22 //! history reads, and the refunding delete. The grade pre-flight (draft, kind,
3-//! grader/target walls) and the `EXAM_LOCK` lease live in
3+//! grader/target walls) lives in
44 //! [`crate::service::exam_result`]; the mark newtype and the latest-per-pair
55 //! fold live in [`crate::domain::exam_result`].
66
7-use surrealdb::types::SurrealValue;
8-
9-use crate::constant::{
10- EXAM_RESULT_COUNT_FIELD, HIGH_MARK_MIN, HIGH_MARK_TOTAL_FIELD, MARKS_GIVEN_TOTAL_FIELD,
11- REF_COUNT_FIELD, REF_RETIRED_FIELD,
12-};
13-use crate::database::{Database, transaction_with_retry};
14-use crate::db::cap;
7+use crate::constant::HIGH_MARK_MIN;
8+use crate::database::{Database, tx_with_retry};
159 use crate::domain::course::CourseId;
1610 use crate::domain::exam::ExamId;
1711 use crate::domain::exam_result::{
18- ExamResult, ExamResultId, Mark, draft_error, kind_ref, latest_per_pair, retired_kind_error,
12+ ExamResult, Mark, draft_error, latest_per_pair, retired_kind_error,
1913 };
2014 use crate::domain::user::UserId;
2115 use crate::error::AppError;
2216
23-/// The `THROW` marker the in-transaction kind claim aborts with β€” the mark's
24-/// own transaction refusing a name the school has retired.
25-const RETIRED_MARK: &str = "kind_retired";
26-
2717 /// A single user's result for an exam, if graded β€” the latest sitting's mark.
2818 async fn find(db: &Database, exam: &ExamId, user: &UserId) -> Result<Option<ExamResult>, AppError> {
2919 // Grade-of-record is the latest sitting's mark: the highest seq wins.
30- let mut result = db
31- .query(
32- "SELECT * FROM exam_result WHERE exam = $ex AND user = $usr
33- ORDER BY seq DESC LIMIT 1",
34- )
35- .bind(("ex", exam.record()))
36- .bind(("usr", user.record()))
37- .await?
38- .check()?;
39- Ok(result.take::<Vec<ExamResult>>(0)?.into_iter().next())
20+ Ok(sqlx::query_as!(
21+ ExamResult,
22+ r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
23+ mark AS "mark: Mark", graded_by AS "graded_by: UserId"
24+ FROM exam_result WHERE exam = $1 AND app_user = $2
25+ ORDER BY seq DESC LIMIT 1"#,
26+ exam as &ExamId,
27+ user as &UserId,
28+ )
29+ .fetch_optional(db)
30+ .await?)
4031 }
4132
4233 /// Record (or overwrite) `user`'s mark for the `seq`th sitting of `exam`.
43-/// One row per (exam, user, seq), keyed by a deterministic composite id so
44-/// this is a single atomic UPSERT β€” concurrent grades for the same sitting
45-/// converge on one row instead of racing the unique index into a 500.
46-/// Grading a retake writes a fresh mark at the current seq and never touches
47-/// prior sittings' marks; the latest seq is the grade-of-record.
34+/// One row per (exam, user, seq), keyed by the natural composite primary key
35+/// `exam_result_exam_user_seq`, so this is a single atomic UPSERT β€”
36+/// concurrent grades for the same sitting converge on one row instead of
37+/// racing the unique index into a 500. Grading a retake writes a fresh mark
38+/// at the current seq and never touches prior sittings' marks; the latest
39+/// seq is the grade-of-record.
4840 ///
4941 /// `kind` is the exam's kind, and this is where a mark takes its reference
5042 /// on it β€” claimed *inside the mark's own transaction*, and only on the
@@ -58,7 +50,10 @@ async fn find(db: &Database, exam: &ExamId, user: &UserId) -> Result<Option<Exam
5850 /// The exam's own `result_count` is claimed in the same breath, and it is
5951 /// what a kind change is refused against: the exam PATCH pins that counter,
6052 /// so a mark landing while it decides cannot slip past its gate and leave
61-/// itself counted under a kind its exam no longer carries.
53+/// itself counted under a kind its exam no longer carries. The exam row is
54+/// taken `FOR UPDATE` first β€” which is also what serializes this write with
55+/// a concurrent re-draft and with the exam-delete cascade, replacing the
56+/// reader lease grading used to hold.
6257 ///
6358 /// An overwrite (a regrade of a sitting already marked) claims *nothing*:
6459 /// one mark, one reference, so the branch that finds a row simply leaves
@@ -91,115 +86,111 @@ pub async fn grade(
9186 graded_by: &UserId,
9287 kind: &str,
9388 ) -> Result<ExamResult, AppError> {
94- let result = ExamResult {
95- id: ExamResultId::composite(exam, user, seq),
96- exam: exam.clone(),
97- user: user.clone(),
98- seq,
99- mark,
100- graded_by: graded_by.clone(),
101- };
10289 // The "exists" and "not a draft" gates ride in the same transaction as
10390 // the mark, the mirror of the re-draft gate on
10491 // `crate::db::exam::update_if_unchanged`: between them, a mark and a
10592 // re-draft racing each other can only ever leave one of the two applied,
10693 // whichever process either ran in. The existence gate is not
107- // redundant with the draft one β€” a deleted exam reads NONE, which is
108- // *falsy*, so the draft gate alone waved a mark onto an exam that no
109- // longer existed. The caller's pre-flight check answers the same 409
110- // one round trip earlier. It is also what makes a separate "did the
111- // exam survive my claim?" check moot: the claim now sits behind this
112- // gate instead of in front of it.
94+ // redundant with the draft one β€” a missing row answers the same `404`
95+ // the old `exam_missing` THROW answered with, and `draft` alone could
96+ // never see a row that is not there. The caller's pre-flight check
97+ // answers the same 409 one round trip earlier.
11398 //
114- // `$before` is the sitting's *previous mark*, and it answers both
115- // questions off one read: `mark` is a mandatory column on a schemafull
116- // row, so `NONE` there means no row at all β€” the claim branch β€” while a
117- // number is what the student's counter takes its difference against.
118- // Read one statement before the counters inside the same transaction:
119- // read anywhere else it would be a guess about a row two graders may be
120- // writing at once, and the difference would be taken against a mark
121- // some other round had already replaced.
122- //
123- // Re-sent while the store answers "conflict, retry": the gates read a
124- // column an exam PATCH writes, and the counters are the ones a
125- // concurrent delete gives back, so this contends on three records by
126- // design. Sound to re-send because no statement in it can legitimately
127- // answer "already exists": the counter writes are `UPDATE`/`UPSERT` on
128- // ids no rival can collide *into*, and the mark's own UPSERT is on a
129- // deterministic id bijective with the `exam_result_exam_user_seq`
130- // unique tuple β€” `key::sitting(exam, user, seq)` *is* that tuple, so
131- // the index entry can only ever point at the row the id already names
132- // and the write resolves onto it. A lost round aborts having written
133- // nothing, counters included.
134- let _guard = cap::counter_lock().await;
135- let (mut written, mut errors) = transaction_with_retry(
136- db,
137- &format!(
138- "BEGIN TRANSACTION;
139- IF (SELECT VALUE id FROM ONLY $exam) IS NONE {{ THROW 'exam_missing' }};
140- IF (SELECT VALUE draft FROM ONLY $exam) {{ THROW 'exam_draft' }};
141- LET $before = (SELECT VALUE mark FROM ONLY $id);
142- IF $before = NONE {{
143- LET $kind = (UPSERT $kref SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + 1
144- WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id);
145- IF array::len($kind) = 0 {{ THROW '{RETIRED_MARK}' }};
146- UPDATE $exam SET {EXAM_RESULT_COUNT_FIELD} =
147- ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1;
148- UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =
149- ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1;
150- }};
151- LET $high = (IF $result.mark >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }})
152- - (IF ($before ?? -1) >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }});
153- IF $high != 0 {{
154- UPDATE $student SET {HIGH_MARK_TOTAL_FIELD} =
155- math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) + $high, 0])
156- }};
157- LET $after = (UPSERT $id CONTENT $result RETURN AFTER);
158- RETURN $after[0];
159- COMMIT TRANSACTION;"
160- ),
161- &[
162- ("exam".into(), exam.record().into_value()),
163- ("id".into(), result.id.record().into_value()),
164- ("kref".into(), kind_ref(kind).into_value()),
165- ("grader".into(), graded_by.record().into_value()),
166- ("student".into(), user.record().into_value()),
167- ("result".into(), result.into_value()),
168- ],
169- &["exam_missing", "exam_draft", RETIRED_MARK],
170- )
171- .await?;
172- // An aborted transaction errors every slot and only the THROW's own
173- // slot names the marker, so a refusal is read by marker while a lost
174- // round was already re-sent β€” never reported as a 500.
175- let thrown = |marker: &str| {
176- errors
177- .values()
178- .any(|error| error.to_string().contains(marker))
179- };
180- if thrown("exam_missing") {
181- return Err(AppError::NotFound);
182- }
183- if thrown("exam_draft") {
184- return Err(draft_error());
185- }
186- if thrown(RETIRED_MARK) {
187- return Err(retired_kind_error(kind));
188- }
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 instead of a hand-kept
194- // number β€” see `db::exam::delete` for the bug the hand-kept one caused.
195- // Probed on crate 3.2.3: an `IF { … }` block occupies exactly one slot
196- // however many statements it holds, and one whether or not it is taken.
197- let slot = written.num_statements().saturating_sub(2);
198- written
199- .take::<Vec<ExamResult>>(slot)?
200- .into_iter()
201- .next()
202- .ok_or_else(|| AppError::Internal("failed to record exam result".into()))
99+ // `$before` β€” the sitting's previous mark β€” answers both counter
100+ // questions off one read: `None` there means no row at all (the claim
101+ // branch), while a number is what the student's counter takes its
102+ // difference against. Read one statement before the counters inside
103+ // the same transaction: read anywhere else it would be a guess about a
104+ // row two graders may be writing at once, and the difference would be
105+ // taken against a mark some other round had already replaced. The exam
106+ // row's `FOR UPDATE` is what makes that read the write's own: a rival
107+ // grade holds the same lock across its whole transaction, so the two
108+ // serialize instead of interleaving their counter moves.
109+ tx_with_retry(db, false, async |conn| {
110+ let exam_row = sqlx::query!(
111+ r#"SELECT draft AS "draft: bool" FROM exam WHERE id = $1 FOR UPDATE"#,
112+ exam as &ExamId,
113+ )
114+ .fetch_optional(&mut *conn)
115+ .await?;
116+ let Some(exam_row) = exam_row else {
117+ return Err(AppError::NotFound);
118+ };
119+ if exam_row.draft {
120+ return Err(draft_error());
121+ }
122+ let before = sqlx::query!(
123+ r#"SELECT mark AS "mark: Mark" FROM exam_result
124+ WHERE exam = $1 AND app_user = $2 AND seq = $3"#,
125+ exam as &ExamId,
126+ user as &UserId,
127+ seq,
128+ )
129+ .fetch_optional(&mut *conn)
130+ .await?
131+ .map(|row| row.mark);
132+ if before.is_none() {
133+ // `kind_retired`: the mark's own transaction refusing a name
134+ // the school has retired. Zero rows β€” retired, or the ref row
135+ // gone with the kind β€” refuse the claim; a live row takes the
136+ // count.
137+ let claimed = sqlx::query!(
138+ r#"UPDATE kind_ref SET count = kind_ref.count + 1
139+ WHERE name = $1 AND retired = false
140+ RETURNING 1"#,
141+ kind,
142+ )
143+ .fetch_optional(&mut *conn)
144+ .await?;
145+ if claimed.is_none() {
146+ return Err(retired_kind_error(kind));
147+ }
148+ sqlx::query!(
149+ r#"UPDATE exam SET result_count = exam.result_count + 1 WHERE id = $1"#,
150+ exam as &ExamId,
151+ )
152+ .execute(&mut *conn)
153+ .await?;
154+ sqlx::query!(
155+ r#"UPDATE app_user SET marks_given_total = app_user.marks_given_total + 1
156+ WHERE id = $1"#,
157+ graded_by as &UserId,
158+ )
159+ .execute(&mut *conn)
160+ .await?;
161+ }
162+ let stored = before.map_or(-1, |mark| mark.as_i64());
163+ let high = i64::from(mark.as_i64() >= HIGH_MARK_MIN) - i64::from(stored >= HIGH_MARK_MIN);
164+ if high != 0 {
165+ sqlx::query!(
166+ r#"UPDATE app_user SET high_mark_total =
167+ GREATEST(high_mark_total + $2, 0)
168+ WHERE id = $1"#,
169+ user as &UserId,
170+ high,
171+ )
172+ .execute(&mut *conn)
173+ .await?;
174+ }
175+ let written = sqlx::query_as!(
176+ ExamResult,
177+ r#"INSERT INTO exam_result (exam, app_user, seq, mark, graded_by)
178+ VALUES ($1, $2, $3, $4, $5)
179+ ON CONFLICT (exam, app_user, seq) DO UPDATE
180+ SET mark = EXCLUDED.mark, graded_by = EXCLUDED.graded_by
181+ RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq,
182+ mark AS "mark: Mark", graded_by AS "graded_by: UserId""#,
183+ exam as &ExamId,
184+ user as &UserId,
185+ seq,
186+ mark,
187+ graded_by as &UserId,
188+ )
189+ .fetch_one(&mut *conn)
190+ .await?;
191+ Ok(written)
192+ })
193+ .await
203194 }
204195
205196 /// The user's graded results restricted to one course's exams β€” the raw
@@ -209,26 +200,33 @@ pub async fn list_for_user_in_course(
209200 course: &CourseId,
210201 user: &UserId,
211202 ) -> Result<Vec<ExamResult>, AppError> {
212- let mut result = db
213- .query(
214- "SELECT * FROM exam_result WHERE user = $usr
215- AND exam IN (SELECT VALUE id FROM exam WHERE course = $course)
216- ORDER BY id DESC",
217- )
218- .bind(("usr", user.record()))
219- .bind(("course", course.record()))
220- .await?
221- .check()?;
222- Ok(latest_per_pair(result.take::<Vec<ExamResult>>(0)?))
203+ let rows = sqlx::query_as!(
204+ ExamResult,
205+ r#"SELECT r.exam AS "exam: ExamId", r.app_user AS "user: UserId", r.seq,
206+ r.mark AS "mark: Mark", r.graded_by AS "graded_by: UserId"
207+ FROM exam_result r JOIN exam e ON e.id = r.exam
208+ WHERE r.app_user = $1 AND e.course = $2
209+ ORDER BY r.exam DESC, r.seq DESC"#,
210+ user as &UserId,
211+ course as &CourseId,
212+ )
213+ .fetch_all(db)
214+ .await?;
215+ Ok(latest_per_pair(rows))
223216 }
224217
225218 pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamResult>, AppError> {
226- let mut result = db
227- .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC")
228- .bind(("ex", exam.record()))
229- .await?
230- .check()?;
231- Ok(latest_per_pair(result.take::<Vec<ExamResult>>(0)?))
219+ let rows = sqlx::query_as!(
220+ ExamResult,
221+ r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
222+ mark AS "mark: Mark", graded_by AS "graded_by: UserId"
223+ FROM exam_result WHERE exam = $1
224+ ORDER BY exam DESC, seq DESC"#,
225+ exam as &ExamId,
226+ )
227+ .fetch_all(db)
228+ .await?;
229+ Ok(latest_per_pair(rows))
232230 }
233231
234232 /// Every sitting's mark for one (exam, user) pair, oldest first β€” the
@@ -238,16 +236,17 @@ pub async fn list_all_for_exam_user(
238236 exam: &ExamId,
239237 user: &UserId,
240238 ) -> Result<Vec<ExamResult>, AppError> {
241- let mut result = db
242- .query(
243- "SELECT * FROM exam_result WHERE exam = $ex AND user = $usr
244- ORDER BY seq ASC",
245- )
246- .bind(("ex", exam.record()))
247- .bind(("usr", user.record()))
248- .await?
249- .check()?;
250- Ok(result.take::<Vec<ExamResult>>(0)?)
239+ Ok(sqlx::query_as!(
240+ ExamResult,
241+ r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
242+ mark AS "mark: Mark", graded_by AS "graded_by: UserId"
243+ FROM exam_result WHERE exam = $1 AND app_user = $2
244+ ORDER BY seq ASC"#,
245+ exam as &ExamId,
246+ user as &UserId,
247+ )
248+ .fetch_all(db)
249+ .await?)
251250 }
252251
253252 /// A single user's result for an exam, if graded.
@@ -272,7 +271,7 @@ pub async fn read_for_user(
272271 /// actually deleted: `marks_given_total` to each row's *own* grader (two
273272 /// teachers can hold two sittings of the same pair), and `high_mark_total`
274273 /// once per removed row that cleared [`HIGH_MARK_MIN`], read off the
275-/// `BEFORE` image rather than re-derived. That last one is why
274+/// deleted image rather than re-derived. That last one is why
276275 /// [`grade`] has to move the student's counter on a *regrade*
277276 /// too: this end reads the stored mark, so the other end must be decided by
278277 /// the stored mark as well, or a mark walked across the line between the
@@ -289,57 +288,92 @@ pub async fn remove(
289288 // release them a second time, and on a kind another exam still grades
290289 // under, one release too many reads as one mark too few β€” a kind
291290 // wrongly free to leave the settings.
292- //
293- // Re-sent while the store answers "conflict, retry": the counters this
294- // touches are the ones a concurrent grade claims, so a lost round is
295- // routine and aborts having written nothing. `check()` cannot be used
296- // to read the outcome β€” it takes the *lowest*-slot error, and an
297- // aborted transaction's generic "not executed" sibling masked the real
298- // conflict, the exact defect deleted from `db::exam::delete`. No THROW
299- // of its own, and only `DELETE`/`UPDATE` inside, so nothing here can
300- // answer "already exists" and make a retry unsound.
301- let (mut result, mut errors) = transaction_with_retry(
302- db,
303- &format!(
304- "BEGIN TRANSACTION;
305- LET $gone = (DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE);
306- IF array::len($gone) > 0 {{
307- UPDATE type::record('kind_ref', $kind) SET {REF_COUNT_FIELD} =
308- math::max([({REF_COUNT_FIELD} ?? 0) - array::len($gone), 0]);
309- UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} =
310- math::max([({EXAM_RESULT_COUNT_FIELD} ?? 0) - array::len($gone), 0]);
311- LET $high = array::len($gone[WHERE mark >= {HIGH_MARK_MIN}]);
312- IF $high > 0 {{
313- UPDATE $usr SET {HIGH_MARK_TOTAL_FIELD} =
314- math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) - $high, 0])
315- }};
316- FOR $row IN $gone {{
317- LET $grader = $row.graded_by;
318- UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =
319- math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0])
320- }};
321- }};
322- RETURN $gone;
323- COMMIT TRANSACTION;"
324- ),
325- &[
326- ("ex".into(), exam.record().into_value()),
327- ("usr".into(), user.record().into_value()),
328- ("kind".into(), kind.to_string().into_value()),
329- ],
330- &[],
331- )
332- .await?;
333- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
334- return Err(error.into());
335- }
336- // `RETURN` is the last statement before `COMMIT`; its slot follows the
337- // statement count, as in `db::exam::delete`.
338- let slot = result.num_statements().saturating_sub(2);
339- let removed = result.take::<Vec<ExamResult>>(slot)?;
340- Ok(removed.into_iter().next())
291+ tx_with_retry(db, false, async |conn| {
292+ // The `gone` CTE deletes and reports in one statement: the counters
293+ // below move by exactly what this delete removed, so a concurrent
294+ // grade's rows (it holds the exam row's lock, and this statement's
295+ // sibling below takes the same lock before touching `result_count`)
296+ // can never be half-counted.
297+ let gone = sqlx::query!(
298+ r#"WITH gone AS (
299+ DELETE FROM exam_result
300+ WHERE exam = $1 AND app_user = $2
301+ RETURNING mark AS "mark: Mark", graded_by AS "graded_by: UserId", seq)
302+ SELECT seq, mark AS "mark: Mark", graded_by AS "graded_by: UserId"
303+ FROM gone ORDER BY seq ASC"#,
304+ exam as &ExamId,
305+ user as &UserId,
306+ )
307+ .fetch_all(&mut *conn)
308+ .await?;
309+ if gone.is_empty() {
310+ return Ok(None);
311+ }
312+ sqlx::query!(
313+ r#"UPDATE kind_ref SET count = GREATEST(kind_ref.count - $2, 0)
314+ WHERE name = $1"#,
315+ kind,
316+ gone.len() as i64,
317+ )
318+ .execute(&mut *conn)
319+ .await?;
320+ sqlx::query!(
321+ r#"UPDATE exam SET result_count = GREATEST(exam.result_count - $2, 0)
322+ WHERE id = $1"#,
323+ exam as &ExamId,
324+ gone.len() as i64,
325+ )
326+ .execute(&mut *conn)
327+ .await?;
328+ let high = gone.iter().filter(|row| row.mark.as_i64() >= HIGH_MARK_MIN).count() as i64;
329+ if high > 0 {
330+ sqlx::query!(
331+ r#"UPDATE app_user SET high_mark_total =
332+ GREATEST(high_mark_total - $2, 0)
333+ WHERE id = $1"#,
334+ user as &UserId,
335+ high,
336+ )
337+ .execute(&mut *conn)
338+ .await?;
339+ }
340+ // One give-back per distinct grader: two teachers can hold two
341+ // sittings of the same pair.
342+ let mut per_grader: Vec<(UserId, i64)> = Vec::new();
343+ for row in &gone {
344+ if let Some((_, n)) =
345+ per_grader.iter_mut().find(|(grader, _)| grader == &row.graded_by)
346+ {
347+ *n += 1;
348+ } else {
349+ per_grader.push((row.graded_by.clone(), 1));
350+ }
351+ }
352+ for (grader, n) in &per_grader {
353+ sqlx::query!(
354+ r#"UPDATE app_user SET marks_given_total =
355+ GREATEST(marks_given_total - $2, 0)
356+ WHERE id = $1"#,
357+ grader as &UserId,
358+ n,
359+ )
360+ .execute(&mut *conn)
361+ .await?;
362+ }
363+ // The first sitting's row comes back β€” the same shape the old
364+ // `RETURN` handed over, whose caller only asks whether anything was
365+ // removed and what the latest standing was.
366+ let first = gone.into_iter().next().map(|row| ExamResult {
367+ exam: exam.clone(),
368+ user: user.clone(),
369+ seq: row.seq,
370+ mark: row.mark,
371+ graded_by: row.graded_by,
372+ });
373+ Ok(first)
374+ })
375+ .await
341376 }
342-
343377 #[cfg(test)]
344378 mod tests {
345379 use super::*;
src/db/question_image.rsmodified+135 -94
@@ -4,66 +4,84 @@
44 //! constructor β€” lives in [`crate::domain::question_image`]; the blob bytes
55 //! stay the web layer's.
66
7-use surrealdb::types::SurrealValue;
7+use sqlx::PgConnection;
88
9-use crate::database::Database;
9+use crate::database::{Database, tx_with_retry};
10+use crate::db::exam_attempt::freeze_gate;
1011 use crate::domain::course::CourseId;
1112 use crate::domain::exam::ExamId;
1213 use crate::domain::exam_question::{ChoiceId, ExamQuestionId};
13-use crate::domain::question_image::{QuestionImage, QuestionImageId};
14+use crate::domain::question_image::QuestionImage;
1415 use crate::error::AppError;
1516
16-/// What one [`upsert`] transaction returns: the row it stored
17-/// and the blob name it replaced. Both are arrays because SurrealDB drops an object
18-/// key valued `NONE` on the way out, while an empty array survives β€” "nothing
19-/// was replaced" has to be readable, not missing.
20-#[derive(SurrealValue)]
21-struct UpsertOutcome {
22- stored: Vec<QuestionImage>,
23- replaced: Vec<String>,
24-}
25-
26-/// Create or replace the slot's image row β€” the deterministic id makes
27-/// this the whole "one image per slot" story β€” handing back what it stored
28-/// plus the blob name it replaced, for the caller to take off disk. Refused
29-/// once the exam has an attempt: pictures are part of the question, so they
30-/// freeze with it, and the gate is in this transaction rather than in a lock
31-/// the caller held.
17+/// Create or replace the slot's image row β€” the `UNIQUE NULLS NOT DISTINCT`
18+/// (question, slot) constraint makes this the whole "one image per slot"
19+/// story β€” handing back what it stored plus the blob name it replaced, for
20+/// the caller to take off disk. Refused once the exam has an attempt:
21+/// pictures are part of the question, so they freeze with it, and the gate
22+/// is in this transaction rather than in a lock the caller held.
3223 ///
33-/// The replaced name is read *here*, not by the caller before it: two
34-/// uploads to one slot both write this row, so they contend and the loser
35-/// re-reads the winner's blob name, where two pre-reads both saw the *old*
36-/// blob and left the loser's fresh one orphaned on disk.
24+/// The replaced name is read *inside the same transaction*, not by the
25+/// caller before it: two uploads to one slot both write this row, so they
26+/// contend on it and the loser re-reads the winner's blob name, where two
27+/// pre-reads both saw the *old* blob and left the loser's fresh one
28+/// orphaned on disk.
3729 pub async fn upsert(
3830 db: &Database,
3931 image: QuestionImage,
4032 ) -> Result<(QuestionImage, Option<String>), AppError> {
41- // whole-row-save-ok: image is built in place, never read back, and the slot id is deterministic
42- let (exam, id) = (image.exam.clone(), image.id.record());
43- let mut result = crate::db::exam_attempt::write_unfrozen(
44- db,
45- &exam,
46- "LET $replaced = (SELECT VALUE file FROM $id);
47- LET $stored = (UPSERT $id CONTENT $image);
48- RETURN { stored: $stored, replaced: $replaced };",
49- vec![
50- ("id".into(), id.into_value()),
51- ("image".into(), image.into_value()),
52- ],
33+ tx_with_retry(db, false, async |conn| {
34+ upsert_in(conn, image).await
35+ })
36+ .await
37+}
38+
39+/// The gated read-and-replace, on one connection.
40+pub(crate) async fn upsert_in(
41+ conn: &mut PgConnection,
42+ image: QuestionImage,
43+) -> Result<(QuestionImage, Option<String>), AppError> {
44+ freeze_gate(conn, &image.exam).await?;
45+ let replaced = replaced_file(conn, &image.question, image.slot.as_ref()).await?;
46+ let stored = sqlx::query_as!(
47+ QuestionImage,
48+ r#"INSERT INTO question_image (exam, question, slot, file, content_type, size)
49+ VALUES ($1, $2, $3, $4, $5, $6)
50+ ON CONFLICT (question, slot) DO UPDATE
51+ SET file = EXCLUDED.file, content_type = EXCLUDED.content_type,
52+ size = EXCLUDED.size
53+ RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId",
54+ slot AS "slot: Option<ChoiceId>", file,
55+ content_type AS "content_type: FileContentType", size"#,
56+ image.exam as &ExamId,
57+ image.question as &ExamQuestionId,
58+ image.slot,
59+ image.file,
60+ image.content_type,
61+ image.size,
62+ )
63+ .fetch_one(&mut *conn)
64+ .await?;
65+ Ok((stored, replaced))
66+}
67+
68+/// The blob name a slot's row currently names β€” the file a replace takes
69+/// off disk. `IS NOT DISTINCT FROM` is what makes the illustration slot's
70+/// `NULL` match itself.
71+pub(crate) async fn replaced_file(
72+ conn: &mut PgConnection,
73+ question: &ExamQuestionId,
74+ slot: Option<&ChoiceId>,
75+) -> Result<Option<String>, AppError> {
76+ let row = sqlx::query!(
77+ r#"SELECT file FROM question_image
78+ WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#,
79+ question as &ExamQuestionId,
80+ slot.map(ChoiceId::clone),
5381 )
82+ .fetch_optional(conn)
5483 .await?;
55- // The trailing `RETURN` is the last statement before `COMMIT`, so its
56- // slot follows the statement count rather than a hand-kept number;
57- // `num_statements` counts BEGIN and COMMIT.
58- let slot = result.num_statements().saturating_sub(2);
59- let failed = || AppError::Internal("failed to store question image".into());
60- let outcome = result
61- .take::<Vec<UpsertOutcome>>(slot)?
62- .into_iter()
63- .next()
64- .ok_or_else(failed)?;
65- let stored = outcome.stored.into_iter().next().ok_or_else(failed)?;
66- Ok((stored, outcome.replaced.into_iter().next()))
84+ Ok(row.map(|row| row.file))
6785 }
6886
6987 pub async fn read_slot(
@@ -71,31 +89,48 @@ pub async fn read_slot(
7189 question: &ExamQuestionId,
7290 slot: Option<&ChoiceId>,
7391 ) -> Result<Option<QuestionImage>, AppError> {
74- Ok(db
75- .select(QuestionImageId::for_slot(question, slot).record())
76- .await?)
92+ Ok(sqlx::query_as!(
93+ QuestionImage,
94+ r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
95+ slot AS "slot: Option<ChoiceId>", file,
96+ content_type AS "content_type: FileContentType", size
97+ FROM question_image
98+ WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#,
99+ question as &ExamQuestionId,
100+ slot.map(ChoiceId::clone),
101+ )
102+ .fetch_optional(db)
103+ .await?)
77104 }
78105
79106 /// Every image of the exam's questions β€” one query for the list views.
80107 pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<QuestionImage>, AppError> {
81- let mut result = db
82- .query("SELECT * FROM question_image WHERE exam = $ex")
83- .bind(("ex", exam.record()))
84- .await?
85- .check()?;
86- Ok(result.take::<Vec<QuestionImage>>(0)?)
108+ Ok(sqlx::query_as!(
109+ QuestionImage,
110+ r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
111+ slot AS "slot: Option<ChoiceId>", file,
112+ content_type AS "content_type: FileContentType", size
113+ FROM question_image WHERE exam = $1"#,
114+ exam as &ExamId,
115+ )
116+ .fetch_all(db)
117+ .await?)
87118 }
88119
89120 pub async fn list_for_question(
90121 db: &Database,
91122 question: &ExamQuestionId,
92123 ) -> Result<Vec<QuestionImage>, AppError> {
93- let mut result = db
94- .query("SELECT * FROM question_image WHERE question = $q")
95- .bind(("q", question.record()))
96- .await?
97- .check()?;
98- Ok(result.take::<Vec<QuestionImage>>(0)?)
124+ Ok(sqlx::query_as!(
125+ QuestionImage,
126+ r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId",
127+ slot AS "slot: Option<ChoiceId>", file,
128+ content_type AS "content_type: FileContentType", size
129+ FROM question_image WHERE question = $1"#,
130+ question as &ExamQuestionId,
131+ )
132+ .fetch_all(db)
133+ .await?)
99134 }
100135
101136 /// Drop the option pictures whose choice is gone β€” every choice image of
@@ -112,17 +147,19 @@ pub async fn delete_choices_not_in(
112147 question: &ExamQuestionId,
113148 keep: &[ChoiceId],
114149 ) -> Result<Vec<QuestionImage>, AppError> {
115- let keep: Vec<String> = keep.iter().map(|id| id.as_str().to_string()).collect();
116- let mut result = db
117- .query(
118- "DELETE question_image \
119- WHERE question = $q AND slot != NONE AND slot NOT IN $keep RETURN BEFORE",
120- )
121- .bind(("q", question.record()))
122- .bind(("keep", keep))
123- .await?
124- .check()?;
125- Ok(result.take::<Vec<QuestionImage>>(0)?)
150+ let keep = keep.iter().map(ChoiceId::as_str).collect::<Vec<_>>();
151+ Ok(sqlx::query_as!(
152+ QuestionImage,
153+ r#"DELETE FROM question_image
154+ WHERE question = $1 AND slot IS NOT NULL AND NOT (slot = ANY($2))
155+ RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId",
156+ slot AS "slot: Option<ChoiceId>", file,
157+ content_type AS "content_type: FileContentType", size"#,
158+ question as &ExamQuestionId,
159+ keep,
160+ )
161+ .fetch_all(db)
162+ .await?)
126163 }
127164
128165 /// The blob names behind every image of every exam of `course` β€” collected
@@ -131,32 +168,36 @@ pub async fn file_keys_for_course(
131168 db: &Database,
132169 course: &CourseId,
133170 ) -> Result<Vec<String>, AppError> {
134- let mut result = db
135- .query(
136- "SELECT VALUE file FROM question_image \
137- WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)",
138- )
139- .bind(("course", course.record()))
140- .await?
141- .check()?;
142- Ok(result.take::<Vec<String>>(0)?)
171+ let rows = sqlx::query!(
172+ r#"SELECT qi.file FROM question_image qi
173+ JOIN exam e ON e.id = qi.exam WHERE e.course = $1"#,
174+ course as &CourseId,
175+ )
176+ .fetch_all(db)
177+ .await?;
178+ Ok(rows.into_iter().map(|row| row.file).collect())
143179 }
144180
145181 /// Refused once the exam has an attempt, in the same transaction β€” same
146182 /// gate, same reason as [`upsert`].
147183 pub async fn delete(db: &Database, image: QuestionImage) -> Result<QuestionImage, AppError> {
148- let mut result = crate::db::exam_attempt::write_unfrozen(
149- db,
150- &image.exam,
151- "DELETE $id RETURN BEFORE;",
152- vec![("id".into(), image.id.record().into_value())],
153- )
154- .await?;
155- result
156- .take::<Vec<QuestionImage>>(crate::db::exam_attempt::FROZEN_SLOT)?
157- .into_iter()
158- .next()
159- .ok_or(AppError::NotFound)
184+ tx_with_retry(db, false, async |conn| {
185+ freeze_gate(conn, &image.exam).await?;
186+ let deleted = sqlx::query_as!(
187+ QuestionImage,
188+ r#"DELETE FROM question_image
189+ WHERE question = $1 AND slot IS NOT DISTINCT FROM $2
190+ RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId",
191+ slot AS "slot: Option<ChoiceId>", file,
192+ content_type AS "content_type: FileContentType", size"#,
193+ image.question as &ExamQuestionId,
194+ image.slot,
195+ )
196+ .fetch_optional(&mut *conn)
197+ .await?;
198+ deleted.ok_or(AppError::NotFound)
199+ })
200+ .await
160201 }
161202
162203 #[cfg(test)]