forge
Explore
Log in

Don't you dare go Hollow

πŸ”€ merge: port courses to sqlx/Postgres (L2)

Browse files at this commit

b88890f814c4cfb5b80f0194163a2bfb632c7bc4Ahmet Kaan GümüşParent: b213847b9b7897
src/db/course.rsmodified+369 -209
@@ -1,11 +1,9 @@
1 //! The `course` table: the unit exams, sessions, subjects and enrollments1 //! The `course` table: the unit exams, sessions, subjects and enrollments
2 //! hang off. Listed newest first; deleted with its whole subtree in one2 //! hang off. Listed newest first; deleted with its whole subtree in one
3-use surrealdb::types::{RecordId, SurrealValue};3+//! guarded cascade.
4 4
5-use crate::constant::{5+use crate::constant::COURSE_TABLE;
6- CLASS_COURSE_COUNT_FIELD, COURSE_COUNT_FIELD, ENROLLMENT_COUNT_FIELD, REF_COUNT_FIELD,6+use crate::database::{Database, tx_with_retry, unique_violation};
7-};
8-use crate::database::{Database, transaction_with_retry};
9 use crate::db::cap;7 use crate::db::cap;
10 use crate::db::field_update::FieldUpdate;8 use crate::db::field_update::FieldUpdate;
11 use crate::db::page::PagedList;9 use crate::db::page::PagedList;
@@ -14,16 +12,6 @@ use crate::domain::term::{self, TermId};
14 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
15 use crate::error::AppError;13 use crate::error::AppError;
16 14
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).
27 pub async fn create(15 pub async fn create(
28 db: &Database,16 db: &Database,
29 creator: &UserId,17 creator: &UserId,
@@ -33,50 +21,87 @@ pub async fn create(
33 term: Option<TermId>,21 term: Option<TermId>,
34 capacity: Option<i64>,22 capacity: Option<i64>,
35 ) -> Result<Course, AppError> {23 ) -> Result<Course, AppError> {
36- let course = Course {24+ let id = CourseId::generate();
37- id: CourseId::generate(),25+ let Some(term) = term else {
38- creator: creator.clone(),26+ let created = sqlx::query_as!(
39- teachers: Vec::new(),27+ Course,
40- term,28+ r#"INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity)
41- 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(),
42 title,62 title,
43 description,63 description,
44 kind,64 kind,
45- };65+ capacity,
46- let id = course.id.record();66+ term,
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,
54 cap::UNLIMITED,67 cap::UNLIMITED,
55- &id,
56- &course,
57- db,
58 )68 )
59- .await?69+ .fetch_one(db)
60- {70+ .await;
61- cap::Claimed::Made(created) => Ok(created),71+ match created {
72+ Ok(created) => Ok(created),
62 // Uncapped, so "full" can only mean the conditional write matched no73 // Uncapped, so "full" can only mean the conditional write matched no
63 // term row at all β€” the existence check the pre-flight lookup makes.74 // term row at all β€” the existence check the pre-flight lookup makes.
64- cap::Claimed::Full => Err(term::gone_error()),75+ Err(sqlx::Error::RowNotFound) => Err(term::gone_error()),
65- // Unreachable: the id is a ULID this call just generated.76+ // Unreachable: the id was minted above.
66- cap::Claimed::Duplicate => Err(AppError::Internal("failed to create course".into())),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()),
67 }81 }
68 }82 }
69 83
70 pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> {84 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)
72 }94 }
73 95
74 pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> {96 pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> {
75- let mut result = db97+ let rows = sqlx::query_as!(
76- .query("SELECT * FROM course ORDER BY id DESC")98+ Course,
77- .await?99+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
78- .check()?;100+ FROM course ORDER BY id DESC"#,
79- Ok(result.take::<Vec<Course>>(0)?)101+ )
102+ .fetch_all(db)
103+ .await?;
104+ Ok(rows)
80 }105 }
81 106
82 /// The courses `user` is enrolled in β€” the spine of `/courses/me` and the107 /// The courses `user` is enrolled in β€” the spine of `/courses/me` and the
@@ -88,36 +113,38 @@ pub async fn list_enrolled(
88 offset: i64,113 offset: i64,
89 ) -> Result<(Vec<Course>, i64), AppError> {114 ) -> Result<(Vec<Course>, i64), AppError> {
90 PagedList::new(115 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)",
92 "ORDER BY id DESC",117 "ORDER BY id DESC",
93 )118 )
94- .bind("usr", user.record())119+ .bind(user.uuid())
95- .run(limit, offset, db)120+ .run::<Course>(limit, offset, db)
96 .await121 .await
97 }122 }
98 123
99 /// The courses `user` runs β€” the ones they created plus the ones a manager124 /// The courses `user` runs β€” the ones they created plus the ones a manager
100 /// assigned them to. A teacher's slice of the catalog.125 /// assigned them to. A teacher's slice of the catalog.
101 ///126 ///
102-/// corner-cut: unpaged full table scan, and it stays one β€” every profile read127+/// corner-cut: unpaged full table scan, and it stays one β€” every profile
103-/// of a teacher pays it, so the ceiling is the course table's size. It128+/// read of a teacher pays it, so the ceiling is the course table's size.
104-/// cannot be indexed away on SurrealDB 3.2.3: an index on `creator` alone129+/// Under Postgres the `OR` halves could each use an index on `creator` /
105-/// leaves the `OR` a `TableScan` (EXPLAIN), and the per-element index the130+/// `teachers` (a GIN), but the old per-element index the membership half
106-/// membership half would need (`DEFINE INDEX ... FIELDS teachers[*]`) is131+/// would have needed was *wrong*, not merely useless β€” `$usr IN teachers`
107-/// *wrong*, not merely useless β€” with it, `$usr IN teachers` and132+/// returned **no rows at all** with it, which is what the integration test
108-/// `teachers CONTAINS $usr` return **no rows at all**, which is what the133+/// `assigned_teacher_manages_course_without_owning_it` catches. The upgrade
109-/// integration test `assigned_teacher_manages_course_without_owning_it`134+/// path is structural: a `course_teacher` link table indexed on `user`, the
110-/// catches. A plain `FIELDS teachers` index is correct but unused. The135+/// shape `enrollment` already has, turning this into two index-backed
111-/// upgrade path is structural: a `course_teacher` link table indexed on136+/// reads. No schema carries it yet, so the scan stays.
112-/// `user`, the shape `enrollment` already has, turning this into two
113-/// index-backed reads.
114 pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> {137 pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> {
115- let mut result = db138+ let rows = sqlx::query_as!(
116- .query("SELECT * FROM course WHERE creator = $usr OR $usr IN teachers ORDER BY id DESC")139+ Course,
117- .bind(("usr", user.record()))140+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
118- .await?141+ FROM course WHERE creator = $1 OR $2 = ANY(teachers) ORDER BY id DESC"#,
119- .check()?;142+ user,
120- Ok(result.take::<Vec<Course>>(0)?)143+ user,
144+ )
145+ .fetch_all(db)
146+ .await?;
147+ Ok(rows)
121 }148 }
122 149
123 /// Load every course behind `ids` (one query) β€” the join half of the150 /// 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>,
126 if ids.is_empty() {153 if ids.is_empty() {
127 return Ok(Vec::new());154 return Ok(Vec::new());
128 }155 }
129- let records: Vec<RecordId> = ids.iter().map(CourseId::record).collect();156+ let keys: Vec<CourseId> = ids.to_vec();
130- let mut result = db157+ let rows = sqlx::query_as!(
131- .query("SELECT * FROM course WHERE id IN $ids")158+ Course,
132- .bind(("ids", records))159+ r#"SELECT id, creator, teachers, title, description, kind, term, capacity
133- .await?160+ FROM course WHERE id = ANY($1)"#,
134- .check()?;161+ keys,
135- Ok(result.take::<Vec<Course>>(0)?)162+ )
163+ .fetch_all(db)
164+ .await?;
165+ Ok(rows)
136 }166 }
137 167
138 /// Request-scoped: `teachers` is written by [`assign_teacher`],168 /// Request-scoped: `teachers` is written by [`assign_teacher`],
@@ -160,19 +190,25 @@ pub async fn update(
160 // without its count. A PATCH that carried no `term_id`, or re-stated the190 // without its count. A PATCH that carried no `term_id`, or re-stated the
161 // link it already had, moves neither counter.191 // link it already had, moves neither counter.
162 let (claim, release) = term::ref_move(course.term.as_ref(), &term);192 let (claim, release) = term::ref_move(course.term.as_ref(), &term);
163- let expected = course.term.as_ref().map(TermId::record);193+ FieldUpdate::new(COURSE_TABLE, course.id.uuid())
164- FieldUpdate::new(course.id.record())194+ .set("title", title.map(|title| title.as_str().to_owned()))
165- .set("title", title)195+ .set(
166- .set("description", description)196+ "description",
167- .set("kind", kind)197+ description.map(|description| description.as_str().to_owned()),
168- .set("term", term.map(|term| term.map(|term| term.record())))198+ )
169- .set("capacity", capacity)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))
170 .refcount(205 .refcount(
171- COURSE_COUNT_FIELD,
172 "term",206 "term",
173- expected,207+ "course_count",
174- claim,208+ "term",
175- release,209+ course.term.as_ref().map(|term| term.uuid()),
210+ claim.map(|term| term.uuid()),
211+ release.map(|term| term.uuid()),
176 term::gone_error(),212 term::gone_error(),
177 )213 )
178 .run::<Course>(db)214 .run::<Course>(db)
@@ -184,8 +220,9 @@ pub async fn update(
184 /// Field-scoped, and the new list is folded server-side out of the *stored*220 /// Field-scoped, and the new list is folded server-side out of the *stored*
185 /// one: a course PATCH awaits a term lookup between its read and its write,221 /// one: a course PATCH awaits a term lookup between its read and its write,
186 /// so a whole-row save from either side would revert the other. The222 /// so a whole-row save from either side would revert the other. The
187-/// `array::distinct` keeps the assignment idempotent even when two requests223+/// `array_agg(DISTINCT …)` keeps the assignment idempotent even when two
188-/// name the same teacher at once (the early return only sees a stale row).224+/// requests name the same teacher at once (the early return only sees a
225+/// stale row).
189 pub async fn assign_teacher(226 pub async fn assign_teacher(
190 db: &Database,227 db: &Database,
191 course: Course,228 course: Course,
@@ -194,20 +231,19 @@ pub async fn assign_teacher(
194 if course.is_assigned(teacher) {231 if course.is_assigned(teacher) {
195 return Ok(course);232 return Ok(course);
196 }233 }
197- let mut result = db234+ let updated = sqlx::query_as!(
198- .query(235+ Course,
199- "UPDATE $id SET teachers = array::distinct(array::append(teachers, $usr))236+ r#"UPDATE course
200- RETURN AFTER",237+ SET teachers = (SELECT array_agg(DISTINCT x)
201- )238+ FROM unnest(course.teachers || $2) AS x)
202- .bind(("id", course.id.record()))239+ WHERE id = $1
203- .bind(("usr", teacher.record()))240+ RETURNING id, creator, teachers, title, description, kind, term, capacity"#,
204- .await?241+ course.id,
205- .check()?;242+ teacher,
206- result243+ )
207- .take::<Vec<Course>>(0)?244+ .fetch_optional(db)
208- .into_iter()245+ .await?;
209- .next()246+ updated.ok_or(AppError::NotFound)
210- .ok_or(AppError::NotFound)
211 }247 }
212 248
213 /// Drop `teacher` from this course. `None` when they weren't assigned, so249 /// Drop `teacher` from this course. `None` when they weren't assigned, so
@@ -220,30 +256,32 @@ pub async fn unassign_teacher(
220 if !course.is_assigned(teacher) {256 if !course.is_assigned(teacher) {
221 return Ok(None);257 return Ok(None);
222 }258 }
223- // Same field-scoped story as [`assign_teacher`]; `-=` drops the259+ // Same field-scoped story as [`assign_teacher`]; `array_remove` drops
224- // one link off the stored list without touching the course's own text.260+ // the one link off the stored list without touching the course's own
225- let mut result = db261+ // text.
226- .query("UPDATE $id SET teachers -= $usr RETURN AFTER")262+ let updated = sqlx::query_as!(
227- .bind(("id", course.id.record()))263+ Course,
228- .bind(("usr", teacher.record()))264+ r#"UPDATE course SET teachers = array_remove(teachers, $2)
229- .await?265+ WHERE id = $1
230- .check()?;266+ RETURNING id, creator, teachers, title, description, kind, term, capacity"#,
231- Ok(Some(267+ course.id,
232- result268+ teacher,
233- .take::<Vec<Course>>(0)?269+ )
234- .into_iter()270+ .fetch_optional(db)
235- .next()271+ .await?;
236- .ok_or(AppError::NotFound)?,272+ Ok(updated)
237- ))
238 }273 }
239 274
240 /// Strip `user` from every course they were assigned to β€” the sweep for a275 /// Strip `user` from every course they were assigned to β€” the sweep for a
241 /// user demoted below `teacher`, who may no longer run anything.276 /// user demoted below `teacher`, who may no longer run anything.
242 pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {277 pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {
243- db.query("UPDATE course SET teachers -= $usr WHERE $usr IN teachers")278+ sqlx::query!(
244- .bind(("usr", user.record()))279+ r#"UPDATE course SET teachers = array_remove(teachers, $1)
245- .await?280+ WHERE $1 = ANY(teachers)"#,
246- .check()?;281+ user,
282+ )
283+ .execute(db)
284+ .await?;
247 Ok(())285 Ok(())
248 }286 }
249 287
@@ -261,111 +299,233 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App
261 /// **Bank templates** survive it β€” they are a separate, reusable library299 /// **Bank templates** survive it β€” they are a separate, reusable library
262 /// spanning every course β€” so their `source_exam` and `subject` links are300 /// spanning every course β€” so their `source_exam` and `subject` links are
263 /// cleared instead, in this same transaction, exactly as301 /// cleared instead, in this same transaction, exactly as
264-/// [`crate::db::exam::delete`] and302+/// [`crate::db::exam::delete`] and [`crate::db::subject::delete`]
265-/// [`crate::db::subject::delete`] clear them one level down.303+/// clear them one level down. Deleting a course must leave the bank where
266-/// Deleting a course must leave the bank where deleting each of its exams304+/// deleting each of its exams and subjects by hand would have left it, or
267-/// and subjects by hand would have left it, or a template is left pointing305+/// a template is left pointing at a dead exam (permanently: nothing else
268-/// at a dead exam (permanently: nothing else ever visits that column) and306+/// ever visits that column) and at a dead subject the next `PATCH`
269-/// at a dead subject the next `PATCH` omitting `subject_id` writes straight307+/// omitting `subject_id` writes straight back.
270-/// back.
271 ///308 ///
272 /// The **grade blueprints** naming it are swept in that same transaction.309 /// The **grade blueprints** naming it are swept in that same transaction.
273 /// Nothing else can reach them β€” a blueprint holds its courses as a list on310 /// Nothing else can reach them β€” a blueprint holds its courses as a list on
274 /// its own row, not as link rows this cascade could delete β€” and an id left311 /// its own row, not as link rows this cascade could delete β€” and an id left
275 /// behind is permanent rather than merely stale: the pump's own312 /// behind is permanent rather than merely stale: the pump's own
276-/// [`crate::db::class_blueprint::prune`] fires only313+/// [`crate::db::class_blueprint::prune`] fires only while walking a
277-/// while walking a section, so a grade with no sections can never drop one,314+/// section, so a grade with no sections can never drop one, and every
278-/// and every `PATCH` of that template is refused for naming a course that315+/// `PATCH` of that template is refused for naming a course that does not
279-/// does not exist, which is precisely the call documented as the repair.316+/// exist, which is precisely the call documented as the repair. A dozen-row
317+/// table scanned unindexed, deliberately: a course delete is rare.
280 ///318 ///
281-/// It is a table scan, deliberately unindexed: `class_blueprint` holds one319+/// The **derived AI rows** (`rag_output` carries a denormalized `course`
282-/// row per grade label the school uses (a dozen), a course delete is rare,320+/// besides its note link) and the event **audience links** are FK children
283-/// and the per-element index the `WHERE` would want321+/// the old store let dangle: `rag_output` is disposable and dies here, and
284-/// (`FIELDS courses[*]`) is the one this store answers with **no rows at322+/// an event whose audience was "this course's students" keeps standing with
285-/// all** β€” the trap [`list_for_teacher`] documents.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).
286 ///326 ///
287 /// The marks going with it give their exam kinds' references back, counted327 /// The marks going with it give their exam kinds' references back, counted
288 /// per kind inside this same transaction β€” the mirror of `Exam::delete`.328 /// per kind inside this same transaction β€” the mirror of `Exam::delete`.
289 /// Skipping it would leave every kind the course graded under counted329 /// Skipping it would leave every kind the course graded under counted
290 /// forever, and a counted kind can never leave the school's settings.330 /// forever, and a counted kind can never leave the school's settings.
291 ///331 ///
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+///
292 /// `false` = refused, nothing was written: someone is still enrolled. The341 /// `false` = refused, nothing was written: someone is still enrolled. The
293-/// roster is read off the course's own `enrollment_count`, so the check and342+/// guard locks the course row (`FOR UPDATE`) and reads its own
294-/// the delete are one conditional write on one record β€” an enroll racing343+/// `enrollment_count`, so an enroll racing this either takes its seat
295-/// this either takes its seat first (and the delete is refused) or finds344+/// first (and the delete is refused) or finds the row gone (and is refused
296-/// the row gone (and is refused itself). `Err(NotFound)`345+/// itself). `Err(NotFound)` keeps the answer a concurrent *delete* used
297-/// keeps the answer a concurrent *delete* used to get.346+/// to get β€” and unlike the old one-statement guard, this one tells the two
347+/// apart without a second read.
298 pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {348 pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
299- let sql = format!(349+ tx_with_retry(db, true, async |tx| {
300- "BEGIN TRANSACTION;350+ // The guard and the lock: the row (and its roster count) cannot
301- LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);351+ // change under this transaction, and every enroll claim contends on
302- IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }};352+ // this very row, so check and cascade are one decision.
303- FOR $row IN $gone {{353+ let guard = sqlx::query!(
304- IF $row.term != NONE {{354+ r#"SELECT enrollment_count, term FROM course WHERE id = $1 FOR UPDATE"#,
305- UPDATE $row.term SET {COURSE_COUNT_FIELD} = \355+ course.id,
306- math::max([({COURSE_COUNT_FIELD} ?? 0) - 1, 0]);356+ )
307- }};357+ .fetch_optional(&mut *tx)
308- }};358+ .await?;
309- FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result359+ let Some(guard) = guard else {
310- WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)360+ return Err(AppError::NotFound);
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),
363 };361 };
364- }362+ if guard.enrollment_count != 0 {
365- if let Some(error) = errors.drain().map(|(_, error)| error).next() {363+ return Ok(false);
366- return Err(error.into());364+ }
367- }365+ // The exam ids are needed twice β€” the kind_ref refund and the bank's
368- Ok(true)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
369 }529 }
370 530
371 /// A real course row, for the tests of every child that must now prove its531 /// 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 @@
1 //! The `course_session` table: reads, a course's timetable listing, the1 //! The `course_session` table: reads, a course's timetable listing, the
2 //! request-scoped field update, and the delete that sweeps roll-call rows in2 //! request-scoped field update, and the delete that sweeps roll-call rows in
3-//! one transaction. Creation writes the course row through3+//! one transaction. Creation stands on the course foreign key, so a lesson
4-//! [`cap::touch_and_create`] so a lesson can never outlive its course; the4+//! can never outlive its course; the web-facing doors and the
5-//! web-facing doors and the teacher-resolution rule live in5+//! teacher-resolution rule live in [`crate::service::course_session`].
6-//! [`crate::service::course_session`].
7 6
8-use surrealdb::types::SurrealValue;7+use crate::constant::COURSE_SESSION_TABLE;
9-8+use crate::database::{Database, foreign_key_violation, tx_with_retry};
10-use crate::constant::ENROLLMENT_COUNT_FIELD;
11-use crate::database::{Database, transaction_with_retry};
12-use crate::db::cap;
13 use crate::db::field_update::FieldUpdate;9 use crate::db::field_update::FieldUpdate;
14 use crate::db::page::PagedList;10 use crate::db::page::PagedList;
15 use crate::domain::course::CourseId;11 use crate::domain::course::CourseId;
@@ -34,23 +30,44 @@ pub async fn create(
34 starts_at,30 starts_at,
35 ends_at,31 ends_at,
36 };32 };
37- // The course row is *written* (bumped and put back), not read, so this33+ // The course foreign key is the existence proof the old bump-and-restore
38- // collides with `Course::delete`'s cascade: a lesson that outlives its34+ // "touch" trick faked: a lesson whose course is already gone β€” or which
39- // course 404s through `session_with_course` forever β€” unreadable,35+ // is deleted while this insert is in flight β€” is refused here, so a
40- // unpatchable, undeletable. See [`cap::touch_and_create`].36+ // lesson can never outlive its course and 404 through
41- cap::touch_and_create(37+ // `session_with_course` forever β€” unreadable, unpatchable, undeletable.
42- &course.record(),38+ // `23503` is the parent-gone refusal, the same answer the touch
43- ENROLLMENT_COUNT_FIELD,39+ // produced.
44- &session.id.record(),40+ let created = sqlx::query_as!(
45- &session,41+ CourseSession,
46- db,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,
47 )51 )
48- .await?52+ .fetch_one(db)
49- .ok_or(AppError::NotFound)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+ }
50 }59 }
51 60
52 pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> {61 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)
54 }71 }
55 72
56 /// A course's sessions, most recent lesson first. Ordered by `starts_at`73 /// A course's sessions, most recent lesson first. Ordered by `starts_at`
@@ -63,11 +80,11 @@ pub async fn list_for_course(
63 offset: i64,80 offset: i64,
64 ) -> Result<(Vec<CourseSession>, i64), AppError> {81 ) -> Result<(Vec<CourseSession>, i64), AppError> {
65 PagedList::new(82 PagedList::new(
66- "course_session WHERE course = $course",83+ "course_session WHERE course = $1",
67 "ORDER BY starts_at DESC, id DESC",84 "ORDER BY starts_at DESC, id DESC",
68 )85 )
69- .bind("course", course.record())86+ .bind(course.uuid())
70- .run(limit, offset, db)87+ .run::<CourseSession>(limit, offset, db)
71 .await88 .await
72 }89 }
73 90
@@ -86,11 +103,17 @@ pub async fn update(
86 starts_at: Option<Timestamp>,103 starts_at: Option<Timestamp>,
87 ends_at: Option<Option<Timestamp>>,104 ends_at: Option<Option<Timestamp>>,
88 ) -> Result<CourseSession, AppError> {105 ) -> Result<CourseSession, AppError> {
89- FieldUpdate::new(session.id.record())106+ FieldUpdate::new(COURSE_SESSION_TABLE, session.id.uuid())
90- .set("teacher", teacher.map(|teacher| teacher.record()))107+ .set(
91- .set("topic", topic)108+ "teacher",
92- .set("starts_at", starts_at)109+ teacher.map(|teacher| crate::db::page::Param::Uuid(teacher.uuid())),
93- .set("ends_at", ends_at)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+ )
94 .ordered("starts_at", "ends_at", range_error())117 .ordered("starts_at", "ends_at", range_error())
95 .run::<CourseSession>(db)118 .run::<CourseSession>(db)
96 .await119 .await
@@ -99,32 +122,31 @@ pub async fn update(
99 /// Delete the session and cascade-remove its roll-call rows, in one122 /// Delete the session and cascade-remove its roll-call rows, in one
100 /// transaction: as two unbatched queries a failure between them stranded123 /// transaction: as two unbatched queries a failure between them stranded
101 /// roll-call rows on a session that was already gone. The other half of124 /// roll-call rows on a session that was already gone. The other half of
102-/// that invariant is [`crate::db::session_attendance::mark`],125+/// that invariant is [`crate::db::session_attendance::mark`], whose
103-/// which proves the session still exists inside its own write β€” a126+/// session-row lock makes a mark and this delete take turns β€” a mark
104-/// transaction here cannot stop a mark that commits *after* this one.127+/// committing after this cascade cannot name a session that is gone.
105 pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> {128 pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> {
106- let (mut result, mut errors) = transaction_with_retry(129+ tx_with_retry(db, false, async |tx| {
107- db,130+ // Roll-call rows first: the session row's own FK would refuse the
108- "BEGIN TRANSACTION;131+ // delete while they exist. An empty first sweep is fine β€” the
109- DELETE session_attendance WHERE session = $s;132+ // session may simply have had none.
110- LET $before = (DELETE $s RETURN BEFORE);133+ sqlx::query!(
111- RETURN $before;134+ r#"DELETE FROM session_attendance WHERE session = $1"#,
112- COMMIT TRANSACTION;",135+ session.id,
113- &[("s".into(), session.id.record().into_value())],136+ )
114- // No THROW of its own β€” an unconditional cascade, so the only137+ .execute(&mut *tx)
115- // error worth telling apart is a lost round (see138+ .await?;
116- // [`crate::db::exam::delete`]).139+ let deleted = sqlx::query_as!(
117- &[],140+ CourseSession,
118- )141+ r#"DELETE FROM course_session WHERE id = $1
119- .await?;142+ RETURNING id, course, teacher, topic, starts_at, ends_at"#,
120- if let Some(error) = errors.drain().map(|(_, error)| error).next() {143+ session.id,
121- return Err(error.into());144+ )
122- }145+ .fetch_optional(&mut *tx)
123- // Read through the trailing `RETURN`, never a hand-counted slot.146+ .await?;
124- let slot = result.num_statements().saturating_sub(2);147+ deleted.ok_or(AppError::NotFound)
125- let deleted: Option<CourseSession> =148+ })
126- result.take::<Vec<CourseSession>>(slot)?.into_iter().next();149+ .await
127- deleted.ok_or(AppError::NotFound)
128 }150 }
129 151
130 #[cfg(test)]152 #[cfg(test)]
src/db/enrollment.rsmodified+170 -170
@@ -1,49 +1,55 @@
1 //! The `enrollment` table: the roster read and listing, the seat-returning1 //! The `enrollment` table: the roster read and listing, the seat-returning
2-//! delete, and the enroll claim β€” the one transaction that checks the pair2+//! delete, and the enroll claim β€” one transaction that checks the pair free,
3-//! free, the member still a student, and the roster under capacity while it3+//! the member still a student, and the roster under capacity while it
4 //! spends the seat. The target-user gates the HTTP handlers pay live in4 //! spends the seat. The target-user gates the HTTP handlers pay live in
5 //! [`crate::service::enrollment`].5 //! [`crate::service::enrollment`].
6 6
7-use surrealdb::types::SurrealValue;7+use crate::database::{Database, tx_with_retry, unique_violation};
8-
9-use crate::constant::ENROLLMENT_COUNT_FIELD;
10-use crate::database::{Database, transaction_with_retry};
11 use crate::db::cap;8 use crate::db::cap;
12 use crate::db::page::PagedList;9 use crate::db::page::PagedList;
13 use crate::domain::course::CourseId;10 use crate::domain::course::CourseId;
14-use crate::domain::enrollment::{Enrollment, EnrollmentId};11+use crate::domain::enrollment::Enrollment;
15 use crate::domain::role::Role;12 use crate::domain::role::Role;
16 use crate::domain::user::UserId;13 use crate::domain::user::UserId;
17 use crate::error::{AppError, ValidationError};14 use crate::error::{AppError, ValidationError};
18 15
19-/// The `THROW` markers [`enroll`]'s claim aborts with: this pair16+/// What [`enroll`]'s transaction settled on β€” the three old `THROW` markers
20-/// already holds a row, the roster is full, and the person being enrolled is no17+/// (`enroll_held`, `enroll_not_student`, `enroll_full`) as Rust verdicts.
21-/// longer a student.18+enum Verdict {
22-const HELD_MARK: &str = "enroll_held";19+ /// This pair already holds a row.
23-const FULL_MARK: &str = "enroll_full";20+ Held,
24-const UNFIT_MARK: &str = "enroll_not_student";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";
25 32
26-/// Enroll (idempotently) `user` into `course`. One row per (course, user),33+/// Enroll (idempotently) `user` into `course`. The table's primary key *is*
27-/// keyed by a deterministic composite id, so concurrent enrolls of the same34+/// the (course, user) pair, so concurrent enrolls of the same pair converge
28-/// pair converge on one row instead of racing the unique index into a 500:35+/// on one row instead of racing into a 500: the loser reads the winner's row
29-/// the loser of the `CREATE` reads the winner's row back and returns it.36+/// back and returns it. When the course carries a capacity, a full roster
30-/// When the course carries a capacity, a full roster refuses new members37+/// refuses new members (409) β€” the seat is taken by a single-record
31-/// (409) β€” the seat is taken by a single-record conditional write on the38+/// conditional write on the course row whose bound is the row's *own*
32-/// course row whose bound is the row's *own* `capacity` column, read inside39+/// `capacity` column, read inside the same statement that spends the seat. A
33-/// the same statement that spends the seat. A snapshot integer taken by a40+/// snapshot integer taken by a read beforehand would be exactly the number a
34-/// read beforehand would be exactly the number a concurrent capacity PATCH41+/// concurrent capacity PATCH invalidates. An already enrolled user is
35-/// invalidates, which is what this promised and did not do. An already42+/// returned as-is even when the roster is full, and never charged a seat.
36-/// enrolled user is returned as-is even when the roster is full, and never43+/// The same claim is the delete guard's other half: it matches nothing once
37-/// charged a seat. The same claim is the delete guard's other half: it44+/// the course row is gone, and while it holds a seat the course cannot be
38-/// matches nothing once the course row is gone, and while it holds a seat45+/// deleted β€” so no roster row can outlive its course.
39-/// the course cannot be deleted β€” so no roster row can outlive its course.
40 ///46 ///
41-/// On admissibility ([`crate::database::transaction_with_retry`]): the47+/// Gate order is the old THROW order: an existing pair outranks the role
42-/// `CREATE` here *can* answer "already exists", but only to a rival that48+/// check, which outranks a full roster. The role check takes the user row
43-/// landed inside this very window β€” and the re-send then sees that row at49+/// `FOR NO KEY UPDATE`, the same row a demotion cascade updates before its
44-/// the `$held` gate and takes the other branch, so the loop converges50+/// sweep, so grant and demotion serialize on the row lock in both
45-/// instead of re-asking a settled question. Same shape, same reason, as51+/// directions β€” a row landing after the sweep is impossible, and a demotion
46-/// [`crate::db::class_pump::attach`].52+/// landing before this check refuses it.
47 pub async fn enroll(53 pub async fn enroll(
48 db: &Database,54 db: &Database,
49 course: &CourseId,55 course: &CourseId,
@@ -53,112 +59,89 @@ pub async fn enroll(
53 if let Some(existing) = read_for_user(db, course, user).await? {59 if let Some(existing) = read_for_user(db, course, user).await? {
54 return disown_if_pumped(db, existing).await;60 return disown_if_pumped(db, existing).await;
55 }61 }
56- let enrollment = Enrollment {62+ let verdict = tx_with_retry(db, false, async |tx| {
57- id: EnrollmentId::composite(course, user),63+ // The duplicate gate rides ahead of the role check, so "you are
58- course: course.clone(),64+ // already in" still outranks everything.
59- user: user.clone(),65+ let held = sqlx::query!(
60- enrolled_by: enrolled_by.clone(),66+ r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#,
61- // Hand-placed: no source key at all is written, which is what makes67+ course,
62- // a class sweep unable to take this row back.68+ user,
63- source: None,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,
64 };123 };
65- // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has124+ match verdict {
66- // to be *seen*, or the pair's second writer would keep the seat it125+ Ok(Verdict::Made(row)) => Ok(row),
67- // claimed for a row that already existed and the counter would drift126+ Ok(Verdict::Held) => match read_for_user(db, course, user).await? {
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 Some(existing) => disown_if_pumped(db, existing).await,127 Some(existing) => disown_if_pumped(db, existing).await,
125 None => Err(AppError::Internal("failed to enroll user".into())),128 None => Err(AppError::Internal("failed to enroll user".into())),
126- };129+ },
127- }130+ // Demoted while this ran: the same refusal the service's own gate
128- // Demoted while this ran: the same refusal the service's own gate makes131+ // makes a moment earlier, and the only one that can arrive after it.
129- // a moment earlier, and the only one that can arrive after it.132+ Ok(Verdict::Unfit) => Err(AppError::Validation(ValidationError::Invalid {
130- if errors
131- .values()
132- .any(|error| error.to_string().contains(UNFIT_MARK))
133- {
134- return Err(AppError::Validation(ValidationError::Invalid {
135 field: "user_id",133 field: "user_id",
136 reason: "only students can be enrolled in a course",134 reason: "only students can be enrolled in a course",
137- }));135+ })),
138- }136+ // Full, or the course is gone β€” the conditional write matches
139- // Full, or the course is gone β€” the conditional write matches nothing137+ // nothing either way, and only this path pays for the read that
140- // either way, and only this path pays for the read that tells them138+ // tells them apart.
141- // apart.139+ Ok(Verdict::Full) => match crate::db::course::read(db, course).await? {
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? {
147 Some(_) => Err(AppError::Conflict("the course is full")),140 Some(_) => Err(AppError::Conflict("the course is full")),
148 None => Err(AppError::NotFound),141 None => Err(AppError::NotFound),
149- };142+ },
150- }143+ Err(err) => Err(err),
151- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
152- return Err(error.into());
153 }144 }
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()))
162 }145 }
163 146
164 /// A hand enroll landing on a row a class pumped takes the row *off* the147 /// A hand enroll landing on a row a class pumped takes the row *off* the
@@ -167,28 +150,30 @@ pub async fn enroll(
167 /// holds in the other direction β€” a manual unenroll wins, permanently β€” and150 /// holds in the other direction β€” a manual unenroll wins, permanently β€” and
168 /// without it "hand-placed" was a state only a first enroll could reach.151 /// without it "hand-placed" was a state only a first enroll could reach.
169 ///152 ///
170-/// `UNSET`, not `= NONE`: absence *is* the meaning of this column (see the153+/// `NULL`, not absence: the column is a nullable uuid whose NULL *is* the
171-/// struct doc), and it is what a hand enroll writes on the create path.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.
172 async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result<Enrollment, AppError> {156 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() {
174 return Ok(existing);158 return Ok(existing);
175 }159 }
176- let mut result = db160+ let disowned = sqlx::query_as!(
177- .query("UPDATE $id UNSET source RETURN AFTER")161+ Enrollment,
178- .bind(("id", existing.id.record()))162+ r#"UPDATE enrollment SET source = NULL
179- .await?163+ WHERE course = $1 AND app_user = $2
180- .check()?;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?;
181 // A row that is no longer there is not an internal error: an unenroll170 // A row that is no longer there is not an internal error: an unenroll
182 // (or the class sweep a role change runs) landing between the read171 // (or the class sweep a role change runs) landing between the read
183 // above and this write matches nothing, and the caller asked to be172 // above and this write matches nothing, and the caller asked to be
184 // enrolled β€” which they were, by the row this call was handed. The173 // enrolled β€” which they were, by the row this call was handed. The
185 // disown is all that is lost, and it is lost to a delete that took the174 // disown is all that is lost, and it is lost to a delete that took the
186 // whole row with it.175 // whole row with it.
187- Ok(result176+ Ok(disowned.unwrap_or(existing))
188- .take::<Vec<Enrollment>>(0)?
189- .into_iter()
190- .next()
191- .unwrap_or(existing))
192 }177 }
193 178
194 /// Some(_) iff `user` is enrolled in `course` β€” the grading gate.179 /// Some(_) iff `user` is enrolled in `course` β€” the grading gate.
@@ -197,13 +182,16 @@ pub async fn read_for_user(
197 course: &CourseId,182 course: &CourseId,
198 user: &UserId,183 user: &UserId,
199 ) -> Result<Option<Enrollment>, AppError> {184 ) -> Result<Option<Enrollment>, AppError> {
200- let mut result = db185+ let row = sqlx::query_as!(
201- .query("SELECT * FROM enrollment WHERE course = $course AND user = $usr LIMIT 1")186+ Enrollment,
202- .bind(("course", course.record()))187+ r#"SELECT course, app_user AS "user", enrolled_by, source
203- .bind(("usr", user.record()))188+ FROM enrollment WHERE course = $1 AND app_user = $2"#,
204- .await?189+ course,
205- .check()?;190+ user,
206- Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next())191+ )
192+ .fetch_optional(db)
193+ .await?;
194+ Ok(row)
207 }195 }
208 196
209 pub async fn list_for_course(197 pub async fn list_for_course(
@@ -212,32 +200,44 @@ pub async fn list_for_course(
212 limit: Option<i64>,200 limit: Option<i64>,
213 offset: i64,201 offset: i64,
214 ) -> Result<(Vec<Enrollment>, i64), AppError> {202 ) -> Result<(Vec<Enrollment>, i64), AppError> {
215- PagedList::new("enrollment WHERE course = $course", "ORDER BY id DESC")203+ // The old composite key `{course}_{user}` sorted by user within a
216- .bind("course", course.record())204+ // course β€” its course prefix was constant β€” so the natural-PK columns
217- .run(limit, offset, db)205+ // sort the same way.
218- .await206+ 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
219 }213 }
220 214
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.
221 pub async fn remove(217 pub async fn remove(
222 db: &Database,218 db: &Database,
223 course: &CourseId,219 course: &CourseId,
224 user: &UserId,220 user: &UserId,
225 ) -> Result<Option<Enrollment>, AppError> {221 ) -> Result<Option<Enrollment>, AppError> {
226- // The seat comes back in the same transaction as the row that held it,222+ let gone = sqlx::query_as!(
227- // so nothing but a lost transaction can drift the counter.223+ Enrollment,
228- let mut result = db224+ r#"WITH gone AS (
229- .query(225+ DELETE FROM enrollment
230- "BEGIN TRANSACTION;226+ WHERE course = $1 AND app_user = $2
231- LET $gone = (DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE);227+ RETURNING course, app_user, enrolled_by, source),
232- UPDATE $course SET enrollment_count = math::max([(enrollment_count ?? 0) - array::len($gone), 0]);228+ seated AS (
233- RETURN $gone;229+ UPDATE course
234- COMMIT TRANSACTION;",230+ SET enrollment_count = GREATEST(
235- )231+ enrollment_count - (SELECT count(*) FROM gone), 0)
236- .bind(("course", course.record()))232+ WHERE id = $1
237- .bind(("usr", user.record()))233+ RETURNING 1)
238- .await?234+ SELECT course, app_user AS "user", enrolled_by, source FROM gone"#,
239- .check()?;235+ course,
240- Ok(result.take::<Vec<Enrollment>>(3)?.into_iter().next())236+ user,
237+ )
238+ .fetch_optional(db)
239+ .await?;
240+ Ok(gone)
241 }241 }
242 242
243 #[cfg(test)]243 #[cfg(test)]
src/db/session_attendance.rsmodified+193 -185
@@ -4,60 +4,30 @@
4 //! management's, only students attend, enrollment) are4 //! management's, only students attend, enrollment) are
5 //! [`crate::service::session_attendance`]'s to judge before calling here.5 //! [`crate::service::session_attendance`]'s to judge before calling here.
6 6
7-use surrealdb::types::SurrealValue;7+use crate::database::{Database, tx_with_retry};
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};
13 use crate::db::page::PagedList;8 use crate::db::page::PagedList;
14 use crate::domain::attendance::AttendanceStatus;9 use crate::domain::attendance::AttendanceStatus;
15 use crate::domain::course_session::{CourseSession, CourseSessionId};10 use crate::domain::course_session::{CourseSession, CourseSessionId};
16-use crate::domain::session_attendance::{11+use crate::domain::session_attendance::SessionAttendance;
17- SessionAttendance, SessionAttendanceId, counts_as_attended,
18-};
19 use crate::domain::timestamp::Timestamp;12 use crate::domain::timestamp::Timestamp;
20 use crate::domain::user::UserId;13 use crate::domain::user::UserId;
21 use crate::error::AppError;14 use crate::error::AppError;
22 15
23-/// Record (or overwrite) `user`'s status for the session. One row per16+/// Record (or overwrite) `user`'s status for the session. The table's
24-/// (session, user), keyed by a deterministic composite id so this is a17+/// primary key *is* the (session, user) pair, so the mark is a single
25-/// single atomic UPSERT β€” concurrent marks converge on the one row.18+/// 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.
55 ///19 ///
56-/// Sound to re-send while the store answers "conflict, retry": the gate20+/// The "session still exists" gate is a row lock: the transaction takes the
57-/// reads the record a delete writes, so the two contend by design, and the21+/// session row `FOR NO KEY UPDATE` before anything else, so a session (or
58-/// UPSERT cannot legitimately answer "already exists" β€” its composite id is22+/// course) delete cascading beneath this mark simply waits, and a delete
59-/// bijective with the `session_attendance_session_user` unique tuple, so23+/// that got there first leaves this gate matching nothing β€” `404`, the
60-/// the index entry can only point at the row the id already names.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.
61 ///31 ///
62 /// Two badge counters move in this same transaction, both of them read32 /// Two badge counters move in this same transaction, both of them read
63 /// from the store rather than taken on the caller's word:33 /// from the store rather than taken on the caller's word:
@@ -65,27 +35,27 @@ use crate::error::AppError;
65 /// - `lessons_attended_total`, on the person marked, as a *delta* rather35 /// - `lessons_attended_total`, on the person marked, as a *delta* rather
66 /// than an increment, because this is an upsert: a re-mark that changes36 /// than an increment, because this is an upsert: a re-mark that changes
67 /// nothing must change nothing, and a teacher's correction must move it37 /// nothing must change nothing, and a teacher's correction must move it
68-/// back down. `$was` is read before the upsert overwrites it (`NONE` when38+/// back down. The pair's stored status is read before the upsert
69-/// the pair has no row yet), so it writes only on a real crossing of the39+/// overwrites it (`None` when the pair has no row yet), so it writes
70-/// attended line, and only for a **student** β€” attending lessons is a40+/// only on a real crossing of the attended line, and only for a
71-/// student's badge, the same student-only rule enrolling and sitting an41+/// **student** β€” attending lessons is a student's badge, the same
72-/// exam already carry, so a teacher marked present in their own lesson42+/// student-only rule enrolling and sitting an exam already carry, so a
73-/// moves it in neither direction. The live `role` decides that, not the43+/// teacher marked present in their own lesson moves it in neither
74-/// role someone held when the row was written.44+/// direction. The live `role` decides that, not the role someone held
45+/// when the row was written.
75 /// - `lessons_held_total`, on the *session's* teacher, exactly once per46 /// - `lessons_held_total`, on the *session's* teacher, exactly once per
76-/// session: the first roll call taken stamps47+/// session: the first roll call taken stamps `held_counted_at` on the
77-/// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees48+/// lesson and every later mark sees the stamp and credits nothing. It
78-/// the stamp and credits nothing. It counts lessons that actually49+/// counts lessons that actually happened β€” scheduling one and
79-/// happened β€” scheduling one and cancelling it earns nothing, which is50+/// cancelling it earns nothing, which is why the credit does not live
80-/// why the credit does not live in `crate::db::course_session::create`. Two51+/// in `crate::db::course_session::create`. Two simultaneous first
81-/// simultaneous first marks both write the lesson row, so the store's own52+/// marks serialize on the session row's lock, so the stamp cannot be
82-/// conflict detection (and `transaction_with_retry` behind it) is what53+/// set twice.
83-/// keeps the stamp from being set twice.
84 ///54 ///
85 /// "Actually happened" is a clock reading, not a request count: the55 /// "Actually happened" is a clock reading, not a request count: the
86 /// credit waits for the lesson's own `starts_at` to arrive. Roll call is56 /// 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 and57+/// deliberately *not* time-gated β€” a teacher may open the sheet early
88-/// is never refused β€” so without this a teacher could schedule two58+/// and is never refused β€” so without this a teacher could schedule two
89 /// hundred lessons for next week, mark one student in each, and hold two59 /// hundred lessons for next week, mark one student in each, and hold two
90 /// hundred lessons this afternoon. Because the stamp is written only on60 /// hundred lessons this afternoon. Because the stamp is written only on
91 /// the branch that credits, a sheet opened early and touched again after61 /// the branch that credits, a sheet opened early and touched again after
@@ -100,9 +70,6 @@ use crate::error::AppError;
100 /// credited β€” a student's real lessons eaten by someone else's farm. It70 /// credited β€” a student's real lessons eaten by someone else's farm. It
101 /// is also nobody's self-service: only a teacher can mark a student, so71 /// is also nobody's self-service: only a teacher can mark a student, so
102 /// the counter cannot be moved by the person it decorates.72 /// 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.
106 //73 //
107 // corner-cut: that asymmetry leaves a teacher able to inflate a *student's*74 // corner-cut: that asymmetry leaves a teacher able to inflate a *student's*
108 // attendance with future-dated lessons. Closing it needs the credit stamped75 // attendance with future-dated lessons. Closing it needs the credit stamped
@@ -117,76 +84,94 @@ pub async fn mark(
117 status: AttendanceStatus,84 status: AttendanceStatus,
118 marked_by: &UserId,85 marked_by: &UserId,
119 ) -> Result<SessionAttendance, AppError> {86 ) -> Result<SessionAttendance, AppError> {
120- let attended = counts_as_attended(&status);87+ let attended = crate::domain::session_attendance::counts_as_attended(&status);
121 let delta: i64 = if attended { 1 } else { -1 };88 let delta: i64 = if attended { 1 } else { -1 };
122- let attendance = SessionAttendance {89+ let now = Timestamp::now();
123- id: SessionAttendanceId::composite(session.get_id(), user),90+ tx_with_retry(db, false, async |tx| {
124- session: session.get_id().clone(),91+ // The gate and the serialization point: a live session row, locked
125- course: session.get_course().clone(),92+ // against the delete cascade and every rival mark.
126- user: user.clone(),93+ let sess = sqlx::query!(
127- status,94+ r#"SELECT teacher, starts_at, held_counted_at
128- marked_by: marked_by.clone(),95+ FROM course_session WHERE id = $1 FOR NO KEY UPDATE"#,
129- };96+ session.id,
130- let (mut written, mut errors) = transaction_with_retry(97+ )
131- db,98+ .fetch_optional(&mut *tx)
132- &format!(99+ .await?;
133- "BEGIN TRANSACTION;100+ let Some(sess) = sess else {
134- LET $teacher = (SELECT VALUE teacher FROM ONLY $sess);101+ return Err(AppError::NotFound);
135- IF $teacher IS NONE {{ THROW 'session_missing' }};102+ };
136- LET $counted = (SELECT VALUE {LESSON_COUNTED_AT_FIELD} FROM ONLY $sess);103+ // The pair's stored status β€” the pre-image the attended delta is
137- LET $begun = ((SELECT VALUE starts_at FROM ONLY $sess) <= $stamp);104+ // computed off.
138- LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');105+ let was = sqlx::query!(
139- LET $was = ((SELECT VALUE status FROM ONLY $id) IN ['present', 'late']);106+ r#"SELECT status FROM session_attendance
140- LET $after = (UPSERT $id CONTENT $row RETURN AFTER);107+ WHERE session = $1 AND app_user = $2"#,
141- IF $student AND $was != $now {{108+ session.id,
142- UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =109+ user,
143- math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0])110+ )
144- }};111+ .fetch_optional(&mut *tx)
145- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = ({LESSON_COUNTED_AT_FIELD} ?? 0) + 1;112+ .await?
146- IF ($counted IS NONE) AND $begun {{113+ .map(|row| row.status);
147- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp;114+ // The live role of the person marked (a gone user row marks as
148- UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} =115+ // non-student β€” no badge to move; the service gate has already
149- ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1116+ // refused a vanished target before this write ran).
150- }} ELSE {{117+ let is_student = sqlx::query!(
151- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $counted118+ r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#,
152- }};119+ user,
153- RETURN $after;120+ )
154- COMMIT TRANSACTION;"121+ .fetch_optional(&mut *tx)
155- ),122+ .await?
156- &[123+ .map(|row| row.is_student)
157- // `$session` is SurrealDB's own protected variable (the auth124+ .unwrap_or(false);
158- // session): binding that name errors the whole query.125+ let row = sqlx::query_as!(
159- ("sess".into(), session.get_id().record().into_value()),126+ SessionAttendance,
160- ("id".into(), attendance.id.record().into_value()),127+ r#"INSERT INTO session_attendance (session, app_user, course, status, marked_by)
161- ("usr".into(), user.record().into_value()),128+ VALUES ($1, $2, $3, $4, $5)
162- ("now".into(), attended.into_value()),129+ ON CONFLICT (session, app_user) DO UPDATE
163- ("delta".into(), delta.into_value()),130+ SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by
164- ("stamp".into(), Timestamp::now().into_value()),131+ RETURNING session, app_user AS "user", course, status, marked_by"#,
165- ("row".into(), attendance.into_value()),132+ session.id,
166- ],133+ user,
167- &["session_missing"],134+ session.course,
168- )135+ status,
169- .await?;136+ marked_by,
170- // An aborted transaction errors every slot and only the THROW's own137+ )
171- // slot names the marker, so a refusal is read by marker while a lost138+ .fetch_one(&mut *tx)
172- // round was already re-sent β€” never reported as a 500.139+ .await?;
173- if errors140+ // The attended badge: student-only, and only on a real crossing.
174- .values()141+ let was_attended = was
175- .any(|error| error.to_string().contains("session_missing"))142+ .as_deref()
176- {143+ .is_some_and(|was| was == "present" || was == "late");
177- return Err(AppError::NotFound);144+ if is_student && was_attended != attended {
178- }145+ sqlx::query!(
179- if let Some(error) = errors.drain().map(|(_, error)| error).next() {146+ r#"UPDATE app_user
180- return Err(error.into());147+ SET lessons_attended_total = GREATEST(lessons_attended_total + $2, 0)
181- }148+ WHERE id = $1"#,
182- // The trailing `RETURN` is always the last statement before `COMMIT`,149+ user,
183- // so its slot follows the statement count instead of a hand-kept one.150+ delta,
184- let slot = written.num_statements().saturating_sub(2);151+ )
185- written152+ .execute(&mut *tx)
186- .take::<Vec<SessionAttendance>>(slot)?153+ .await?;
187- .into_iter()154+ }
188- .next()155+ // The held badge: once per lesson, and only once the lesson began.
189- .ok_or_else(|| AppError::Internal("failed to mark session attendance".into()))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
190 }175 }
191 176
192 pub async fn list_for_session(177 pub async fn list_for_session(
@@ -195,10 +180,16 @@ pub async fn list_for_session(
195 limit: Option<i64>,180 limit: Option<i64>,
196 offset: i64,181 offset: i64,
197 ) -> Result<(Vec<SessionAttendance>, i64), AppError> {182 ) -> Result<(Vec<SessionAttendance>, i64), AppError> {
198- PagedList::new("session_attendance WHERE session = $s", "ORDER BY id DESC")183+ // The old composite key `{session}_{user}` sorted by user within a
199- .bind("s", session.record())184+ // session β€” its session prefix was constant β€” so the natural-PK
200- .run(limit, offset, db)185+ // columns sort the same way.
201- .await186+ 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
202 }193 }
203 194
204 /// Every roll-call row ever recorded for `user` β€” the session half of the195 /// Every roll-call row ever recorded for `user` β€” the session half of the
@@ -209,12 +200,16 @@ pub async fn list_for_user(
209 db: &Database,200 db: &Database,
210 user: &UserId,201 user: &UserId,
211 ) -> Result<Vec<SessionAttendance>, AppError> {202 ) -> Result<Vec<SessionAttendance>, AppError> {
212- let mut result = db203+ let rows = sqlx::query_as!(
213- .query("SELECT * FROM session_attendance WHERE user = $usr ORDER BY id DESC")204+ SessionAttendance,
214- .bind(("usr", user.record()))205+ r#"SELECT session, app_user AS "user", course, status, marked_by
215- .await?206+ FROM session_attendance WHERE app_user = $1
216- .check()?;207+ ORDER BY session DESC, app_user DESC"#,
217- Ok(result.take::<Vec<SessionAttendance>>(0)?)208+ user,
209+ )
210+ .fetch_all(db)
211+ .await?;
212+ Ok(rows)
218 }213 }
219 214
220 /// Clearing a row the student was counted for gives the count back, in the215 /// Clearing a row the student was counted for gives the count back, in the
@@ -229,50 +224,60 @@ pub async fn list_for_user(
229 ///224 ///
230 /// Student-only on the same terms as the mark, and read from the store for225 /// Student-only on the same terms as the mark, and read from the store for
231 /// the same reason.226 /// 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.
241 pub async fn remove(227 pub async fn remove(
242 db: &Database,228 db: &Database,
243 session: &CourseSessionId,229 session: &CourseSessionId,
244 user: &UserId,230 user: &UserId,
245 ) -> Result<Option<SessionAttendance>, AppError> {231 ) -> Result<Option<SessionAttendance>, AppError> {
246- let (mut result, mut errors) = transaction_with_retry(232+ tx_with_retry(db, false, async |tx| {
247- db,233+ // The pre-image and the row's right to exist in one locked
248- &format!(234+ // statement: the row cannot vanish (or change status) under this
249- "BEGIN TRANSACTION;235+ // transaction, and `None` here is simply "nothing to remove".
250- LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');236+ let Some(gone) = sqlx::query_as!(
251- LET $gone = (DELETE session_attendance237+ SessionAttendance,
252- WHERE session = $s AND user = $usr RETURN BEFORE);238+ r#"SELECT session, app_user AS "user", course, status, marked_by
253- IF $student AND array::len($gone) > 0 AND $gone[0].status IN ['present', 'late'] {{239+ FROM session_attendance
254- UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =240+ WHERE session = $1 AND app_user = $2
255- math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) - 1, 0])241+ FOR UPDATE"#,
256- }};242+ session,
257- RETURN $gone;243+ user,
258- COMMIT TRANSACTION;"244+ )
259- ),245+ .fetch_optional(&mut *tx)
260- &[246+ .await?
261- ("s".into(), session.record().into_value()),247+ else {
262- ("usr".into(), user.record().into_value()),248+ return Ok(None);
263- ],249+ };
264- &[],250+ if crate::domain::session_attendance::counts_as_attended(&gone.status) {
265- )251+ // Student-only, live role: the same rule the mark pays.
266- .await?;252+ let student = sqlx::query!(
267- if let Some(error) = errors.drain().map(|(_, error)| error).next() {253+ r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#,
268- return Err(error.into());254+ user,
269- }255+ )
270- // The trailing `RETURN` is always the last statement before `COMMIT`.256+ .fetch_optional(&mut *tx)
271- let slot = result.num_statements().saturating_sub(2);257+ .await?
272- Ok(result258+ .map(|row| row.is_student)
273- .take::<Vec<SessionAttendance>>(slot)?259+ .unwrap_or(false);
274- .into_iter()260+ if student {
275- .next())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
276 }281 }
277 282
278 #[cfg(test)]283 #[cfg(test)]
@@ -345,7 +350,10 @@ mod tests {
345 }350 }
346 351
347 async fn held(user: &UserId, db: &Database) -> i64 {352 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()
349 }357 }
350 358
351 /// The whole transition table in one pass: an upsert may only move the359 /// 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;
11 use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};11 use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};
12 use crate::error::AppError;12 use crate::error::AppError;
13 13
14-
15 pub async fn create(14 pub async fn create(
16 db: &Database,15 db: &Database,
17 course: &CourseId,16 course: &CourseId,
src/domain/course.rsmodified+0 -7
@@ -33,14 +33,7 @@ impl CourseId {
33 pub fn key(&self) -> String {33 pub fn key(&self) -> String {
34 self.0.to_string()34 self.0.to_string()
35 }35 }
36-
37- /// The inner uuid, for binding the id through the runtime-checked
38- /// builders ([`crate::db::page::Param`]) whose values are raw uuids.
39- pub(crate) fn uuid(&self) -> uuid::Uuid {
40- self.0
41- }
42 }36 }
43-
44 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]37 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
45 #[sqlx(transparent)]38 #[sqlx(transparent)]
46 pub struct CourseTitle(String);39 pub struct CourseTitle(String);
src/domain/course_session.rsmodified+1 -8
@@ -1,4 +1,4 @@
1-use crate::constant::{MAX_SESSION_TOPIC_LEN};1+use crate::constant::MAX_SESSION_TOPIC_LEN;
2 use crate::domain::course::CourseId;2 use crate::domain::course::CourseId;
3 use crate::domain::monotonic_id::next_uuid;3 use crate::domain::monotonic_id::next_uuid;
4 use crate::domain::timestamp::Timestamp;4 use crate::domain::timestamp::Timestamp;
@@ -34,14 +34,7 @@ impl CourseSessionId {
34 pub fn key(&self) -> String {34 pub fn key(&self) -> String {
35 self.0.to_string()35 self.0.to_string()
36 }36 }
37-
38- /// The inner uuid, for binding the id through the runtime-checked
39- /// builders ([`crate::db::page::Param`]) whose values are raw uuids.
40- pub(crate) fn uuid(&self) -> uuid::Uuid {
41- self.0
42- }
43 }37 }
44-
45 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]38 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
46 #[sqlx(transparent)]39 #[sqlx(transparent)]
47 pub struct SessionTopic(String);40 pub struct SessionTopic(String);
src/domain/subject.rsmodified+1 -10
@@ -40,14 +40,7 @@ impl SubjectId {
40 pub fn key(&self) -> String {40 pub fn key(&self) -> String {
41 self.0.to_string()41 self.0.to_string()
42 }42 }
43-
44- /// The inner uuid, for binding the id through the runtime-checked
45- /// builders ([`crate::db::page::Param`]) whose values are raw uuids.
46- pub(crate) fn uuid(&self) -> Uuid {
47- self.0
48- }
49 }43 }
50-
51 #[derive(Debug, Clone, PartialEq, Eq, Type)]44 #[derive(Debug, Clone, PartialEq, Eq, Type)]
52 #[sqlx(transparent)]45 #[sqlx(transparent)]
53 pub struct SubjectName(String);46 pub struct SubjectName(String);
@@ -119,9 +112,7 @@ mod tests {
119 /// burst comes out shuffled.112 /// burst comes out shuffled.
120 #[tokio::test]113 #[tokio::test]
121 async fn ids_sort_in_creation_order() {114 async fn ids_sort_in_creation_order() {
122- let ids: Vec<String> = (0..500)115+ let ids: Vec<String> = (0..500).map(|_| SubjectId::generate().key()).collect();
123- .map(|_| SubjectId::generate().key())
124- .collect();
125 let mut sorted = ids.clone();116 let mut sorted = ids.clone();
126 sorted.sort();117 sorted.sort();
127 assert_eq!(ids, sorted);118 assert_eq!(ids, sorted);
src/domain/term.rsmodified+0 -11
@@ -40,18 +40,7 @@ impl TermId {
40 pub fn key(&self) -> String {40 pub fn key(&self) -> String {
41 self.0.to_string()41 self.0.to_string()
42 }42 }
43-
44- /// The inner uuid, for binding the id through the runtime-checked
45- /// builders ([`crate::db::page::Param`]) whose values are raw uuids.
46- pub(crate) fn uuid(&self) -> Uuid {
47- self.0
48- }
49 }43 }
50-
51-/// The answer every link to a term that is not there gets β€” the claim is a
52-/// conditional write on the term row, so a term a delete already removed
53-/// matches nothing and the caller says exactly what the link resolver's
54-/// pre-flight lookup ([`crate::service::term::resolve`]) would have.
55 pub fn gone_error() -> AppError {44 pub fn gone_error() -> AppError {
56 AppError::Validation(ValidationError::Invalid {45 AppError::Validation(ValidationError::Invalid {
57 field: "term_id",46 field: "term_id",
src/service/course.rsmodified+9 -22
@@ -1,7 +1,7 @@
1 //! Course workflows: the archived-term gate every course-scoped write pays,1 //! Course workflows: the archived-term gate every course-scoped write pays,
2 //! the staffing changes a manager makes, and the delete that collects the2 //! the staffing changes a manager makes, and the delete that collects the
3-//! image/homework/note-file blob keys under the exam and homework locks3+//! image/homework/note-file blob keys before the guarded cascade sweeps
4-//! before the cascade sweeps those rows. The queries live in4+//! those rows. The queries live in
5 //! [`crate::db::course`].5 //! [`crate::db::course`].
6 6
7 use crate::database::Database;7 use crate::database::Database;
@@ -135,24 +135,13 @@ pub struct DeleteOutcome {
135 /// Delete the course: collect the image/homework/note-file blob keys, then135 /// Delete the course: collect the image/homework/note-file blob keys, then
136 /// run the cascading delete.136 /// run the cascading delete.
137 ///137 ///
138-/// Writer lease of [`crate::service::exam_attempt::EXAM_LOCK`], for138+/// The old writer leases on the exam-attempt and homework state are gone
139-/// `delete_exam`'s reason: this cascade sweeps the course's exams *and their139+/// with the store that needed them: this cascade is one guarded
140-/// attempts*, and an attempt is the one exam child whose write cannot140+/// transaction whose retry answers a child write that raced it mid-sweep
141-/// collide with the sweep (its claim lands on the student's row, never the141+/// (`is_retryable_cascade` β€” a foreign key naming a row the racing write
142-/// exam's). Narrower here β€” the delete is refused while anyone is enrolled,142+/// just landed), so an attempt started or a grade written beside the sweep
143-/// so a start would have to pass its enrollment gate and then have that143+/// is either swept by the re-sent cascade or refused by the very foreign
144-/// enrollment removed under it β€” but the hole is the same one and so is the144+/// key it would have orphaned. No lock can out-guard that.
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.
156 ///145 ///
157 /// The keys are read before the delete because it takes their rows with it;146 /// The keys are read before the delete because it takes their rows with it;
158 /// a refused delete just drops them unused. Unlinking the blobs stays the147 /// a refused delete just drops them unused. Unlinking the blobs stays the
@@ -160,8 +149,6 @@ pub struct DeleteOutcome {
160 /// blob.149 /// blob.
161 pub async fn delete(db: &Database, course: &Course) -> Result<DeleteOutcome, AppError> {150 pub async fn delete(db: &Database, course: &Course) -> Result<DeleteOutcome, AppError> {
162 require_open(db, course).await?;151 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;
165 let image_files = crate::db::question_image::file_keys_for_course(db, course.get_id()).await?;152 let image_files = crate::db::question_image::file_keys_for_course(db, course.get_id()).await?;
166 let answer_image_files =153 let answer_image_files =
167 crate::db::answer_image::file_keys_for_course(db, course.get_id()).await?;154 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(
545 "only the course creator or a manager/admin can delete this course",545 "only the course creator or a manager/admin can delete this course",
546 ));546 ));
547 }547 }
548- // The workflow β€” archived-term gate, EXAM_LOCK and HOMEWORK_LOCK writer548+ // The workflow β€” archived-term gate, blob-key collection, cascade β€” is
549- // leases, blob-key collection, cascade β€” is [`service::course::delete`]'s.549+ // [`service::course::delete`]'s.
550 // Blob unlinking stays here because only the web layer knows `files_path`.550 // Blob unlinking stays here because only the web layer knows `files_path`.
551 let outcome = service::course::delete(&st.db, &course).await?;551 let outcome = service::course::delete(&st.db, &course).await?;
552 if !outcome.deleted {552 if !outcome.deleted {