forge
Explore
Log in

Don't you dare go Hollow

Port courses, subjects, terms, enrollments, sessions, attendance to sqlx/Postgres

Browse files at this commit

f734c6af9370891e50e37ce21879b52669005e09Ahmet Kaan GümüşParent: dd0e1d8
  • feat
    • port courses, subjects, terms, enrollments, sessions, attendance to sqlx/Postgres
Show full message
🗃️ feat!: port courses, subjects, terms, enrollments, sessions, attendance to sqlx/Postgres
src/db/course.rsmodified+369 -209
@@ -1,11 +1,9 @@
11 //! The `course` table: the unit exams, sessions, subjects and enrollments
22 //! hang off. Listed newest first; deleted with its whole subtree in one
3-use surrealdb::types::{RecordId, SurrealValue};
3+//! guarded cascade.
44
5-use crate::constant::{
6- CLASS_COURSE_COUNT_FIELD, COURSE_COUNT_FIELD, ENROLLMENT_COUNT_FIELD, REF_COUNT_FIELD,
7-};
8-use crate::database::{Database, transaction_with_retry};
5+use crate::constant::COURSE_TABLE;
6+use crate::database::{Database, tx_with_retry, unique_violation};
97 use crate::db::cap;
108 use crate::db::field_update::FieldUpdate;
119 use crate::db::page::PagedList;
@@ -14,16 +12,6 @@ use crate::domain::term::{self, TermId};
1412 use crate::domain::user::UserId;
1513 use crate::error::AppError;
1614
17-/// The `THROW` marker the delete guard aborts with — a roster that is not
18-/// empty, or a course row that is no longer there.
19-const ROSTER_MARK: &str = "course_roster";
20-
21-/// Create the course, claiming a reference on the term it links (if any) in
22-/// the *same transaction* as the row: the claim is a conditional write on
23-/// the term row, so it fails when the term is already gone and it makes the
24-/// term undeletable the instant this link exists — and a crash can never
25-/// leave one without the other, which a claim sent as its own query could
26-/// (the count would strand and the term be undeletable forever).
2715 pub async fn create(
2816 db: &Database,
2917 creator: &UserId,
@@ -33,50 +21,87 @@ pub async fn create(
3321 term: Option<TermId>,
3422 capacity: Option<i64>,
3523 ) -> Result<Course, AppError> {
36- let course = Course {
37- id: CourseId::generate(),
38- creator: creator.clone(),
39- teachers: Vec::new(),
40- term,
41- capacity,
24+ let id = CourseId::generate();
25+ let Some(term) = term else {
26+ let created = sqlx::query_as!(
27+ Course,
28+ r#"INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity)
29+ VALUES ($1, $2, $3, $4, $5, $6, NULL, $7)
30+ RETURNING id, creator, teachers, title, description, kind, term, capacity"#,
31+ id,
32+ creator,
33+ Vec::<UserId>::new(),
34+ title,
35+ description,
36+ kind,
37+ capacity,
38+ )
39+ .fetch_one(db)
40+ .await?;
41+ return Ok(created);
42+ };
43+ // Claim a reference on the term in the *same statement* as the row: the
44+ // claim is a conditional write on the term row, so it fails when the
45+ // term is already gone and it makes the term undeletable the instant
46+ // this link exists — and a crash can never leave one without the other,
47+ // which a claim sent as its own query could (the count would strand and
48+ // the term be undeletable forever).
49+ let created = sqlx::query_as!(
50+ Course,
51+ r#"WITH seat AS (
52+ UPDATE term
53+ SET course_count = course_count + 1
54+ WHERE id = $8 AND course_count < $9
55+ RETURNING 1)
56+ INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity)
57+ SELECT $1, $2, $3, $4, $5, $6, $8, $7 WHERE EXISTS (SELECT 1 FROM seat)
58+ RETURNING id, creator, teachers, title, description, kind, term, capacity"#,
59+ id,
60+ creator,
61+ Vec::<UserId>::new(),
4262 title,
4363 description,
4464 kind,
45- };
46- let id = course.id.record();
47- let Some(term) = course.term.clone() else {
48- let created: Option<Course> = db.create(id).content(course).await?;
49- return created.ok_or_else(|| AppError::Internal("failed to create course".into()));
50- };
51- match cap::claim_and_create(
52- &term.record(),
53- COURSE_COUNT_FIELD,
65+ capacity,
66+ term,
5467 cap::UNLIMITED,
55- &id,
56- &course,
57- db,
5868 )
59- .await?
60- {
61- cap::Claimed::Made(created) => Ok(created),
69+ .fetch_one(db)
70+ .await;
71+ match created {
72+ Ok(created) => Ok(created),
6273 // Uncapped, so "full" can only mean the conditional write matched no
6374 // term row at all — the existence check the pre-flight lookup makes.
64- cap::Claimed::Full => Err(term::gone_error()),
65- // Unreachable: the id is a ULID this call just generated.
66- cap::Claimed::Duplicate => Err(AppError::Internal("failed to create course".into())),
75+ Err(sqlx::Error::RowNotFound) => Err(term::gone_error()),
76+ // Unreachable: the id was minted above.
77+ Err(err) if unique_violation(&err).is_some() => {
78+ Err(AppError::Internal("failed to create course".into()))
79+ }
80+ Err(err) => Err(err.into()),
6781 }
6882 }
6983
7084 pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> {
71- Ok(db.select(id.record()).await?)
85+ let course = sqlx::query_as!(
86+ Course,
87+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
88+ FROM course WHERE id = $1"#,
89+ id,
90+ )
91+ .fetch_optional(db)
92+ .await?;
93+ Ok(course)
7294 }
7395
7496 pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> {
75- let mut result = db
76- .query("SELECT * FROM course ORDER BY id DESC")
77- .await?
78- .check()?;
79- Ok(result.take::<Vec<Course>>(0)?)
97+ let rows = sqlx::query_as!(
98+ Course,
99+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
100+ FROM course ORDER BY id DESC"#,
101+ )
102+ .fetch_all(db)
103+ .await?;
104+ Ok(rows)
80105 }
81106
82107 /// The courses `user` is enrolled in — the spine of `/courses/me` and the
@@ -88,36 +113,38 @@ pub async fn list_enrolled(
88113 offset: i64,
89114 ) -> Result<(Vec<Course>, i64), AppError> {
90115 PagedList::new(
91- "course WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr)",
116+ "course WHERE id IN (SELECT course FROM enrollment WHERE app_user = $1)",
92117 "ORDER BY id DESC",
93118 )
94- .bind("usr", user.record())
95- .run(limit, offset, db)
119+ .bind(user.uuid())
120+ .run::<Course>(limit, offset, db)
96121 .await
97122 }
98123
99124 /// The courses `user` runs — the ones they created plus the ones a manager
100125 /// assigned them to. A teacher's slice of the catalog.
101126 ///
102-/// corner-cut: unpaged full table scan, and it stays one — every profile read
103-/// of a teacher pays it, so the ceiling is the course table's size. It
104-/// cannot be indexed away on SurrealDB 3.2.3: an index on `creator` alone
105-/// leaves the `OR` a `TableScan` (EXPLAIN), and the per-element index the
106-/// membership half would need (`DEFINE INDEX ... FIELDS teachers[*]`) is
107-/// *wrong*, not merely useless — with it, `$usr IN teachers` and
108-/// `teachers CONTAINS $usr` return **no rows at all**, which is what the
109-/// integration test `assigned_teacher_manages_course_without_owning_it`
110-/// catches. A plain `FIELDS teachers` index is correct but unused. The
111-/// upgrade path is structural: a `course_teacher` link table indexed on
112-/// `user`, the shape `enrollment` already has, turning this into two
113-/// index-backed reads.
127+/// corner-cut: unpaged full table scan, and it stays one — every profile
128+/// read of a teacher pays it, so the ceiling is the course table's size.
129+/// Under Postgres the `OR` halves could each use an index on `creator` /
130+/// `teachers` (a GIN), but the old per-element index the membership half
131+/// would have needed was *wrong*, not merely useless — `$usr IN teachers`
132+/// returned **no rows at all** with it, which is what the integration test
133+/// `assigned_teacher_manages_course_without_owning_it` catches. The upgrade
134+/// path is structural: a `course_teacher` link table indexed on `user`, the
135+/// shape `enrollment` already has, turning this into two index-backed
136+/// reads. No schema carries it yet, so the scan stays.
114137 pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> {
115- let mut result = db
116- .query("SELECT * FROM course WHERE creator = $usr OR $usr IN teachers ORDER BY id DESC")
117- .bind(("usr", user.record()))
118- .await?
119- .check()?;
120- Ok(result.take::<Vec<Course>>(0)?)
138+ let rows = sqlx::query_as!(
139+ Course,
140+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
141+ FROM course WHERE creator = $1 OR $2 = ANY(teachers) ORDER BY id DESC"#,
142+ user,
143+ user,
144+ )
145+ .fetch_all(db)
146+ .await?;
147+ Ok(rows)
121148 }
122149
123150 /// Load every course behind `ids` (one query) — the join half of the
@@ -126,13 +153,16 @@ pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result<Vec<Course>,
126153 if ids.is_empty() {
127154 return Ok(Vec::new());
128155 }
129- let records: Vec<RecordId> = ids.iter().map(CourseId::record).collect();
130- let mut result = db
131- .query("SELECT * FROM course WHERE id IN $ids")
132- .bind(("ids", records))
133- .await?
134- .check()?;
135- Ok(result.take::<Vec<Course>>(0)?)
156+ let keys: Vec<CourseId> = ids.to_vec();
157+ let rows = sqlx::query_as!(
158+ Course,
159+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
160+ FROM course WHERE id = ANY($1)"#,
161+ keys,
162+ )
163+ .fetch_all(db)
164+ .await?;
165+ Ok(rows)
136166 }
137167
138168 /// Request-scoped: `teachers` is written by [`assign_teacher`],
@@ -160,19 +190,25 @@ pub async fn update(
160190 // without its count. A PATCH that carried no `term_id`, or re-stated the
161191 // link it already had, moves neither counter.
162192 let (claim, release) = term::ref_move(course.term.as_ref(), &term);
163- let expected = course.term.as_ref().map(TermId::record);
164- FieldUpdate::new(course.id.record())
165- .set("title", title)
166- .set("description", description)
167- .set("kind", kind)
168- .set("term", term.map(|term| term.map(|term| term.record())))
169- .set("capacity", capacity)
193+ FieldUpdate::new(COURSE_TABLE, course.id.uuid())
194+ .set("title", title.map(|title| title.as_str().to_owned()))
195+ .set(
196+ "description",
197+ description.map(|description| description.as_str().to_owned()),
198+ )
199+ .set("kind", kind.map(|kind| kind.as_str().to_owned()))
200+ .set(
201+ "term",
202+ term.map(|term| crate::db::page::Param::OptUuid(term.map(|term| term.uuid()))),
203+ )
204+ .set("capacity", capacity.map(crate::db::page::Param::OptI64))
170205 .refcount(
171- COURSE_COUNT_FIELD,
172206 "term",
173- expected,
174- claim,
175- release,
207+ "course_count",
208+ "term",
209+ course.term.as_ref().map(|term| term.uuid()),
210+ claim.map(|term| term.uuid()),
211+ release.map(|term| term.uuid()),
176212 term::gone_error(),
177213 )
178214 .run::<Course>(db)
@@ -184,8 +220,9 @@ pub async fn update(
184220 /// Field-scoped, and the new list is folded server-side out of the *stored*
185221 /// one: a course PATCH awaits a term lookup between its read and its write,
186222 /// so a whole-row save from either side would revert the other. The
187-/// `array::distinct` keeps the assignment idempotent even when two requests
188-/// name the same teacher at once (the early return only sees a stale row).
223+/// `array_agg(DISTINCT …)` keeps the assignment idempotent even when two
224+/// requests name the same teacher at once (the early return only sees a
225+/// stale row).
189226 pub async fn assign_teacher(
190227 db: &Database,
191228 course: Course,
@@ -194,20 +231,19 @@ pub async fn assign_teacher(
194231 if course.is_assigned(teacher) {
195232 return Ok(course);
196233 }
197- let mut result = db
198- .query(
199- "UPDATE $id SET teachers = array::distinct(array::append(teachers, $usr))
200- RETURN AFTER",
201- )
202- .bind(("id", course.id.record()))
203- .bind(("usr", teacher.record()))
204- .await?
205- .check()?;
206- result
207- .take::<Vec<Course>>(0)?
208- .into_iter()
209- .next()
210- .ok_or(AppError::NotFound)
234+ let updated = sqlx::query_as!(
235+ Course,
236+ r#"UPDATE course
237+ SET teachers = (SELECT array_agg(DISTINCT x)
238+ FROM unnest(course.teachers || $2) AS x)
239+ WHERE id = $1
240+ RETURNING id, creator, teachers, title, description, kind, term, capacity"#,
241+ course.id,
242+ teacher,
243+ )
244+ .fetch_optional(db)
245+ .await?;
246+ updated.ok_or(AppError::NotFound)
211247 }
212248
213249 /// Drop `teacher` from this course. `None` when they weren't assigned, so
@@ -220,30 +256,32 @@ pub async fn unassign_teacher(
220256 if !course.is_assigned(teacher) {
221257 return Ok(None);
222258 }
223- // Same field-scoped story as [`assign_teacher`]; `-=` drops the
224- // one link off the stored list without touching the course's own text.
225- let mut result = db
226- .query("UPDATE $id SET teachers -= $usr RETURN AFTER")
227- .bind(("id", course.id.record()))
228- .bind(("usr", teacher.record()))
229- .await?
230- .check()?;
231- Ok(Some(
232- result
233- .take::<Vec<Course>>(0)?
234- .into_iter()
235- .next()
236- .ok_or(AppError::NotFound)?,
237- ))
259+ // Same field-scoped story as [`assign_teacher`]; `array_remove` drops
260+ // the one link off the stored list without touching the course's own
261+ // text.
262+ let updated = sqlx::query_as!(
263+ Course,
264+ r#"UPDATE course SET teachers = array_remove(teachers, $2)
265+ WHERE id = $1
266+ RETURNING id, creator, teachers, title, description, kind, term, capacity"#,
267+ course.id,
268+ teacher,
269+ )
270+ .fetch_optional(db)
271+ .await?;
272+ Ok(updated)
238273 }
239274
240275 /// Strip `user` from every course they were assigned to — the sweep for a
241276 /// user demoted below `teacher`, who may no longer run anything.
242277 pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {
243- db.query("UPDATE course SET teachers -= $usr WHERE $usr IN teachers")
244- .bind(("usr", user.record()))
245- .await?
246- .check()?;
278+ sqlx::query!(
279+ r#"UPDATE course SET teachers = array_remove(teachers, $1)
280+ WHERE $1 = ANY(teachers)"#,
281+ user,
282+ )
283+ .execute(db)
284+ .await?;
247285 Ok(())
248286 }
249287
@@ -261,111 +299,233 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App
261299 /// **Bank templates** survive it — they are a separate, reusable library
262300 /// spanning every course — so their `source_exam` and `subject` links are
263301 /// cleared instead, in this same transaction, exactly as
264-/// [`crate::db::exam::delete`] and
265-/// [`crate::db::subject::delete`] clear them one level down.
266-/// Deleting a course must leave the bank where deleting each of its exams
267-/// and subjects by hand would have left it, or a template is left pointing
268-/// at a dead exam (permanently: nothing else ever visits that column) and
269-/// at a dead subject the next `PATCH` omitting `subject_id` writes straight
270-/// back.
302+/// [`crate::db::exam::delete`] and [`crate::db::subject::delete`]
303+/// clear them one level down. Deleting a course must leave the bank where
304+/// deleting each of its exams and subjects by hand would have left it, or
305+/// a template is left pointing at a dead exam (permanently: nothing else
306+/// ever visits that column) and at a dead subject the next `PATCH`
307+/// omitting `subject_id` writes straight back.
271308 ///
272309 /// The **grade blueprints** naming it are swept in that same transaction.
273310 /// Nothing else can reach them — a blueprint holds its courses as a list on
274311 /// its own row, not as link rows this cascade could delete — and an id left
275312 /// behind is permanent rather than merely stale: the pump's own
276-/// [`crate::db::class_blueprint::prune`] fires only
277-/// while walking a section, so a grade with no sections can never drop one,
278-/// and every `PATCH` of that template is refused for naming a course that
279-/// does not exist, which is precisely the call documented as the repair.
313+/// [`crate::db::class_blueprint::prune`] fires only while walking a
314+/// section, so a grade with no sections can never drop one, and every
315+/// `PATCH` of that template is refused for naming a course that does not
316+/// exist, which is precisely the call documented as the repair. A dozen-row
317+/// table scanned unindexed, deliberately: a course delete is rare.
280318 ///
281-/// It is a table scan, deliberately unindexed: `class_blueprint` holds one
282-/// row per grade label the school uses (a dozen), a course delete is rare,
283-/// and the per-element index the `WHERE` would want
284-/// (`FIELDS courses[*]`) is the one this store answers with **no rows at
285-/// all** — the trap [`list_for_teacher`] documents.
319+/// The **derived AI rows** (`rag_output` carries a denormalized `course`
320+/// besides its note link) and the event **audience links** are FK children
321+/// the old store let dangle: `rag_output` is disposable and dies here, and
322+/// an event whose audience was "this course's students" keeps standing with
323+/// `audience_course` cleared — an empty roster, exactly the documented
324+/// outcome of the class twin (`Course::delete` never touched `event`; it
325+/// still doesn't delete one).
286326 ///
287327 /// The marks going with it give their exam kinds' references back, counted
288328 /// per kind inside this same transaction — the mirror of `Exam::delete`.
289329 /// Skipping it would leave every kind the course graded under counted
290330 /// forever, and a counted kind can never leave the school's settings.
291331 ///
332+/// **Order is the foreign-key graph, children first** (the old store had
333+/// no FKs, so its order was free): exam results/attempts/answers/images
334+/// and question images before `exam_question`; `exam_question` before
335+/// `exam`; homework files before submissions before results before
336+/// `homework`; roll-call rows before `course_session`; note files and
337+/// rag rows before `course_note`; every one of them before the `course`
338+/// row itself, whose `NO ACTION` FKs are checked the moment the final
339+/// `DELETE` runs.
340+///
292341 /// `false` = refused, nothing was written: someone is still enrolled. The
293-/// roster is read off the course's own `enrollment_count`, so the check and
294-/// the delete are one conditional write on one record — an enroll racing
295-/// this either takes its seat first (and the delete is refused) or finds
296-/// the row gone (and is refused itself). `Err(NotFound)`
297-/// keeps the answer a concurrent *delete* used to get.
342+/// guard locks the course row (`FOR UPDATE`) and reads its own
343+/// `enrollment_count`, so an enroll racing this either takes its seat
344+/// first (and the delete is refused) or finds the row gone (and is refused
345+/// itself). `Err(NotFound)` keeps the answer a concurrent *delete* used
346+/// to get — and unlike the old one-statement guard, this one tells the two
347+/// apart without a second read.
298348 pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
299- let sql = format!(
300- "BEGIN TRANSACTION;
301- LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);
302- IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }};
303- FOR $row IN $gone {{
304- IF $row.term != NONE {{
305- UPDATE $row.term SET {COURSE_COUNT_FIELD} = \
306- math::max([({COURSE_COUNT_FIELD} ?? 0) - 1, 0]);
307- }};
308- }};
309- FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result
310- WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)
311- GROUP BY kind) ?? []) {{
312- UPDATE type::record('kind_ref', $row.kind) SET {REF_COUNT_FIELD} = \
313- math::max([({REF_COUNT_FIELD} ?? 0) - $row.n, 0])
314- }};
315- DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
316- DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
317- DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
318- DELETE answer_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
319- DELETE question_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
320- DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
321- DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course));
322- DELETE homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course);
323- DELETE homework_result WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course);
324- DELETE course_note_file WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course);
325- DELETE course_note WHERE course = $course;
326- LET $detached = (DELETE class_course WHERE course = $course RETURN BEFORE);
327- FOR $row IN ($detached ?? []) {{
328- UPDATE $row.class SET {CLASS_COURSE_COUNT_FIELD} = \
329- math::max([({CLASS_COURSE_COUNT_FIELD} ?? 0) - 1, 0]);
330- }};
331- UPDATE class_blueprint SET courses -= $course WHERE $course IN courses;
332- DELETE session_attendance WHERE course = $course;
333- DELETE course_session WHERE course = $course;
334- DELETE enrollment WHERE course = $course;
335- UPDATE bank_question SET subject = NONE
336- WHERE subject IN (SELECT VALUE id FROM subject WHERE course = $course);
337- DELETE subject WHERE course = $course;
338- DELETE homework WHERE course = $course;
339- UPDATE bank_question SET source_exam = NONE
340- WHERE source_exam IN (SELECT VALUE id FROM exam WHERE course = $course);
341- DELETE exam WHERE course = $course;
342- COMMIT TRANSACTION;"
343- );
344- // An aborted transaction errors *every* slot, most with a generic "not
345- // executed" — only the THROW's own slot names the marker, and a lost
346- // round is re-sent rather than reported (see [`transaction_with_retry`]).
347- let (_, mut errors) = transaction_with_retry(
348- db,
349- &sql,
350- &[("course".into(), course.id.record().into_value())],
351- &[ROSTER_MARK],
352- )
353- .await?;
354- if errors
355- .values()
356- .any(|error| error.to_string().contains(ROSTER_MARK))
357- {
358- // Full stop or already gone: the guard cannot tell those apart, and
359- // only the refusal path pays for the extra read that can.
360- return match read(db, &course.id).await? {
361- Some(_) => Ok(false),
362- None => Err(AppError::NotFound),
349+ tx_with_retry(db, true, async |tx| {
350+ // The guard and the lock: the row (and its roster count) cannot
351+ // change under this transaction, and every enroll claim contends on
352+ // this very row, so check and cascade are one decision.
353+ let guard = sqlx::query!(
354+ r#"SELECT enrollment_count, term FROM course WHERE id = $1 FOR UPDATE"#,
355+ course.id,
356+ )
357+ .fetch_optional(&mut *tx)
358+ .await?;
359+ let Some(guard) = guard else {
360+ return Err(AppError::NotFound);
363361 };
364- }
365- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
366- return Err(error.into());
367- }
368- Ok(true)
362+ if guard.enrollment_count != 0 {
363+ return Ok(false);
364+ }
365+ // The exam ids are needed twice — the kind_ref refund and the bank's
366+ // source_exam clear — and must be collected before the sweeps take
367+ // the rows they name.
368+ let exams: Vec<uuid::Uuid> =
369+ sqlx::query!(r#"SELECT id FROM exam WHERE course = $1"#, course.id,)
370+ .fetch_all(&mut *tx)
371+ .await?
372+ .into_iter()
373+ .map(|row| row.id)
374+ .collect();
375+ // Every mark the course ever gave gives its exam kind's reference
376+ // back, counted per kind (mirrors `Exam::delete`). The kind rides
377+ // the exam row — `exam_result` names its exam, not its kind.
378+ sqlx::query!(
379+ r#"UPDATE kind_ref k
380+ SET count = GREATEST(k.count - s.n, 0)
381+ FROM (SELECT e.kind, count(*) AS n FROM exam_result r
382+ JOIN exam e ON r.exam = e.id
383+ WHERE r.exam = ANY($1) GROUP BY e.kind) s
384+ WHERE k.name = s.kind"#,
385+ exams,
386+ )
387+ .execute(&mut *tx)
388+ .await?;
389+ // The term gets its reference back inside the same transaction.
390+ if let Some(term) = guard.term {
391+ sqlx::query!(
392+ r#"UPDATE term SET course_count = GREATEST(course_count - 1, 0)
393+ WHERE id = $1"#,
394+ term,
395+ )
396+ .execute(&mut *tx)
397+ .await?;
398+ }
399+ // Events aimed at this course keep standing, audience cleared.
400+ sqlx::query!(
401+ r#"UPDATE event SET audience_course = NULL WHERE audience_course = $1"#,
402+ course.id,
403+ )
404+ .execute(&mut *tx)
405+ .await?;
406+ // The exam subtree, deepest children first.
407+ sqlx::query!(r#"DELETE FROM exam_result WHERE exam = ANY($1)"#, exams)
408+ .execute(&mut *tx)
409+ .await?;
410+ sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = ANY($1)"#, exams)
411+ .execute(&mut *tx)
412+ .await?;
413+ sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = ANY($1)"#, exams)
414+ .execute(&mut *tx)
415+ .await?;
416+ sqlx::query!(r#"DELETE FROM answer_image WHERE exam = ANY($1)"#, exams)
417+ .execute(&mut *tx)
418+ .await?;
419+ sqlx::query!(r#"DELETE FROM question_image WHERE exam = ANY($1)"#, exams)
420+ .execute(&mut *tx)
421+ .await?;
422+ sqlx::query!(r#"DELETE FROM exam_question WHERE exam = ANY($1)"#, exams)
423+ .execute(&mut *tx)
424+ .await?;
425+ // The homework subtree: files, then submissions (whose graded_by
426+ // link names a result deleted after them), then results.
427+ sqlx::query!(
428+ r#"DELETE FROM homework_file WHERE submission IN (
429+ SELECT id FROM homework_submission
430+ WHERE homework IN (SELECT id FROM homework WHERE course = $1))"#,
431+ course.id,
432+ )
433+ .execute(&mut *tx)
434+ .await?;
435+ sqlx::query!(
436+ r#"DELETE FROM homework_submission WHERE homework IN (
437+ SELECT id FROM homework WHERE course = $1)"#,
438+ course.id,
439+ )
440+ .execute(&mut *tx)
441+ .await?;
442+ sqlx::query!(
443+ r#"DELETE FROM homework_result WHERE homework IN (
444+ SELECT id FROM homework WHERE course = $1)"#,
445+ course.id,
446+ )
447+ .execute(&mut *tx)
448+ .await?;
449+ // Derived AI rows for this course's notes.
450+ sqlx::query!(r#"DELETE FROM rag_output WHERE course = $1"#, course.id)
451+ .execute(&mut *tx)
452+ .await?;
453+ // Notes: files before their notes.
454+ sqlx::query!(
455+ r#"DELETE FROM course_note_file WHERE course_note IN (
456+ SELECT id FROM course_note WHERE course = $1)"#,
457+ course.id,
458+ )
459+ .execute(&mut *tx)
460+ .await?;
461+ sqlx::query!(r#"DELETE FROM course_note WHERE course = $1"#, course.id)
462+ .execute(&mut *tx)
463+ .await?;
464+ // Class attachments: detach and hand each class its count back in
465+ // one statement, then strike the course out of every blueprint.
466+ sqlx::query!(
467+ r#"WITH detached AS (
468+ DELETE FROM class_course WHERE course = $1 RETURNING class)
469+ UPDATE class_group g
470+ SET class_course_count = GREATEST(g.class_course_count - 1, 0)
471+ FROM detached WHERE g.id = detached.class"#,
472+ course.id,
473+ )
474+ .execute(&mut *tx)
475+ .await?;
476+ sqlx::query!(
477+ r#"UPDATE class_blueprint SET courses = array_remove(courses, $1)
478+ WHERE $1 = ANY(courses)"#,
479+ course.id,
480+ )
481+ .execute(&mut *tx)
482+ .await?;
483+ // Sessions with their roll call, then the roster itself.
484+ sqlx::query!(
485+ r#"DELETE FROM session_attendance WHERE course = $1"#,
486+ course.id,
487+ )
488+ .execute(&mut *tx)
489+ .await?;
490+ sqlx::query!(r#"DELETE FROM course_session WHERE course = $1"#, course.id)
491+ .execute(&mut *tx)
492+ .await?;
493+ sqlx::query!(r#"DELETE FROM enrollment WHERE course = $1"#, course.id)
494+ .execute(&mut *tx)
495+ .await?;
496+ // The bank keeps its templates; their links to this course's
497+ // content go first, so the subject/exam deletes below cannot trip
498+ // a foreign key behind them.
499+ sqlx::query!(
500+ r#"UPDATE bank_question SET subject = NULL
501+ WHERE subject IN (SELECT id FROM subject WHERE course = $1)"#,
502+ course.id,
503+ )
504+ .execute(&mut *tx)
505+ .await?;
506+ sqlx::query!(
507+ r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = ANY($1)"#,
508+ exams,
509+ )
510+ .execute(&mut *tx)
511+ .await?;
512+ // Subjects before exams would trip `exam.subject` — exams go first.
513+ sqlx::query!(r#"DELETE FROM exam WHERE course = $1"#, course.id)
514+ .execute(&mut *tx)
515+ .await?;
516+ sqlx::query!(r#"DELETE FROM homework WHERE course = $1"#, course.id)
517+ .execute(&mut *tx)
518+ .await?;
519+ sqlx::query!(r#"DELETE FROM subject WHERE course = $1"#, course.id)
520+ .execute(&mut *tx)
521+ .await?;
522+ // Last: the course itself, now FK-silent.
523+ sqlx::query!(r#"DELETE FROM course WHERE id = $1"#, course.id)
524+ .execute(&mut *tx)
525+ .await?;
526+ Ok(true)
527+ })
528+ .await
369529 }
370530
371531 /// A real course row, for the tests of every child that must now prove its
src/db/course_session.rsmodified+77 -55
@@ -1,15 +1,11 @@
11 //! The `course_session` table: reads, a course's timetable listing, the
22 //! request-scoped field update, and the delete that sweeps roll-call rows in
3-//! one transaction. Creation writes the course row through
4-//! [`cap::touch_and_create`] so a lesson can never outlive its course; the
5-//! web-facing doors and the teacher-resolution rule live in
6-//! [`crate::service::course_session`].
3+//! one transaction. Creation stands on the course foreign key, so a lesson
4+//! can never outlive its course; the web-facing doors and the
5+//! teacher-resolution rule live in [`crate::service::course_session`].
76
8-use surrealdb::types::SurrealValue;
9-
10-use crate::constant::ENROLLMENT_COUNT_FIELD;
11-use crate::database::{Database, transaction_with_retry};
12-use crate::db::cap;
7+use crate::constant::COURSE_SESSION_TABLE;
8+use crate::database::{Database, foreign_key_violation, tx_with_retry};
139 use crate::db::field_update::FieldUpdate;
1410 use crate::db::page::PagedList;
1511 use crate::domain::course::CourseId;
@@ -34,23 +30,44 @@ pub async fn create(
3430 starts_at,
3531 ends_at,
3632 };
37- // The course row is *written* (bumped and put back), not read, so this
38- // collides with `Course::delete`'s cascade: a lesson that outlives its
39- // course 404s through `session_with_course` forever — unreadable,
40- // unpatchable, undeletable. See [`cap::touch_and_create`].
41- cap::touch_and_create(
42- &course.record(),
43- ENROLLMENT_COUNT_FIELD,
44- &session.id.record(),
45- &session,
46- db,
33+ // The course foreign key is the existence proof the old bump-and-restore
34+ // "touch" trick faked: a lesson whose course is already gone — or which
35+ // is deleted while this insert is in flight — is refused here, so a
36+ // lesson can never outlive its course and 404 through
37+ // `session_with_course` forever — unreadable, unpatchable, undeletable.
38+ // `23503` is the parent-gone refusal, the same answer the touch
39+ // produced.
40+ let created = sqlx::query_as!(
41+ CourseSession,
42+ r#"INSERT INTO course_session (id, course, teacher, topic, starts_at, ends_at)
43+ VALUES ($1, $2, $3, $4, $5, $6)
44+ RETURNING id, course, teacher, topic, starts_at, ends_at"#,
45+ session.id,
46+ session.course,
47+ session.teacher,
48+ session.topic,
49+ session.starts_at,
50+ session.ends_at,
4751 )
48- .await?
49- .ok_or(AppError::NotFound)
52+ .fetch_one(db)
53+ .await;
54+ match created {
55+ Ok(created) => Ok(created),
56+ Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound),
57+ Err(err) => Err(err.into()),
58+ }
5059 }
5160
5261 pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> {
53- Ok(db.select(id.record()).await?)
62+ let session = sqlx::query_as!(
63+ CourseSession,
64+ r#"SELECT id, course, teacher, topic, starts_at, ends_at
65+ FROM course_session WHERE id = $1"#,
66+ id,
67+ )
68+ .fetch_optional(db)
69+ .await?;
70+ Ok(session)
5471 }
5572
5673 /// A course's sessions, most recent lesson first. Ordered by `starts_at`
@@ -63,11 +80,11 @@ pub async fn list_for_course(
6380 offset: i64,
6481 ) -> Result<(Vec<CourseSession>, i64), AppError> {
6582 PagedList::new(
66- "course_session WHERE course = $course",
83+ "course_session WHERE course = $1",
6784 "ORDER BY starts_at DESC, id DESC",
6885 )
69- .bind("course", course.record())
70- .run(limit, offset, db)
86+ .bind(course.uuid())
87+ .run::<CourseSession>(limit, offset, db)
7188 .await
7289 }
7390
@@ -86,11 +103,17 @@ pub async fn update(
86103 starts_at: Option<Timestamp>,
87104 ends_at: Option<Option<Timestamp>>,
88105 ) -> Result<CourseSession, AppError> {
89- FieldUpdate::new(session.id.record())
90- .set("teacher", teacher.map(|teacher| teacher.record()))
91- .set("topic", topic)
92- .set("starts_at", starts_at)
93- .set("ends_at", ends_at)
106+ FieldUpdate::new(COURSE_SESSION_TABLE, session.id.uuid())
107+ .set(
108+ "teacher",
109+ teacher.map(|teacher| crate::db::page::Param::Uuid(teacher.uuid())),
110+ )
111+ .set("topic", topic.map(|topic| topic.as_str().to_owned()))
112+ .set("starts_at", starts_at.map(|at| at.as_millis()))
113+ .set(
114+ "ends_at",
115+ ends_at.map(|ends_at| crate::db::page::Param::OptI64(ends_at.map(|at| at.as_millis()))),
116+ )
94117 .ordered("starts_at", "ends_at", range_error())
95118 .run::<CourseSession>(db)
96119 .await
@@ -99,32 +122,31 @@ pub async fn update(
99122 /// Delete the session and cascade-remove its roll-call rows, in one
100123 /// transaction: as two unbatched queries a failure between them stranded
101124 /// roll-call rows on a session that was already gone. The other half of
102-/// that invariant is [`crate::db::session_attendance::mark`],
103-/// which proves the session still exists inside its own write — a
104-/// transaction here cannot stop a mark that commits *after* this one.
125+/// that invariant is [`crate::db::session_attendance::mark`], whose
126+/// session-row lock makes a mark and this delete take turns — a mark
127+/// committing after this cascade cannot name a session that is gone.
105128 pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> {
106- let (mut result, mut errors) = transaction_with_retry(
107- db,
108- "BEGIN TRANSACTION;
109- DELETE session_attendance WHERE session = $s;
110- LET $before = (DELETE $s RETURN BEFORE);
111- RETURN $before;
112- COMMIT TRANSACTION;",
113- &[("s".into(), session.id.record().into_value())],
114- // No THROW of its own — an unconditional cascade, so the only
115- // error worth telling apart is a lost round (see
116- // [`crate::db::exam::delete`]).
117- &[],
118- )
119- .await?;
120- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
121- return Err(error.into());
122- }
123- // Read through the trailing `RETURN`, never a hand-counted slot.
124- let slot = result.num_statements().saturating_sub(2);
125- let deleted: Option<CourseSession> =
126- result.take::<Vec<CourseSession>>(slot)?.into_iter().next();
127- deleted.ok_or(AppError::NotFound)
129+ tx_with_retry(db, false, async |tx| {
130+ // Roll-call rows first: the session row's own FK would refuse the
131+ // delete while they exist. An empty first sweep is fine — the
132+ // session may simply have had none.
133+ sqlx::query!(
134+ r#"DELETE FROM session_attendance WHERE session = $1"#,
135+ session.id,
136+ )
137+ .execute(&mut *tx)
138+ .await?;
139+ let deleted = sqlx::query_as!(
140+ CourseSession,
141+ r#"DELETE FROM course_session WHERE id = $1
142+ RETURNING id, course, teacher, topic, starts_at, ends_at"#,
143+ session.id,
144+ )
145+ .fetch_optional(&mut *tx)
146+ .await?;
147+ deleted.ok_or(AppError::NotFound)
148+ })
149+ .await
128150 }
129151
130152 #[cfg(test)]
src/db/enrollment.rsmodified+170 -170
@@ -1,49 +1,55 @@
11 //! The `enrollment` table: the roster read and listing, the seat-returning
2-//! delete, and the enroll claim — the one transaction that checks the pair
3-//! free, the member still a student, and the roster under capacity while it
2+//! delete, and the enroll claim — one transaction that checks the pair free,
3+//! the member still a student, and the roster under capacity while it
44 //! spends the seat. The target-user gates the HTTP handlers pay live in
55 //! [`crate::service::enrollment`].
66
7-use surrealdb::types::SurrealValue;
8-
9-use crate::constant::ENROLLMENT_COUNT_FIELD;
10-use crate::database::{Database, transaction_with_retry};
7+use crate::database::{Database, tx_with_retry, unique_violation};
118 use crate::db::cap;
129 use crate::db::page::PagedList;
1310 use crate::domain::course::CourseId;
14-use crate::domain::enrollment::{Enrollment, EnrollmentId};
11+use crate::domain::enrollment::Enrollment;
1512 use crate::domain::role::Role;
1613 use crate::domain::user::UserId;
1714 use crate::error::{AppError, ValidationError};
1815
19-/// The `THROW` markers [`enroll`]'s claim aborts with: this pair
20-/// already holds a row, the roster is full, and the person being enrolled is no
21-/// longer a student.
22-const HELD_MARK: &str = "enroll_held";
23-const FULL_MARK: &str = "enroll_full";
24-const UNFIT_MARK: &str = "enroll_not_student";
16+/// What [`enroll`]'s transaction settled on — the three old `THROW` markers
17+/// (`enroll_held`, `enroll_not_student`, `enroll_full`) as Rust verdicts.
18+enum Verdict {
19+ /// This pair already holds a row.
20+ Held,
21+ /// The person being enrolled is no longer a student.
22+ Unfit,
23+ /// The roster is full — or the course is gone; the caller reads which.
24+ Full,
25+ /// The seat is spent and the row is written.
26+ Made(Enrollment),
27+}
28+
29+/// The primary key the natural composite PK carries — the constraint name
30+/// that surfaces in SQLSTATE 23505 when a rival lands first.
31+const PAIR_CONSTRAINT: &str = "enrollment_course_user";
2532
26-/// Enroll (idempotently) `user` into `course`. One row per (course, user),
27-/// keyed by a deterministic composite id, so concurrent enrolls of the same
28-/// pair converge on one row instead of racing the unique index into a 500:
29-/// the loser of the `CREATE` reads the winner's row back and returns it.
30-/// When the course carries a capacity, a full roster refuses new members
31-/// (409) — the seat is taken by a single-record conditional write on the
32-/// course row whose bound is the row's *own* `capacity` column, read inside
33-/// the same statement that spends the seat. A snapshot integer taken by a
34-/// read beforehand would be exactly the number a concurrent capacity PATCH
35-/// invalidates, which is what this promised and did not do. An already
36-/// enrolled user is returned as-is even when the roster is full, and never
37-/// charged a seat. The same claim is the delete guard's other half: it
38-/// matches nothing once the course row is gone, and while it holds a seat
39-/// the course cannot be deleted — so no roster row can outlive its course.
33+/// Enroll (idempotently) `user` into `course`. The table's primary key *is*
34+/// the (course, user) pair, so concurrent enrolls of the same pair converge
35+/// on one row instead of racing into a 500: the loser reads the winner's row
36+/// back and returns it. When the course carries a capacity, a full roster
37+/// refuses new members (409) — the seat is taken by a single-record
38+/// conditional write on the course row whose bound is the row's *own*
39+/// `capacity` column, read inside the same statement that spends the seat. A
40+/// snapshot integer taken by a read beforehand would be exactly the number a
41+/// concurrent capacity PATCH invalidates. An already enrolled user is
42+/// returned as-is even when the roster is full, and never charged a seat.
43+/// The same claim is the delete guard's other half: it matches nothing once
44+/// the course row is gone, and while it holds a seat the course cannot be
45+/// deleted — so no roster row can outlive its course.
4046 ///
41-/// On admissibility ([`crate::database::transaction_with_retry`]): the
42-/// `CREATE` here *can* answer "already exists", but only to a rival that
43-/// landed inside this very window — and the re-send then sees that row at
44-/// the `$held` gate and takes the other branch, so the loop converges
45-/// instead of re-asking a settled question. Same shape, same reason, as
46-/// [`crate::db::class_pump::attach`].
47+/// Gate order is the old THROW order: an existing pair outranks the role
48+/// check, which outranks a full roster. The role check takes the user row
49+/// `FOR NO KEY UPDATE`, the same row a demotion cascade updates before its
50+/// sweep, so grant and demotion serialize on the row lock in both
51+/// directions — a row landing after the sweep is impossible, and a demotion
52+/// landing before this check refuses it.
4753 pub async fn enroll(
4854 db: &Database,
4955 course: &CourseId,
@@ -53,112 +59,89 @@ pub async fn enroll(
5359 if let Some(existing) = read_for_user(db, course, user).await? {
5460 return disown_if_pumped(db, existing).await;
5561 }
56- let enrollment = Enrollment {
57- id: EnrollmentId::composite(course, user),
58- course: course.clone(),
59- user: user.clone(),
60- enrolled_by: enrolled_by.clone(),
61- // Hand-placed: no source key at all is written, which is what makes
62- // a class sweep unable to take this row back.
63- source: None,
62+ let verdict = tx_with_retry(db, false, async |tx| {
63+ // The duplicate gate rides ahead of the role check, so "you are
64+ // already in" still outranks everything.
65+ let held = sqlx::query!(
66+ r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#,
67+ course,
68+ user,
69+ )
70+ .fetch_optional(&mut *tx)
71+ .await?;
72+ if held.is_some() {
73+ return Ok(Verdict::Held);
74+ }
75+ // The role handshake: the live role decides, and the row lock makes
76+ // the check and the insert one decision against a concurrent
77+ // demotion (see the doc above).
78+ let role = sqlx::query!(
79+ r#"SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#,
80+ user,
81+ )
82+ .fetch_optional(&mut *tx)
83+ .await?;
84+ if role.map(|row| row.role).as_deref() != Some(Role::Student.as_str()) {
85+ return Ok(Verdict::Unfit);
86+ }
87+ // The seat and the row in one statement (the cap recipe): a refused
88+ // insert takes its own seat bump back; zero rows means the roster is
89+ // full or the course is gone — only the caller pays for the read
90+ // that tells those apart.
91+ let row = sqlx::query_as!(
92+ Enrollment,
93+ r#"WITH seat AS (
94+ UPDATE course
95+ SET enrollment_count = enrollment_count + 1
96+ WHERE id = $1
97+ AND enrollment_count < COALESCE(capacity, $2)
98+ RETURNING 1)
99+ INSERT INTO enrollment (course, app_user, enrolled_by, source)
100+ SELECT $1, $3, $4, NULL WHERE EXISTS (SELECT 1 FROM seat)
101+ RETURNING course, app_user AS "user", enrolled_by, source"#,
102+ course,
103+ cap::UNLIMITED,
104+ user,
105+ enrolled_by,
106+ )
107+ .fetch_optional(&mut *tx)
108+ .await?;
109+ match row {
110+ Some(row) => Ok(Verdict::Made(row)),
111+ None => Ok(Verdict::Full),
112+ }
113+ })
114+ .await;
115+ // The 23505 backstop folds into the Held verdict before the mapping:
116+ // someone placed this pair between the gate and the insert, and their
117+ // row is the answer — no seat was spent finding that out.
118+ let verdict = match verdict {
119+ Err(AppError::Db(err)) if unique_violation(&err) == Some(PAIR_CONSTRAINT) => {
120+ Ok(Verdict::Held)
121+ }
122+ other => other,
64123 };
65- // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has
66- // to be *seen*, or the pair's second writer would keep the seat it
67- // claimed for a row that already existed and the counter would drift
68- // above the roster forever.
69- //
70- // Parenthesized `??` throughout: `n ?? 0 < cap` parses as
71- // `n ?? (0 < cap)`, which is truthy for every row and would enroll past
72- // the capacity.
73- //
74- // The seat is claimed on the *course*, so the student's own row is
75- // claimed beside it ([`cap::role_claim`]): a demotion's sweep runs on a
76- // snapshot, and a row landing after it would count a seat for someone
77- // who may not hold one, with nothing left to re-sweep. It rides between
78- // the duplicate gate and the seat, so "you are already in" still
79- // outranks it and it outranks a full roster.
80- let held_by = cap::role_claim(
81- "usr",
82- &format!("!= '{}'", Role::Student.as_str()),
83- UNFIT_MARK,
84- );
85- let hold = held_by.join(";\n ");
86- let sql = format!(
87- "BEGIN TRANSACTION;
88- LET $held = (SELECT VALUE id FROM $id);
89- IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }};
90- {hold};
91- LET $seat = (UPDATE $course SET {ENROLLMENT_COUNT_FIELD} = \
92- ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \
93- WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \
94- RETURN VALUE id);
95- IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }};
96- CREATE $id CONTENT $row;
97- COMMIT TRANSACTION;"
98- );
99- // The process still sends its counter writes one at a time (see
100- // [`cap::counter_lock`]); this statement moves the same counter every
101- // cap claim does.
102- let _guard = cap::counter_lock().await;
103- let (mut result, mut errors) = transaction_with_retry(
104- db,
105- &sql,
106- &[
107- ("id".into(), enrollment.id.record().into_value()),
108- ("row".into(), enrollment.clone().into_value()),
109- ("course".into(), course.record().into_value()),
110- ("usr".into(), user.record().into_value()),
111- ("unlimited".into(), cap::UNLIMITED.into_value()),
112- ],
113- &[HELD_MARK, FULL_MARK, UNFIT_MARK],
114- )
115- .await?;
116- // Someone placed this pair first; their row is the answer, and no seat
117- // was spent finding that out. It is read first: it outranks the refusal
118- // below, and the gate aborts before the seat is touched.
119- if errors
120- .values()
121- .any(|error| error.to_string().contains(HELD_MARK))
122- {
123- return match read_for_user(db, course, user).await? {
124+ match verdict {
125+ Ok(Verdict::Made(row)) => Ok(row),
126+ Ok(Verdict::Held) => match read_for_user(db, course, user).await? {
124127 Some(existing) => disown_if_pumped(db, existing).await,
125128 None => Err(AppError::Internal("failed to enroll user".into())),
126- };
127- }
128- // Demoted while this ran: the same refusal the service's own gate makes
129- // a moment earlier, and the only one that can arrive after it.
130- if errors
131- .values()
132- .any(|error| error.to_string().contains(UNFIT_MARK))
133- {
134- return Err(AppError::Validation(ValidationError::Invalid {
129+ },
130+ // Demoted while this ran: the same refusal the service's own gate
131+ // makes a moment earlier, and the only one that can arrive after it.
132+ Ok(Verdict::Unfit) => Err(AppError::Validation(ValidationError::Invalid {
135133 field: "user_id",
136134 reason: "only students can be enrolled in a course",
137- }));
138- }
139- // Full, or the course is gone — the conditional write matches nothing
140- // either way, and only this path pays for the read that tells them
141- // apart.
142- if errors
143- .values()
144- .any(|error| error.to_string().contains(FULL_MARK))
145- {
146- return match crate::db::course::read(db, course).await? {
135+ })),
136+ // Full, or the course is gone — the conditional write matches
137+ // nothing either way, and only this path pays for the read that
138+ // tells them apart.
139+ Ok(Verdict::Full) => match crate::db::course::read(db, course).await? {
147140 Some(_) => Err(AppError::Conflict("the course is full")),
148141 None => Err(AppError::NotFound),
149- };
150- }
151- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
152- return Err(error.into());
142+ },
143+ Err(err) => Err(err),
153144 }
154- // Slots count BEGIN, two LETs and two IFs, plus the holder claim's own
155- // statements — counted, not tallied by hand, so a statement added there
156- // cannot read back the wrong result.
157- result
158- .take::<Vec<Enrollment>>(5 + held_by.len())?
159- .into_iter()
160- .next()
161- .ok_or_else(|| AppError::Internal("failed to enroll user".into()))
162145 }
163146
164147 /// A hand enroll landing on a row a class pumped takes the row *off* the
@@ -167,28 +150,30 @@ pub async fn enroll(
167150 /// holds in the other direction — a manual unenroll wins, permanently — and
168151 /// without it "hand-placed" was a state only a first enroll could reach.
169152 ///
170-/// `UNSET`, not `= NONE`: absence *is* the meaning of this column (see the
171-/// struct doc), and it is what a hand enroll writes on the create path.
153+/// `NULL`, not absence: the column is a nullable uuid whose NULL *is* the
154+/// meaning a missing key used to carry (see the struct doc), and it is what
155+/// a hand enroll writes on the create path too.
172156 async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result<Enrollment, AppError> {
173- if existing.source.is_none() {
157+ if existing.get_source().is_none() {
174158 return Ok(existing);
175159 }
176- let mut result = db
177- .query("UPDATE $id UNSET source RETURN AFTER")
178- .bind(("id", existing.id.record()))
179- .await?
180- .check()?;
160+ let disowned = sqlx::query_as!(
161+ Enrollment,
162+ r#"UPDATE enrollment SET source = NULL
163+ WHERE course = $1 AND app_user = $2
164+ RETURNING course, app_user AS "user", enrolled_by, source"#,
165+ existing.get_course(),
166+ existing.get_user(),
167+ )
168+ .fetch_optional(db)
169+ .await?;
181170 // A row that is no longer there is not an internal error: an unenroll
182171 // (or the class sweep a role change runs) landing between the read
183172 // above and this write matches nothing, and the caller asked to be
184173 // enrolled — which they were, by the row this call was handed. The
185174 // disown is all that is lost, and it is lost to a delete that took the
186175 // whole row with it.
187- Ok(result
188- .take::<Vec<Enrollment>>(0)?
189- .into_iter()
190- .next()
191- .unwrap_or(existing))
176+ Ok(disowned.unwrap_or(existing))
192177 }
193178
194179 /// Some(_) iff `user` is enrolled in `course` — the grading gate.
@@ -197,13 +182,16 @@ pub async fn read_for_user(
197182 course: &CourseId,
198183 user: &UserId,
199184 ) -> Result<Option<Enrollment>, AppError> {
200- let mut result = db
201- .query("SELECT * FROM enrollment WHERE course = $course AND user = $usr LIMIT 1")
202- .bind(("course", course.record()))
203- .bind(("usr", user.record()))
204- .await?
205- .check()?;
206- Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next())
185+ let row = sqlx::query_as!(
186+ Enrollment,
187+ r#"SELECT course, app_user AS "user", enrolled_by, source
188+ FROM enrollment WHERE course = $1 AND app_user = $2"#,
189+ course,
190+ user,
191+ )
192+ .fetch_optional(db)
193+ .await?;
194+ Ok(row)
207195 }
208196
209197 pub async fn list_for_course(
@@ -212,32 +200,44 @@ pub async fn list_for_course(
212200 limit: Option<i64>,
213201 offset: i64,
214202 ) -> Result<(Vec<Enrollment>, i64), AppError> {
215- PagedList::new("enrollment WHERE course = $course", "ORDER BY id DESC")
216- .bind("course", course.record())
217- .run(limit, offset, db)
218- .await
203+ // The old composite key `{course}_{user}` sorted by user within a
204+ // course — its course prefix was constant — so the natural-PK columns
205+ // sort the same way.
206+ PagedList::new(
207+ "enrollment WHERE course = $1",
208+ "ORDER BY course DESC, app_user DESC",
209+ )
210+ .bind(course.uuid())
211+ .run::<Enrollment>(limit, offset, db)
212+ .await
219213 }
220214
215+/// Take the row and give its seat back in one statement, so nothing but a
216+/// lost transaction can drift the counter. `None` when the pair held no row.
221217 pub async fn remove(
222218 db: &Database,
223219 course: &CourseId,
224220 user: &UserId,
225221 ) -> Result<Option<Enrollment>, AppError> {
226- // The seat comes back in the same transaction as the row that held it,
227- // so nothing but a lost transaction can drift the counter.
228- let mut result = db
229- .query(
230- "BEGIN TRANSACTION;
231- LET $gone = (DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE);
232- UPDATE $course SET enrollment_count = math::max([(enrollment_count ?? 0) - array::len($gone), 0]);
233- RETURN $gone;
234- COMMIT TRANSACTION;",
235- )
236- .bind(("course", course.record()))
237- .bind(("usr", user.record()))
238- .await?
239- .check()?;
240- Ok(result.take::<Vec<Enrollment>>(3)?.into_iter().next())
222+ let gone = sqlx::query_as!(
223+ Enrollment,
224+ r#"WITH gone AS (
225+ DELETE FROM enrollment
226+ WHERE course = $1 AND app_user = $2
227+ RETURNING course, app_user, enrolled_by, source),
228+ seated AS (
229+ UPDATE course
230+ SET enrollment_count = GREATEST(
231+ enrollment_count - (SELECT count(*) FROM gone), 0)
232+ WHERE id = $1
233+ RETURNING 1)
234+ SELECT course, app_user AS "user", enrolled_by, source FROM gone"#,
235+ course,
236+ user,
237+ )
238+ .fetch_optional(db)
239+ .await?;
240+ Ok(gone)
241241 }
242242
243243 #[cfg(test)]
src/db/session_attendance.rsmodified+193 -185
@@ -4,60 +4,30 @@
44 //! management's, only students attend, enrollment) are
55 //! [`crate::service::session_attendance`]'s to judge before calling here.
66
7-use surrealdb::types::SurrealValue;
8-
9-use crate::constant::{
10- LESSON_COUNTED_AT_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD,
11-};
12-use crate::database::{Database, transaction_with_retry};
7+use crate::database::{Database, tx_with_retry};
138 use crate::db::page::PagedList;
149 use crate::domain::attendance::AttendanceStatus;
1510 use crate::domain::course_session::{CourseSession, CourseSessionId};
16-use crate::domain::session_attendance::{
17- SessionAttendance, SessionAttendanceId, counts_as_attended,
18-};
11+use crate::domain::session_attendance::SessionAttendance;
1912 use crate::domain::timestamp::Timestamp;
2013 use crate::domain::user::UserId;
2114 use crate::error::AppError;
2215
23-/// Record (or overwrite) `user`'s status for the session. One row per
24-/// (session, user), keyed by a deterministic composite id so this is a
25-/// single atomic UPSERT — concurrent marks converge on the one row.
26-///
27-/// The "session still exists" gate rides in the same transaction as the
28-/// mark, the mirror of the cascade in [`crate::db::course_session::delete`]: the
29-/// caller's pre-flight read sits four round trips in front of this write,
30-/// so a delete landing in that gap used to leave a roll-call row on a
31-/// session that was gone — and that row was *unremovable*, its only delete
32-/// route 404ing on the vanished session while the attendance report went
33-/// on counting it. A deleted session reads NONE, which is falsy, so the
34-/// gate is written as an explicit `IS NONE` (see
35-/// [`crate::domain::exam_result::ExamResult::grade`]). It reads the
36-/// session's `teacher` — required on every row, so NONE means "no row" just
37-/// as `id` did — because the counter below needs that teacher anyway, and
38-/// one read serves both.
39-///
40-/// A read is not a claim, though: SurrealDB 3.2.3 conflict-checks write
41-/// sets, not read sets, so that gate alone only closes the *sequential*
42-/// order (delete committed, then the mark arrives). To make the two really
43-/// collide, this transaction also *writes* the session row, unconditionally
44-/// — the bump-and-restore of [`crate::domain::exam_answer::ExamAnswer::save`]
45-/// on the one column this write already owns, [`LESSON_COUNTED_AT_FIELD`].
46-/// Unconditional is the whole point: the credit branch below writes that
47-/// column already, but it fires only for the first roll call of a lesson
48-/// that has begun, so a future-dated sheet and every re-mark of a counted
49-/// one touched nothing at all and committed happily beside
50-/// `DELETE /sessions/{id}`. Re-stating the value verbatim would not do
51-/// either — an `UPDATE` that leaves the document unchanged is elided and
52-/// never enters the write set — hence bump first, then either stamp
53-/// (credit branch) or put back exactly what was found, `NONE` included, so
54-/// the row is byte-identical and the once-per-lesson rule is untouched.
16+/// Record (or overwrite) `user`'s status for the session. The table's
17+/// primary key *is* the (session, user) pair, so the mark is a single
18+/// atomic upsert — concurrent marks converge on the one row.
5519 ///
56-/// Sound to re-send while the store answers "conflict, retry": the gate
57-/// reads the record a delete writes, so the two contend by design, and the
58-/// UPSERT cannot legitimately answer "already exists" — its composite id is
59-/// bijective with the `session_attendance_session_user` unique tuple, so
60-/// the index entry can only point at the row the id already names.
20+/// The "session still exists" gate is a row lock: the transaction takes the
21+/// session row `FOR NO KEY UPDATE` before anything else, so a session (or
22+/// course) delete cascading beneath this mark simply waits, and a delete
23+/// that got there first leaves this gate matching nothing — `404`, the
24+/// mirror of [`crate::db::course_session::delete`]. The caller's
25+/// pre-flight read sits several round trips in front of this write, which
26+/// is exactly the gap the old code had to fake with a bump-and-restore
27+/// write on the session row; the lock is the same serialization without
28+/// the trick. It also freezes `starts_at` and `held_counted_at` for the
29+/// transaction, so two simultaneous first marks take turns and the
30+/// lesson-held credit below is stamped exactly once.
6131 ///
6232 /// Two badge counters move in this same transaction, both of them read
6333 /// from the store rather than taken on the caller's word:
@@ -65,27 +35,27 @@ use crate::error::AppError;
6535 /// - `lessons_attended_total`, on the person marked, as a *delta* rather
6636 /// than an increment, because this is an upsert: a re-mark that changes
6737 /// nothing must change nothing, and a teacher's correction must move it
68-/// back down. `$was` is read before the upsert overwrites it (`NONE` when
69-/// the pair has no row yet), so it writes only on a real crossing of the
70-/// attended line, and only for a **student** — attending lessons is a
71-/// student's badge, the same student-only rule enrolling and sitting an
72-/// exam already carry, so a teacher marked present in their own lesson
73-/// moves it in neither direction. The live `role` decides that, not the
74-/// role someone held when the row was written.
38+/// back down. The pair's stored status is read before the upsert
39+/// overwrites it (`None` when the pair has no row yet), so it writes
40+/// only on a real crossing of the attended line, and only for a
41+/// **student** — attending lessons is a student's badge, the same
42+/// student-only rule enrolling and sitting an exam already carry, so a
43+/// teacher marked present in their own lesson moves it in neither
44+/// direction. The live `role` decides that, not the role someone held
45+/// when the row was written.
7546 /// - `lessons_held_total`, on the *session's* teacher, exactly once per
76-/// session: the first roll call taken stamps
77-/// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees
78-/// the stamp and credits nothing. It counts lessons that actually
79-/// happened — scheduling one and cancelling it earns nothing, which is
80-/// why the credit does not live in `crate::db::course_session::create`. Two
81-/// simultaneous first marks both write the lesson row, so the store's own
82-/// conflict detection (and `transaction_with_retry` behind it) is what
83-/// keeps the stamp from being set twice.
47+/// session: the first roll call taken stamps `held_counted_at` on the
48+/// lesson and every later mark sees the stamp and credits nothing. It
49+/// counts lessons that actually happened — scheduling one and
50+/// cancelling it earns nothing, which is why the credit does not live
51+/// in `crate::db::course_session::create`. Two simultaneous first
52+/// marks serialize on the session row's lock, so the stamp cannot be
53+/// set twice.
8454 ///
8555 /// "Actually happened" is a clock reading, not a request count: the
8656 /// credit waits for the lesson's own `starts_at` to arrive. Roll call is
87-/// deliberately *not* time-gated — a teacher may open the sheet early and
88-/// is never refused — so without this a teacher could schedule two
57+/// deliberately *not* time-gated — a teacher may open the sheet early
58+/// and is never refused — so without this a teacher could schedule two
8959 /// hundred lessons for next week, mark one student in each, and hold two
9060 /// hundred lessons this afternoon. Because the stamp is written only on
9161 /// the branch that credits, a sheet opened early and touched again after
@@ -100,9 +70,6 @@ use crate::error::AppError;
10070 /// credited — a student's real lessons eaten by someone else's farm. It
10171 /// is also nobody's self-service: only a teacher can mark a student, so
10272 /// the counter cannot be moved by the person it decorates.
103-///
104-/// Both are floored/guarded rather than trusting the column to exist: a row
105-/// written before these columns carries none of them.
10673 //
10774 // corner-cut: that asymmetry leaves a teacher able to inflate a *student's*
10875 // attendance with future-dated lessons. Closing it needs the credit stamped
@@ -117,76 +84,94 @@ pub async fn mark(
11784 status: AttendanceStatus,
11885 marked_by: &UserId,
11986 ) -> Result<SessionAttendance, AppError> {
120- let attended = counts_as_attended(&status);
87+ let attended = crate::domain::session_attendance::counts_as_attended(&status);
12188 let delta: i64 = if attended { 1 } else { -1 };
122- let attendance = SessionAttendance {
123- id: SessionAttendanceId::composite(session.get_id(), user),
124- session: session.get_id().clone(),
125- course: session.get_course().clone(),
126- user: user.clone(),
127- status,
128- marked_by: marked_by.clone(),
129- };
130- let (mut written, mut errors) = transaction_with_retry(
131- db,
132- &format!(
133- "BEGIN TRANSACTION;
134- LET $teacher = (SELECT VALUE teacher FROM ONLY $sess);
135- IF $teacher IS NONE {{ THROW 'session_missing' }};
136- LET $counted = (SELECT VALUE {LESSON_COUNTED_AT_FIELD} FROM ONLY $sess);
137- LET $begun = ((SELECT VALUE starts_at FROM ONLY $sess) <= $stamp);
138- LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');
139- LET $was = ((SELECT VALUE status FROM ONLY $id) IN ['present', 'late']);
140- LET $after = (UPSERT $id CONTENT $row RETURN AFTER);
141- IF $student AND $was != $now {{
142- UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =
143- math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0])
144- }};
145- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = ({LESSON_COUNTED_AT_FIELD} ?? 0) + 1;
146- IF ($counted IS NONE) AND $begun {{
147- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp;
148- UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} =
149- ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1
150- }} ELSE {{
151- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $counted
152- }};
153- RETURN $after;
154- COMMIT TRANSACTION;"
155- ),
156- &[
157- // `$session` is SurrealDB's own protected variable (the auth
158- // session): binding that name errors the whole query.
159- ("sess".into(), session.get_id().record().into_value()),
160- ("id".into(), attendance.id.record().into_value()),
161- ("usr".into(), user.record().into_value()),
162- ("now".into(), attended.into_value()),
163- ("delta".into(), delta.into_value()),
164- ("stamp".into(), Timestamp::now().into_value()),
165- ("row".into(), attendance.into_value()),
166- ],
167- &["session_missing"],
168- )
169- .await?;
170- // An aborted transaction errors every slot and only the THROW's own
171- // slot names the marker, so a refusal is read by marker while a lost
172- // round was already re-sent — never reported as a 500.
173- if errors
174- .values()
175- .any(|error| error.to_string().contains("session_missing"))
176- {
177- return Err(AppError::NotFound);
178- }
179- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
180- return Err(error.into());
181- }
182- // The trailing `RETURN` is always the last statement before `COMMIT`,
183- // so its slot follows the statement count instead of a hand-kept one.
184- let slot = written.num_statements().saturating_sub(2);
185- written
186- .take::<Vec<SessionAttendance>>(slot)?
187- .into_iter()
188- .next()
189- .ok_or_else(|| AppError::Internal("failed to mark session attendance".into()))
89+ let now = Timestamp::now();
90+ tx_with_retry(db, false, async |tx| {
91+ // The gate and the serialization point: a live session row, locked
92+ // against the delete cascade and every rival mark.
93+ let sess = sqlx::query!(
94+ r#"SELECT teacher, starts_at, held_counted_at
95+ FROM course_session WHERE id = $1 FOR NO KEY UPDATE"#,
96+ session.id,
97+ )
98+ .fetch_optional(&mut *tx)
99+ .await?;
100+ let Some(sess) = sess else {
101+ return Err(AppError::NotFound);
102+ };
103+ // The pair's stored status — the pre-image the attended delta is
104+ // computed off.
105+ let was = sqlx::query!(
106+ r#"SELECT status FROM session_attendance
107+ WHERE session = $1 AND app_user = $2"#,
108+ session.id,
109+ user,
110+ )
111+ .fetch_optional(&mut *tx)
112+ .await?
113+ .map(|row| row.status);
114+ // The live role of the person marked (a gone user row marks as
115+ // non-student — no badge to move; the service gate has already
116+ // refused a vanished target before this write ran).
117+ let is_student = sqlx::query!(
118+ r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#,
119+ user,
120+ )
121+ .fetch_optional(&mut *tx)
122+ .await?
123+ .map(|row| row.is_student)
124+ .unwrap_or(false);
125+ let row = sqlx::query_as!(
126+ SessionAttendance,
127+ r#"INSERT INTO session_attendance (session, app_user, course, status, marked_by)
128+ VALUES ($1, $2, $3, $4, $5)
129+ ON CONFLICT (session, app_user) DO UPDATE
130+ SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by
131+ RETURNING session, app_user AS "user", course, status, marked_by"#,
132+ session.id,
133+ user,
134+ session.course,
135+ status,
136+ marked_by,
137+ )
138+ .fetch_one(&mut *tx)
139+ .await?;
140+ // The attended badge: student-only, and only on a real crossing.
141+ let was_attended = was
142+ .as_deref()
143+ .is_some_and(|was| was == "present" || was == "late");
144+ if is_student && was_attended != attended {
145+ sqlx::query!(
146+ r#"UPDATE app_user
147+ SET lessons_attended_total = GREATEST(lessons_attended_total + $2, 0)
148+ WHERE id = $1"#,
149+ user,
150+ delta,
151+ )
152+ .execute(&mut *tx)
153+ .await?;
154+ }
155+ // The held badge: once per lesson, and only once the lesson began.
156+ if sess.held_counted_at.is_none() && sess.starts_at <= now.as_millis() {
157+ sqlx::query!(
158+ r#"UPDATE course_session SET held_counted_at = $2 WHERE id = $1"#,
159+ session.id,
160+ now.as_millis(),
161+ )
162+ .execute(&mut *tx)
163+ .await?;
164+ sqlx::query!(
165+ r#"UPDATE app_user SET lessons_held_total = lessons_held_total + 1
166+ WHERE id = $1"#,
167+ sess.teacher,
168+ )
169+ .execute(&mut *tx)
170+ .await?;
171+ }
172+ Ok(row)
173+ })
174+ .await
190175 }
191176
192177 pub async fn list_for_session(
@@ -195,10 +180,16 @@ pub async fn list_for_session(
195180 limit: Option<i64>,
196181 offset: i64,
197182 ) -> Result<(Vec<SessionAttendance>, i64), AppError> {
198- PagedList::new("session_attendance WHERE session = $s", "ORDER BY id DESC")
199- .bind("s", session.record())
200- .run(limit, offset, db)
201- .await
183+ // The old composite key `{session}_{user}` sorted by user within a
184+ // session — its session prefix was constant — so the natural-PK
185+ // columns sort the same way.
186+ PagedList::new(
187+ "session_attendance WHERE session = $1",
188+ "ORDER BY session DESC, app_user DESC",
189+ )
190+ .bind(session.uuid())
191+ .run::<SessionAttendance>(limit, offset, db)
192+ .await
202193 }
203194
204195 /// Every roll-call row ever recorded for `user` — the session half of the
@@ -209,12 +200,16 @@ pub async fn list_for_user(
209200 db: &Database,
210201 user: &UserId,
211202 ) -> Result<Vec<SessionAttendance>, AppError> {
212- let mut result = db
213- .query("SELECT * FROM session_attendance WHERE user = $usr ORDER BY id DESC")
214- .bind(("usr", user.record()))
215- .await?
216- .check()?;
217- Ok(result.take::<Vec<SessionAttendance>>(0)?)
203+ let rows = sqlx::query_as!(
204+ SessionAttendance,
205+ r#"SELECT session, app_user AS "user", course, status, marked_by
206+ FROM session_attendance WHERE app_user = $1
207+ ORDER BY session DESC, app_user DESC"#,
208+ user,
209+ )
210+ .fetch_all(db)
211+ .await?;
212+ Ok(rows)
218213 }
219214
220215 /// Clearing a row the student was counted for gives the count back, in the
@@ -229,50 +224,60 @@ pub async fn list_for_user(
229224 ///
230225 /// Student-only on the same terms as the mark, and read from the store for
231226 /// the same reason.
232-///
233-/// Sound to re-send: neither statement can answer "already exists".
234-//
235-// corner-cut: both ends read the *live* role, so a student promoted between
236-// being marked present and having that row corrected leaves the counter one
237-// high (the credit landed as a student, the refund is refused as staff).
238-// Upgrade path is stamping the credit on the roll-call row itself and
239-// refunding off that stamp, the way `counted_on_time` works for homework —
240-// not worth a column until a promotion mid-term is a real complaint.
241227 pub async fn remove(
242228 db: &Database,
243229 session: &CourseSessionId,
244230 user: &UserId,
245231 ) -> Result<Option<SessionAttendance>, AppError> {
246- let (mut result, mut errors) = transaction_with_retry(
247- db,
248- &format!(
249- "BEGIN TRANSACTION;
250- LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');
251- LET $gone = (DELETE session_attendance
252- WHERE session = $s AND user = $usr RETURN BEFORE);
253- IF $student AND array::len($gone) > 0 AND $gone[0].status IN ['present', 'late'] {{
254- UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =
255- math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) - 1, 0])
256- }};
257- RETURN $gone;
258- COMMIT TRANSACTION;"
259- ),
260- &[
261- ("s".into(), session.record().into_value()),
262- ("usr".into(), user.record().into_value()),
263- ],
264- &[],
265- )
266- .await?;
267- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
268- return Err(error.into());
269- }
270- // The trailing `RETURN` is always the last statement before `COMMIT`.
271- let slot = result.num_statements().saturating_sub(2);
272- Ok(result
273- .take::<Vec<SessionAttendance>>(slot)?
274- .into_iter()
275- .next())
232+ tx_with_retry(db, false, async |tx| {
233+ // The pre-image and the row's right to exist in one locked
234+ // statement: the row cannot vanish (or change status) under this
235+ // transaction, and `None` here is simply "nothing to remove".
236+ let Some(gone) = sqlx::query_as!(
237+ SessionAttendance,
238+ r#"SELECT session, app_user AS "user", course, status, marked_by
239+ FROM session_attendance
240+ WHERE session = $1 AND app_user = $2
241+ FOR UPDATE"#,
242+ session,
243+ user,
244+ )
245+ .fetch_optional(&mut *tx)
246+ .await?
247+ else {
248+ return Ok(None);
249+ };
250+ if crate::domain::session_attendance::counts_as_attended(&gone.status) {
251+ // Student-only, live role: the same rule the mark pays.
252+ let student = sqlx::query!(
253+ r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#,
254+ user,
255+ )
256+ .fetch_optional(&mut *tx)
257+ .await?
258+ .map(|row| row.is_student)
259+ .unwrap_or(false);
260+ if student {
261+ sqlx::query!(
262+ r#"UPDATE app_user
263+ SET lessons_attended_total = GREATEST(lessons_attended_total - 1, 0)
264+ WHERE id = $1"#,
265+ user,
266+ )
267+ .execute(&mut *tx)
268+ .await?;
269+ }
270+ }
271+ sqlx::query!(
272+ r#"DELETE FROM session_attendance WHERE session = $1 AND app_user = $2"#,
273+ session,
274+ user,
275+ )
276+ .execute(&mut *tx)
277+ .await?;
278+ Ok(Some(gone))
279+ })
280+ .await
276281 }
277282
278283 #[cfg(test)]
@@ -345,7 +350,10 @@ mod tests {
345350 }
346351
347352 async fn held(user: &UserId, db: &Database) -> i64 {
348- crate::db::badge::load(db, user).await.unwrap().get_lessons_held()
353+ crate::db::badge::load(db, user)
354+ .await
355+ .unwrap()
356+ .get_lessons_held()
349357 }
350358
351359 /// The whole transition table in one pass: an upsert may only move the
src/db/subject.rsmodified+0 -1
@@ -11,7 +11,6 @@ use crate::domain::course::CourseId;
1111 use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};
1212 use crate::error::AppError;
1313
14-
1514 pub async fn create(
1615 db: &Database,
1716 course: &CourseId,
src/domain/course.rsmodified+5 -2
@@ -20,7 +20,7 @@ impl CourseId {
2020
2121 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
2222 /// cannot take the newtype. Static `query!` binds take `self` directly.
23- pub fn uuid(&self) -> Uuid {
23+ pub fn uuid(&self) -> uuid::Uuid {
2424 self.0
2525 }
2626
@@ -33,8 +33,11 @@ impl CourseId {
3333 pub fn key(&self) -> String {
3434 self.0.to_string()
3535 }
36-
3736 }
37+#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
38+#[sqlx(transparent)]
39+pub struct CourseTitle(String);
40+
3841 impl CourseTitle {
3942 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
4043 validate_required("title", value, MAX_COURSE_TITLE_LEN)?;
src/domain/course_session.rsmodified+6 -3
@@ -1,4 +1,4 @@
1-use crate::constant::{MAX_SESSION_TOPIC_LEN};
1+use crate::constant::MAX_SESSION_TOPIC_LEN;
22 use crate::domain::course::CourseId;
33 use crate::domain::monotonic_id::next_uuid;
44 use crate::domain::timestamp::Timestamp;
@@ -21,7 +21,7 @@ impl CourseSessionId {
2121
2222 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
2323 /// cannot take the newtype. Static `query!` binds take `self` directly.
24- pub fn uuid(&self) -> Uuid {
24+ pub fn uuid(&self) -> uuid::Uuid {
2525 self.0
2626 }
2727
@@ -34,8 +34,11 @@ impl CourseSessionId {
3434 pub fn key(&self) -> String {
3535 self.0.to_string()
3636 }
37-
3837 }
38+#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
39+#[sqlx(transparent)]
40+pub struct SessionTopic(String);
41+
3942 impl SessionTopic {
4043 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
4144 validate_optional("topic", value, MAX_SESSION_TOPIC_LEN)?;
src/domain/subject.rsmodified+5 -4
@@ -40,8 +40,11 @@ impl SubjectId {
4040 pub fn key(&self) -> String {
4141 self.0.to_string()
4242 }
43-
4443 }
44+#[derive(Debug, Clone, PartialEq, Eq, Type)]
45+#[sqlx(transparent)]
46+pub struct SubjectName(String);
47+
4548 impl SubjectName {
4649 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
4750 validate_required("name", value, MAX_SUBJECT_NAME_LEN)?;
@@ -109,9 +112,7 @@ mod tests {
109112 /// burst comes out shuffled.
110113 #[tokio::test]
111114 async fn ids_sort_in_creation_order() {
112- let ids: Vec<String> = (0..500)
113- .map(|_| SubjectId::generate().key())
114- .collect();
115+ let ids: Vec<String> = (0..500).map(|_| SubjectId::generate().key()).collect();
115116 let mut sorted = ids.clone();
116117 sorted.sort();
117118 assert_eq!(ids, sorted);
src/domain/term.rsmodified+0 -1
@@ -40,7 +40,6 @@ impl TermId {
4040 pub fn key(&self) -> String {
4141 self.0.to_string()
4242 }
43-
4443 }
4544 pub fn gone_error() -> AppError {
4645 AppError::Validation(ValidationError::Invalid {
src/service/course.rsmodified+9 -22
@@ -1,7 +1,7 @@
11 //! Course workflows: the archived-term gate every course-scoped write pays,
22 //! the staffing changes a manager makes, and the delete that collects the
3-//! image/homework/note-file blob keys under the exam and homework locks
4-//! before the cascade sweeps those rows. The queries live in
3+//! image/homework/note-file blob keys before the guarded cascade sweeps
4+//! those rows. The queries live in
55 //! [`crate::db::course`].
66
77 use crate::database::Database;
@@ -135,24 +135,13 @@ pub struct DeleteOutcome {
135135 /// Delete the course: collect the image/homework/note-file blob keys, then
136136 /// run the cascading delete.
137137 ///
138-/// Writer lease of [`crate::service::exam_attempt::EXAM_LOCK`], for
139-/// `delete_exam`'s reason: this cascade sweeps the course's exams *and their
140-/// attempts*, and an attempt is the one exam child whose write cannot
141-/// collide with the sweep (its claim lands on the student's row, never the
142-/// exam's). Narrower here — the delete is refused while anyone is enrolled,
143-/// so a start would have to pass its enrollment gate and then have that
144-/// enrollment removed under it — but the hole is the same one and so is the
145-/// lease.
146-///
147-/// And the homework half of the same cascade, for
148-/// [`crate::web::homework::delete_homework`]'s reason: it sweeps the
149-/// course's homework with its submissions, files and results, and grading
150-/// ([`crate::db::homework_result::grade`]) writes a
151-/// result row against a homework it only *read*, which a delete committing
152-/// alongside is invisible to. Without this lease the grade lands behind the
153-/// sweep: an orphan `homework_result` under a vanished homework, plus a
154-/// `marks_given_total` on the grader no ungrade can reach. Lock order here
155-/// is EXAM_LOCK then HOMEWORK_LOCK, the only path that takes both.
138+/// The old writer leases on the exam-attempt and homework state are gone
139+/// with the store that needed them: this cascade is one guarded
140+/// transaction whose retry answers a child write that raced it mid-sweep
141+/// (`is_retryable_cascade` — a foreign key naming a row the racing write
142+/// just landed), so an attempt started or a grade written beside the sweep
143+/// is either swept by the re-sent cascade or refused by the very foreign
144+/// key it would have orphaned. No lock can out-guard that.
156145 ///
157146 /// The keys are read before the delete because it takes their rows with it;
158147 /// a refused delete just drops them unused. Unlinking the blobs stays the
@@ -160,8 +149,6 @@ pub struct DeleteOutcome {
160149 /// blob.
161150 pub async fn delete(db: &Database, course: &Course) -> Result<DeleteOutcome, AppError> {
162151 require_open(db, course).await?;
163- let _guard = crate::service::exam_attempt::EXAM_LOCK.write().await;
164- let _homework_guard = crate::service::homework::HOMEWORK_LOCK.write().await;
165152 let image_files = crate::db::question_image::file_keys_for_course(db, course.get_id()).await?;
166153 let answer_image_files =
167154 crate::db::answer_image::file_keys_for_course(db, course.get_id()).await?;
src/web/courses.rsmodified+2 -2
@@ -545,8 +545,8 @@ async fn delete_course(
545545 "only the course creator or a manager/admin can delete this course",
546546 ));
547547 }
548- // The workflow — archived-term gate, EXAM_LOCK and HOMEWORK_LOCK writer
549- // leases, blob-key collection, cascade — is [`service::course::delete`]'s.
548+ // The workflow — archived-term gate, blob-key collection, cascade — is
549+ // [`service::course::delete`]'s.
550550 // Blob unlinking stays here because only the web layer knows `files_path`.
551551 let outcome = service::course::delete(&st.db, &course).await?;
552552 if !outcome.deleted {