forge
Explore
Log in

Don't you dare go Hollow

🏫 pump class rosters through real enrollments

Browse files at this commit

823c8f28b5e9669b704ca9bf858457f815e1410aAhmet Kaan GümüşParent: 4715b08
  • feat
    • 🏫 pump class rosters through real enrollments
Show full message
feat: 🏫 pump class rosters through real enrollments
README.mdmodified+7 -0
@@ -2768,6 +2768,13 @@ src/
2768 names the class that pumped it, absent when hand-placed)2768 names the class that pumped it, absent when hand-placed)
2769 class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube;2769 class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube;
2770 deletable only with no members and no attached courses)2770 deletable only with no members and no attached courses)
2771+ class_member.rs ClassMember (one student in a class; adding them enrolls
2772+ them into every course the class holds)
2773+ class_course.rs ClassCourse (one course on a class; attaching it enrolls
2774+ the class's whole roster)
2775+ class_pump.rs attach/detach (the shared transaction behind both of those:
2776+ link row, class counter and the enrollments it implies move
2777+ together or not at all)
2771 exam.rs ExamId · ExamTitle · ExamDescription · ExamKind · ExamWeight ·2778 exam.rs ExamId · ExamTitle · ExamDescription · ExamKind · ExamWeight ·
2772 ExamMode · ExamDuration · ExamSchedule · Exam (belongs to a course)2779 ExamMode · ExamDuration · ExamSchedule · Exam (belongs to a course)
2773 exam_attempt.rs ExamAttemptId · AttemptStatus · ExamAttempt (numbered sittings per exam+user, metered by max_attempts)2780 exam_attempt.rs ExamAttemptId · AttemptStatus · ExamAttempt (numbered sittings per exam+user, metered by max_attempts)
src/domain/class_course.rsadded+372 -0
@@ -0,0 +1,372 @@
1+//! A course attached to a class, and the enrollments that attachment implies.
2+//!
3+//! The mirror of [`crate::domain::class_member`] along the pump's other axis:
4+//! attaching a course enrolls the class's whole roster into it, detaching it
5+//! sweeps the rows that attach wrote.
6+
7+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
8+
9+use crate::constant::CLASS_COURSE_TABLE;
10+use crate::database::Database;
11+use crate::domain::class_group::ClassGroupId;
12+use crate::domain::class_pump::{Attached, Axis, Sweep, attach, detach, link_id};
13+use crate::domain::course::CourseId;
14+use crate::domain::page::PagedList;
15+use crate::domain::user::UserId;
16+use crate::error::AppError;
17+
18+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
19+pub struct ClassCourseId(RecordId);
20+
21+impl ClassCourseId {
22+ /// The record one (class, course) pair always maps to.
23+ pub fn composite(class: &ClassGroupId, course: &CourseId) -> Self {
24+ Self(link_id(CLASS_COURSE_TABLE, class, course.key()))
25+ }
26+
27+ pub fn record(&self) -> RecordId {
28+ self.0.clone()
29+ }
30+
31+ pub fn key(&self) -> &str {
32+ match &self.0.key {
33+ RecordIdKey::String(key) => key,
34+ _ => "",
35+ }
36+ }
37+}
38+
39+/// One course a class is attached to. `attached_by` is who attached it.
40+#[derive(Debug, Clone, SurrealValue)]
41+pub struct ClassCourse {
42+ id: ClassCourseId,
43+ class: ClassGroupId,
44+ course: CourseId,
45+ attached_by: UserId,
46+}
47+
48+impl ClassCourse {
49+ pub fn get_id(&self) -> &ClassCourseId {
50+ &self.id
51+ }
52+
53+ pub fn get_class(&self) -> &ClassGroupId {
54+ &self.class
55+ }
56+
57+ pub fn get_course(&self) -> &CourseId {
58+ &self.course
59+ }
60+
61+ pub fn get_attached_by(&self) -> &UserId {
62+ &self.attached_by
63+ }
64+
65+ /// Attach `course` to `class` and enroll the class's whole roster into it,
66+ /// in one transaction.
67+ ///
68+ /// Students already in the course keep the rows they have — no seat
69+ /// charged, `source` untouched — and a roster that does not fit refuses the
70+ /// whole attach rather than filling the course to its cap and stopping.
71+ pub async fn attach(
72+ class: &ClassGroupId,
73+ course: &CourseId,
74+ attached_by: &UserId,
75+ db: &Database,
76+ ) -> Result<ClassCourse, AppError> {
77+ let link = ClassCourse {
78+ id: ClassCourseId::composite(class, course),
79+ class: class.clone(),
80+ course: course.clone(),
81+ attached_by: attached_by.clone(),
82+ };
83+ match attach(
84+ class,
85+ Axis::Course,
86+ &link.id.record(),
87+ &link,
88+ course.record(),
89+ attached_by.record(),
90+ db,
91+ )
92+ .await?
93+ {
94+ Attached::Made(saved) => Ok(saved),
95+ Attached::Duplicate => Err(AppError::Conflict("the course is already on this class")),
96+ Attached::Gone => Err(AppError::NotFound),
97+ Attached::Full(full) => Err(AppError::ConflictOwned(format!(
98+ "{full} cannot hold the whole class"
99+ ))),
100+ }
101+ }
102+
103+ /// Detach `course` from `class` and sweep the enrollments the class pumped
104+ /// into it. A course that was not attached is a [`AppError::NotFound`],
105+ /// raised here rather than left to each caller to re-derive from a boolean.
106+ ///
107+ /// A student another attached class still claims keeps their row, re-tagged
108+ /// to that class (see [`crate::domain::class_pump::detach`]).
109+ pub async fn detach(
110+ class: &ClassGroupId,
111+ course: &CourseId,
112+ db: &Database,
113+ ) -> Result<(), AppError> {
114+ let gone = detach(
115+ "$link",
116+ Axis::Course,
117+ Sweep::Rows,
118+ &[(
119+ "link".into(),
120+ ClassCourseId::composite(class, course)
121+ .record()
122+ .into_value(),
123+ )],
124+ db,
125+ )
126+ .await?;
127+ (gone > 0).then_some(()).ok_or(AppError::NotFound)
128+ }
129+
130+ /// The courses a class is attached to, newest first.
131+ pub async fn list_for_class(
132+ class: &ClassGroupId,
133+ limit: Option<i64>,
134+ offset: i64,
135+ db: &Database,
136+ ) -> Result<(Vec<ClassCourse>, i64), AppError> {
137+ PagedList::new(
138+ format!("{CLASS_COURSE_TABLE} WHERE class = $class"),
139+ "ORDER BY id DESC",
140+ )
141+ .bind("class", class.record())
142+ .run(limit, offset, db)
143+ .await
144+ }
145+}
146+
147+#[cfg(test)]
148+mod tests {
149+ use super::*;
150+ use crate::domain::class_member::ClassMember;
151+ use crate::domain::class_member::tests::{a_class, a_course, counter, rows, source_of};
152+ use crate::domain::enrollment::Enrollment;
153+
154+ /// Attaching seeds the course from the roster the class already holds.
155+ #[tokio::test]
156+ async fn an_attach_enrolls_the_whole_roster() {
157+ let db = crate::database::init_mem().await.unwrap();
158+ let manager = UserId::from_key("manager");
159+ let class = a_class("9-A", &db).await;
160+ let algebra = a_course("algebra", None, &db).await;
161+ let students = [UserId::from_key("a"), UserId::from_key("b")];
162+ for student in &students {
163+ ClassMember::add(&class, student, &manager, &db)
164+ .await
165+ .unwrap();
166+ }
167+
168+ ClassCourse::attach(&class, &algebra, &manager, &db)
169+ .await
170+ .unwrap();
171+ for student in &students {
172+ assert_eq!(
173+ source_of(&algebra, student, &db).await,
174+ Some(Some(class.clone()))
175+ );
176+ }
177+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 2);
178+ assert_eq!(counter("class_course_count", class.record(), &db).await, 1);
179+
180+ let again = ClassCourse::attach(&class, &algebra, &manager, &db).await;
181+ assert!(
182+ matches!(again, Err(AppError::Conflict(_))),
183+ "a second attach is a 409: {again:?}"
184+ );
185+ }
186+
187+ /// A course with room for only part of the roster takes none of it: zero
188+ /// enrollments, the counter unmoved, and no attachment row.
189+ #[tokio::test]
190+ async fn a_roster_that_does_not_fit_attaches_nothing() {
191+ let db = crate::database::init_mem().await.unwrap();
192+ let manager = UserId::from_key("manager");
193+ let class = a_class("9-A", &db).await;
194+ let tight = a_course("algebra", Some(2), &db).await;
195+ for student in ["a", "b", "c"] {
196+ ClassMember::add(&class, &UserId::from_key(student), &manager, &db)
197+ .await
198+ .unwrap();
199+ }
200+
201+ let refused = ClassCourse::attach(&class, &tight, &manager, &db).await;
202+ assert!(
203+ matches!(refused, Err(AppError::ConflictOwned(ref message)) if message.contains(tight.key())),
204+ "the refusal must name the course: {refused:?}"
205+ );
206+ assert_eq!(
207+ rows("SELECT VALUE id FROM enrollment", &db).await,
208+ 0,
209+ "the two seats that did fit must be given back with the third"
210+ );
211+ assert_eq!(
212+ rows("SELECT VALUE id FROM class_course", &db).await,
213+ 0,
214+ "…and no attachment row may survive"
215+ );
216+ assert_eq!(counter("enrollment_count", tight.record(), &db).await, 0);
217+ assert_eq!(counter("class_course_count", class.record(), &db).await, 0);
218+ }
219+
220+ /// A hand-placed row is skipped on the way in and left standing on the way
221+ /// out — the class never owned it.
222+ #[tokio::test]
223+ async fn a_hand_placed_row_survives_the_detach() {
224+ let db = crate::database::init_mem().await.unwrap();
225+ let manager = UserId::from_key("manager");
226+ let student = UserId::from_key("student");
227+ let class = a_class("9-A", &db).await;
228+ let algebra = a_course("algebra", None, &db).await;
229+ Enrollment::enroll(&algebra, &student, &manager, &db)
230+ .await
231+ .unwrap();
232+ ClassMember::add(&class, &student, &manager, &db)
233+ .await
234+ .unwrap();
235+
236+ ClassCourse::attach(&class, &algebra, &manager, &db)
237+ .await
238+ .unwrap();
239+ assert_eq!(
240+ source_of(&algebra, &student, &db).await,
241+ Some(None),
242+ "an attach may not adopt a hand-placed row"
243+ );
244+ assert_eq!(
245+ counter("enrollment_count", algebra.record(), &db).await,
246+ 1,
247+ "…nor charge a seat for it"
248+ );
249+
250+ ClassCourse::detach(&class, &algebra, &db).await.unwrap();
251+ assert_eq!(source_of(&algebra, &student, &db).await, Some(None));
252+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
253+ let again = ClassCourse::detach(&class, &algebra, &db).await;
254+ assert!(
255+ matches!(again, Err(AppError::NotFound)),
256+ "a second detach is a 404: {again:?}"
257+ );
258+ }
259+
260+ /// Detaching with nobody else claiming the rows deletes them and gives the
261+ /// seats back.
262+ #[tokio::test]
263+ async fn a_detach_sweeps_the_rows_it_pumped() {
264+ let db = crate::database::init_mem().await.unwrap();
265+ let manager = UserId::from_key("manager");
266+ let student = UserId::from_key("student");
267+ let class = a_class("9-A", &db).await;
268+ let algebra = a_course("algebra", None, &db).await;
269+ ClassMember::add(&class, &student, &manager, &db)
270+ .await
271+ .unwrap();
272+ ClassCourse::attach(&class, &algebra, &manager, &db)
273+ .await
274+ .unwrap();
275+
276+ ClassCourse::detach(&class, &algebra, &db).await.unwrap();
277+ assert_eq!(source_of(&algebra, &student, &db).await, None);
278+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
279+ assert_eq!(counter("class_course_count", class.record(), &db).await, 0);
280+ assert_eq!(
281+ rows("SELECT VALUE id FROM class_member", &db).await,
282+ 1,
283+ "the two axes are independent: dropping the course may not drop \
284+ the student out of the class as well"
285+ );
286+ }
287+
288+ /// Two classes, one course, one student in both: the second attach skipped
289+ /// the row the first wrote, so the row names only the first class — and
290+ /// detaching *that* class must hand the row to the second rather than
291+ /// unenroll a student the second is still responsible for. Detaching the
292+ /// second then finds nobody left and takes the seat back.
293+ #[tokio::test]
294+ async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() {
295+ let db = crate::database::init_mem().await.unwrap();
296+ let manager = UserId::from_key("manager");
297+ let student = UserId::from_key("student");
298+ let algebra = a_course("algebra", None, &db).await;
299+ let first = a_class("9-A", &db).await;
300+ let second = a_class("club", &db).await;
301+ for class in [&first, &second] {
302+ ClassMember::add(class, &student, &manager, &db)
303+ .await
304+ .unwrap();
305+ ClassCourse::attach(class, &algebra, &manager, &db)
306+ .await
307+ .unwrap();
308+ }
309+ assert_eq!(
310+ source_of(&algebra, &student, &db).await,
311+ Some(Some(first.clone())),
312+ "the second attach must skip the row the first wrote"
313+ );
314+ assert_eq!(
315+ counter("enrollment_count", algebra.record(), &db).await,
316+ 1,
317+ "…and pay no second seat for it"
318+ );
319+
320+ ClassCourse::detach(&first, &algebra, &db).await.unwrap();
321+ assert_eq!(
322+ source_of(&algebra, &student, &db).await,
323+ Some(Some(second.clone())),
324+ "the row must be handed to the class that still claims it"
325+ );
326+ assert_eq!(
327+ counter("enrollment_count", algebra.record(), &db).await,
328+ 1,
329+ "a repair is not a release"
330+ );
331+
332+ ClassCourse::detach(&second, &algebra, &db).await.unwrap();
333+ assert_eq!(
334+ source_of(&algebra, &student, &db).await,
335+ None,
336+ "the last claimant leaving takes the row with it"
337+ );
338+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
339+ }
340+
341+ /// The same repair along the member axis: removing the student from the
342+ /// class that owns the row hands it to the other class they are in.
343+ #[tokio::test]
344+ async fn a_member_removal_hands_a_shared_row_over_too() {
345+ let db = crate::database::init_mem().await.unwrap();
346+ let manager = UserId::from_key("manager");
347+ let student = UserId::from_key("student");
348+ let algebra = a_course("algebra", None, &db).await;
349+ let first = a_class("9-A", &db).await;
350+ let second = a_class("club", &db).await;
351+ for class in [&first, &second] {
352+ ClassCourse::attach(class, &algebra, &manager, &db)
353+ .await
354+ .unwrap();
355+ ClassMember::add(class, &student, &manager, &db)
356+ .await
357+ .unwrap();
358+ }
359+
360+ ClassMember::remove(&first, &student, &db).await.unwrap();
361+ assert_eq!(
362+ source_of(&algebra, &student, &db).await,
363+ Some(Some(second.clone())),
364+ "the student is still in the second class, so the row stays"
365+ );
366+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
367+
368+ ClassMember::remove(&second, &student, &db).await.unwrap();
369+ assert_eq!(source_of(&algebra, &student, &db).await, None);
370+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
371+ }
372+}
src/domain/class_member.rsadded+525 -0
@@ -0,0 +1,525 @@
1+//! A student's place in a class, and the enrollments that place implies.
2+//!
3+//! Both writes here are one call into [`crate::domain::class_pump`]: this file
4+//! only names the axis, the counter and the composite id, because adding a
5+//! member and attaching a course to the class are the same pump seen from its
6+//! two ends.
7+
8+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
9+
10+use crate::constant::CLASS_MEMBER_TABLE;
11+use crate::database::Database;
12+use crate::domain::class_group::ClassGroupId;
13+use crate::domain::class_pump::{Attached, Axis, Sweep, attach, detach, link_id};
14+use crate::domain::page::PagedList;
15+use crate::domain::user::UserId;
16+use crate::error::AppError;
17+
18+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
19+pub struct ClassMemberId(RecordId);
20+
21+impl ClassMemberId {
22+ /// The record one (class, user) pair always maps to.
23+ pub fn composite(class: &ClassGroupId, user: &UserId) -> Self {
24+ Self(link_id(CLASS_MEMBER_TABLE, class, user.key()))
25+ }
26+
27+ pub fn record(&self) -> RecordId {
28+ self.0.clone()
29+ }
30+
31+ pub fn key(&self) -> &str {
32+ match &self.0.key {
33+ RecordIdKey::String(key) => key,
34+ _ => "",
35+ }
36+ }
37+}
38+
39+/// One student in one class. `added_by` is who put them there.
40+#[derive(Debug, Clone, SurrealValue)]
41+pub struct ClassMember {
42+ id: ClassMemberId,
43+ class: ClassGroupId,
44+ user: UserId,
45+ added_by: UserId,
46+}
47+
48+impl ClassMember {
49+ pub fn get_id(&self) -> &ClassMemberId {
50+ &self.id
51+ }
52+
53+ pub fn get_class(&self) -> &ClassGroupId {
54+ &self.class
55+ }
56+
57+ pub fn get_user(&self) -> &UserId {
58+ &self.user
59+ }
60+
61+ pub fn get_added_by(&self) -> &UserId {
62+ &self.added_by
63+ }
64+
65+ /// Put `user` in `class` and enroll them into every course the class is
66+ /// already attached to, in one transaction.
67+ ///
68+ /// A student already enrolled in one of those courses keeps the row they
69+ /// have — no seat is charged and their `source` is untouched, so a
70+ /// hand-placed enrollment is never adopted by the class — and a course with
71+ /// no free seat refuses the *whole* join rather than half of it.
72+ pub async fn add(
73+ class: &ClassGroupId,
74+ user: &UserId,
75+ added_by: &UserId,
76+ db: &Database,
77+ ) -> Result<ClassMember, AppError> {
78+ let member = ClassMember {
79+ id: ClassMemberId::composite(class, user),
80+ class: class.clone(),
81+ user: user.clone(),
82+ added_by: added_by.clone(),
83+ };
84+ match attach(
85+ class,
86+ Axis::Member,
87+ &member.id.record(),
88+ &member,
89+ user.record(),
90+ added_by.record(),
91+ db,
92+ )
93+ .await?
94+ {
95+ Attached::Made(saved) => Ok(saved),
96+ Attached::Duplicate => Err(AppError::Conflict("the student is already in this class")),
97+ Attached::Gone => Err(AppError::NotFound),
98+ Attached::Full(course) => Err(AppError::ConflictOwned(format!(
99+ "{course} is full, so the class cannot take this student"
100+ ))),
101+ }
102+ }
103+
104+ /// Take `user` out of `class` and sweep the enrollments the class pumped
105+ /// for them. A student who was not in the class is a
106+ /// [`AppError::NotFound`], raised here rather than left to each caller to
107+ /// re-derive from a boolean.
108+ ///
109+ /// An enrollment another attached class still claims is re-tagged to that
110+ /// class instead of deleted (see [`crate::domain::class_pump::detach`]).
111+ pub async fn remove(
112+ class: &ClassGroupId,
113+ user: &UserId,
114+ db: &Database,
115+ ) -> Result<(), AppError> {
116+ let gone = detach(
117+ "$link",
118+ Axis::Member,
119+ Sweep::Rows,
120+ &[(
121+ "link".into(),
122+ ClassMemberId::composite(class, user).record().into_value(),
123+ )],
124+ db,
125+ )
126+ .await?;
127+ (gone > 0).then_some(()).ok_or(AppError::NotFound)
128+ }
129+
130+ /// Drop every class `user` belongs to, giving each class its member count
131+ /// back — and nothing else. The enrollments are
132+ /// [`crate::domain::enrollment::Enrollment::delete_for_user`]'s to delete;
133+ /// this sweeping them too would decrement the same seats twice.
134+ pub async fn delete_for_user(user: &UserId, db: &Database) -> Result<(), AppError> {
135+ detach(
136+ &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
137+ Axis::Member,
138+ Sweep::CounterOnly,
139+ &[("usr".into(), user.record().into_value())],
140+ db,
141+ )
142+ .await?;
143+ Ok(())
144+ }
145+
146+ /// The class's roster, newest first.
147+ pub async fn list_for_class(
148+ class: &ClassGroupId,
149+ limit: Option<i64>,
150+ offset: i64,
151+ db: &Database,
152+ ) -> Result<(Vec<ClassMember>, i64), AppError> {
153+ PagedList::new(
154+ format!("{CLASS_MEMBER_TABLE} WHERE class = $class"),
155+ "ORDER BY id DESC",
156+ )
157+ .bind("class", class.record())
158+ .run(limit, offset, db)
159+ .await
160+ }
161+}
162+
163+#[cfg(test)]
164+pub(crate) mod tests {
165+ use super::*;
166+ use crate::domain::class_course::ClassCourse;
167+ use crate::domain::class_group::{ClassGroup, ClassName};
168+ use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
169+ use crate::domain::enrollment::Enrollment;
170+
171+ pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId {
172+ ClassGroup::create(
173+ &UserId::from_key("manager"),
174+ ClassName::try_new(name).unwrap(),
175+ None,
176+ None,
177+ db,
178+ )
179+ .await
180+ .unwrap()
181+ .get_id()
182+ .clone()
183+ }
184+
185+ pub(crate) async fn a_course(title: &str, capacity: Option<i64>, db: &Database) -> CourseId {
186+ Course::create(
187+ &UserId::from_key("manager"),
188+ CourseTitle::try_new(title).unwrap(),
189+ CourseDescription::try_new("").unwrap(),
190+ CourseKind::course(),
191+ None,
192+ capacity,
193+ db,
194+ )
195+ .await
196+ .unwrap()
197+ .get_id()
198+ .clone()
199+ }
200+
201+ /// A counter, re-read out of the store — never off a return value, which
202+ /// the in-memory engine forges wins on (see [`crate::domain::cap`]).
203+ pub(crate) async fn counter(field: &str, of: RecordId, db: &Database) -> i64 {
204+ let mut result = db
205+ .query(format!("SELECT VALUE {field} ?? 0 FROM $of"))
206+ .bind(("of", of))
207+ .await
208+ .unwrap()
209+ .check()
210+ .unwrap();
211+ result
212+ .take::<Vec<i64>>(0)
213+ .unwrap()
214+ .first()
215+ .copied()
216+ .unwrap()
217+ }
218+
219+ /// How many rows `sql` selects ids for.
220+ pub(crate) async fn rows(sql: &str, db: &Database) -> usize {
221+ let mut result = db.query(sql).await.unwrap().check().unwrap();
222+ result.take::<Vec<RecordId>>(0).unwrap().len()
223+ }
224+
225+ /// Whether `id` names a live row.
226+ pub(crate) async fn exists(id: RecordId, db: &Database) -> bool {
227+ let mut result = db
228+ .query("SELECT VALUE id FROM $id")
229+ .bind(("id", id))
230+ .await
231+ .unwrap()
232+ .check()
233+ .unwrap();
234+ !result.take::<Vec<RecordId>>(0).unwrap().is_empty()
235+ }
236+
237+ /// The class that wrote an enrollment, or `None` for a hand-placed row.
238+ pub(crate) async fn source_of(
239+ course: &CourseId,
240+ user: &UserId,
241+ db: &Database,
242+ ) -> Option<Option<ClassGroupId>> {
243+ Enrollment::read_for_user(course, user, db)
244+ .await
245+ .unwrap()
246+ .map(|row| row.get_source().cloned())
247+ }
248+
249+ #[tokio::test]
250+ async fn a_member_is_enrolled_into_every_attached_course() {
251+ let db = crate::database::init_mem().await.unwrap();
252+ let manager = UserId::from_key("manager");
253+ let student = UserId::from_key("student");
254+ let class = a_class("9-A", &db).await;
255+ let algebra = a_course("algebra", None, &db).await;
256+ let physics = a_course("physics", None, &db).await;
257+ ClassCourse::attach(&class, &algebra, &manager, &db)
258+ .await
259+ .unwrap();
260+ ClassCourse::attach(&class, &physics, &manager, &db)
261+ .await
262+ .unwrap();
263+
264+ ClassMember::add(&class, &student, &manager, &db)
265+ .await
266+ .unwrap();
267+
268+ for course in [&algebra, &physics] {
269+ assert_eq!(
270+ source_of(course, &student, &db).await,
271+ Some(Some(class.clone())),
272+ "every attached course must hold a row tagged with the class"
273+ );
274+ assert_eq!(counter("enrollment_count", course.record(), &db).await, 1);
275+ }
276+ assert_eq!(counter("class_member_count", class.record(), &db).await, 1);
277+ }
278+
279+ /// The pumped row must carry the *same* composite id a hand enroll would
280+ /// mint, or the two paths would key one pair two ways and only the unique
281+ /// index (a 500) would notice.
282+ #[tokio::test]
283+ async fn a_pumped_row_uses_the_hand_enrolls_composite_id() {
284+ use crate::domain::enrollment::EnrollmentId;
285+
286+ let db = crate::database::init_mem().await.unwrap();
287+ let manager = UserId::from_key("manager");
288+ let student = UserId::from_key("student");
289+ let class = a_class("9-A", &db).await;
290+ let algebra = a_course("algebra", None, &db).await;
291+ ClassCourse::attach(&class, &algebra, &manager, &db)
292+ .await
293+ .unwrap();
294+ ClassMember::add(&class, &student, &manager, &db)
295+ .await
296+ .unwrap();
297+
298+ assert!(
299+ exists(EnrollmentId::composite(&algebra, &student).record(), &db).await,
300+ "the pump must key the pair the way Enrollment::composite does"
301+ );
302+ }
303+
304+ /// Re-adding is a 409, and it must cost nothing: no second counter tick and
305+ /// no second sweep of anybody's enrollment.
306+ #[tokio::test]
307+ async fn a_second_add_is_refused_and_writes_nothing() {
308+ let db = crate::database::init_mem().await.unwrap();
309+ let manager = UserId::from_key("manager");
310+ let student = UserId::from_key("student");
311+ let class = a_class("9-A", &db).await;
312+ let algebra = a_course("algebra", None, &db).await;
313+ ClassCourse::attach(&class, &algebra, &manager, &db)
314+ .await
315+ .unwrap();
316+ ClassMember::add(&class, &student, &manager, &db)
317+ .await
318+ .unwrap();
319+
320+ let again = ClassMember::add(&class, &student, &manager, &db).await;
321+ assert!(
322+ matches!(again, Err(AppError::Conflict(_))),
323+ "a second add is a 409: {again:?}"
324+ );
325+ assert_eq!(
326+ counter("class_member_count", class.record(), &db).await,
327+ 1,
328+ "a refused add may not tick the counter"
329+ );
330+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
331+ }
332+
333+ /// Adding into a class whose courses have no room refuses the *whole* join:
334+ /// the roomy course must not keep a seat the full one denied.
335+ #[tokio::test]
336+ async fn a_full_course_refuses_the_whole_join() {
337+ let db = crate::database::init_mem().await.unwrap();
338+ let manager = UserId::from_key("manager");
339+ let student = UserId::from_key("student");
340+ let class = a_class("9-A", &db).await;
341+ let roomy = a_course("algebra", None, &db).await;
342+ let full = a_course("physics", Some(0), &db).await;
343+ ClassCourse::attach(&class, &roomy, &manager, &db)
344+ .await
345+ .unwrap();
346+ ClassCourse::attach(&class, &full, &manager, &db)
347+ .await
348+ .unwrap();
349+
350+ // The whole record id, not just the key: a caller reading the 409 must
351+ // not have to guess which table the name came from.
352+ let named = format!("{}:{}", crate::constant::COURSE_TABLE, full.key());
353+ let refused = ClassMember::add(&class, &student, &manager, &db).await;
354+ assert!(
355+ matches!(refused, Err(AppError::ConflictOwned(ref message)) if message.contains(&named)),
356+ "the refusal must name the course that had no seat as {named}: {refused:?}"
357+ );
358+ assert_eq!(
359+ rows("SELECT VALUE id FROM enrollment", &db).await,
360+ 0,
361+ "not one seat may survive the refusal"
362+ );
363+ assert_eq!(
364+ rows("SELECT VALUE id FROM class_member", &db).await,
365+ 0,
366+ "…nor the membership row itself"
367+ );
368+ assert_eq!(
369+ counter("enrollment_count", roomy.record(), &db).await,
370+ 0,
371+ "…nor the roomy course's counter"
372+ );
373+ assert_eq!(counter("class_member_count", class.record(), &db).await, 0);
374+ }
375+
376+ /// A student already enrolled by hand keeps their own row: no seat is
377+ /// charged for them, the row's `source` stays empty, and removing them from
378+ /// the class leaves it standing.
379+ #[tokio::test]
380+ async fn a_hand_placed_enrollment_is_skipped_and_survives_removal() {
381+ let db = crate::database::init_mem().await.unwrap();
382+ let manager = UserId::from_key("manager");
383+ let student = UserId::from_key("student");
384+ let class = a_class("9-A", &db).await;
385+ let algebra = a_course("algebra", None, &db).await;
386+ Enrollment::enroll(&algebra, &student, &manager, &db)
387+ .await
388+ .unwrap();
389+ ClassCourse::attach(&class, &algebra, &manager, &db)
390+ .await
391+ .unwrap();
392+
393+ ClassMember::add(&class, &student, &manager, &db)
394+ .await
395+ .unwrap();
396+ assert_eq!(
397+ source_of(&algebra, &student, &db).await,
398+ Some(None),
399+ "the class must not adopt a hand-placed row"
400+ );
401+ assert_eq!(
402+ counter("enrollment_count", algebra.record(), &db).await,
403+ 1,
404+ "the skipped pair may not be charged a second seat"
405+ );
406+
407+ ClassMember::remove(&class, &student, &db).await.unwrap();
408+ assert_eq!(
409+ source_of(&algebra, &student, &db).await,
410+ Some(None),
411+ "the sweep may only take back the rows the class wrote"
412+ );
413+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
414+ }
415+
416+ /// Removal with nobody else claiming the row: the enrollment goes and its
417+ /// seat comes back.
418+ #[tokio::test]
419+ async fn removal_deletes_the_rows_the_class_pumped() {
420+ let db = crate::database::init_mem().await.unwrap();
421+ let manager = UserId::from_key("manager");
422+ let student = UserId::from_key("student");
423+ let class = a_class("9-A", &db).await;
424+ let algebra = a_course("algebra", None, &db).await;
425+ ClassCourse::attach(&class, &algebra, &manager, &db)
426+ .await
427+ .unwrap();
428+ ClassMember::add(&class, &student, &manager, &db)
429+ .await
430+ .unwrap();
431+
432+ ClassMember::remove(&class, &student, &db).await.unwrap();
433+ assert_eq!(source_of(&algebra, &student, &db).await, None);
434+ assert_eq!(
435+ counter("enrollment_count", algebra.record(), &db).await,
436+ 0,
437+ "the seat must come back with the row that held it"
438+ );
439+ assert_eq!(counter("class_member_count", class.record(), &db).await, 0);
440+ let again = ClassMember::remove(&class, &student, &db).await;
441+ assert!(
442+ matches!(again, Err(AppError::NotFound)),
443+ "a second removal is a 404, not a second sweep: {again:?}"
444+ );
445+ }
446+
447+ /// A member who is not in any attached course still removes cleanly, and a
448+ /// course deleted out from under the class leaves nothing to sweep — the
449+ /// membership row and the pumped enrollment are independent facts.
450+ #[tokio::test]
451+ async fn a_sweep_tolerates_rows_a_course_delete_already_took() {
452+ let db = crate::database::init_mem().await.unwrap();
453+ let manager = UserId::from_key("manager");
454+ let student = UserId::from_key("student");
455+ let class = a_class("9-A", &db).await;
456+ let algebra = a_course("algebra", None, &db).await;
457+ ClassCourse::attach(&class, &algebra, &manager, &db)
458+ .await
459+ .unwrap();
460+ ClassMember::add(&class, &student, &manager, &db)
461+ .await
462+ .unwrap();
463+
464+ // `Course::delete` refuses while the roster is occupied, so the wipe is
465+ // spelled the way the cascade does it, minus the guard.
466+ db.query("DELETE enrollment WHERE course = $course; DELETE class_course WHERE course = $course; DELETE $course;")
467+ .bind(("course", algebra.record()))
468+ .await
469+ .unwrap()
470+ .check()
471+ .unwrap();
472+
473+ ClassMember::remove(&class, &student, &db)
474+ .await
475+ .expect("the membership must still be removable with its enrollment gone");
476+ assert_eq!(counter("class_member_count", class.record(), &db).await, 0);
477+ }
478+
479+ /// The role-demotion sweep: memberships go and their counters come back,
480+ /// while the enrollment rows are left for `Enrollment::delete_for_user`.
481+ /// Decrementing those seats here as well would take each one back twice.
482+ #[tokio::test]
483+ async fn delete_for_user_leaves_the_enrollments_alone() {
484+ let db = crate::database::init_mem().await.unwrap();
485+ let manager = UserId::from_key("manager");
486+ let student = UserId::from_key("student");
487+ let first = a_class("9-A", &db).await;
488+ let second = a_class("club", &db).await;
489+ let algebra = a_course("algebra", None, &db).await;
490+ ClassCourse::attach(&first, &algebra, &manager, &db)
491+ .await
492+ .unwrap();
493+ ClassMember::add(&first, &student, &manager, &db)
494+ .await
495+ .unwrap();
496+ ClassMember::add(&second, &student, &manager, &db)
497+ .await
498+ .unwrap();
499+
500+ ClassMember::delete_for_user(&student, &db).await.unwrap();
501+ assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
502+ for class in [&first, &second] {
503+ assert_eq!(
504+ counter("class_member_count", class.record(), &db).await,
505+ 0,
506+ "every class must get its member count back"
507+ );
508+ }
509+ assert_eq!(
510+ source_of(&algebra, &student, &db).await,
511+ Some(Some(first.clone())),
512+ "the enrollment is the other sweep's to delete"
513+ );
514+ assert_eq!(
515+ counter("enrollment_count", algebra.record(), &db).await,
516+ 1,
517+ "…and its seat is the other sweep's to release"
518+ );
519+
520+ // Which is exactly what the demotion calls next, and the seat comes
521+ // back once, not twice.
522+ Enrollment::delete_for_user(&student, &db).await.unwrap();
523+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
524+ }
525+}
src/domain/class_pump.rsadded+434 -0
@@ -0,0 +1,434 @@
1+//! The pump behind the class layer: one link row changed, and every
2+//! `enrollment` row that link implies reconciled with it, in one transaction.
3+//!
4+//! A class (şube) has two link tables — `class_member` (a student in it) and
5+//! `class_course` (a course attached to it) — and the *product* of the two is
6+//! the roster it owes: every member is enrolled in every attached course, in
7+//! real `enrollment` rows tagged [`source`](crate::domain::enrollment) with the
8+//! class that wrote them. Adding a member and attaching a course are therefore
9+//! the same operation seen along its two axes, and so are removing one and
10+//! detaching the other. That axis is what these two primitives take as a
11+//! parameter, so the four public operations are each a couple of lines.
12+//!
13+//! What is *not* one primitive is attach and detach. They share no statement:
14+//! one gates on "this pair already holds a row" and claims two counters
15+//! upwards, the other gates on nothing, releases, and has to decide per
16+//! enrollment row whether a *rival* class still claims it. Folding them behind
17+//! a direction flag would be one function containing two, so the seam stays
18+//! where the SQL puts it.
19+//!
20+//! Everything here writes counters the way [`crate::domain::cap`] does — a
21+//! single-record conditional `UPDATE`, never a count-then-write — and every
22+//! `??` is parenthesized, because `n ?? 0 < $cap` parses as `n ?? (0 < $cap)`
23+//! and is truthy for every row.
24+
25+use surrealdb::types::{RecordId, SurrealValue, Value};
26+
27+use crate::constant::{
28+ CLASS_COURSE_COUNT_FIELD, CLASS_COURSE_TABLE, CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE,
29+ ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE,
30+};
31+use crate::database::{Database, transaction_with_retry};
32+use crate::domain::cap;
33+use crate::domain::class_group::ClassGroupId;
34+use crate::error::AppError;
35+
36+/// The `THROW` markers [`attach`] aborts with. `FULL_MARK` is a *prefix*: the
37+/// record id of the course that had no seat is appended to it, because "the
38+/// class does not fit" is unanswerable without knowing which course to raise
39+/// the capacity of, and the loop only learns that at runtime. The whole id and
40+/// not just the key, so the refusal names something a caller can look up
41+/// without knowing which table it came from.
42+const HELD_MARK: &str = "class_held";
43+const GONE_MARK: &str = "class_gone";
44+const FULL_MARK: &str = "class_full:";
45+
46+/// What [`attach`] settled.
47+pub(crate) enum Attached<T> {
48+ /// The link row, the counter and every enrollment it implied committed
49+ /// together.
50+ Made(T),
51+ /// The link already exists — nothing was written, and no seat was spent
52+ /// finding that out.
53+ Duplicate,
54+ /// The class row is gone (a concurrent delete won). Nothing was written.
55+ Gone,
56+ /// One of the courses had no free seat, named by its key. Nothing was
57+ /// written — not one of the earlier seats in the same run, which is the
58+ /// whole point of doing this in a transaction.
59+ Full(String),
60+}
61+
62+/// Which way the pump runs: the loop below needs a `(course, user)` pair per
63+/// enrollment, and each caller supplies one side as a constant and reads the
64+/// other off the class's *other* link table.
65+pub(crate) enum Axis {
66+ /// A student joining: the courses come from `class_course`.
67+ Member,
68+ /// A course arriving: the students come from `class_member`.
69+ Course,
70+}
71+
72+impl Axis {
73+ /// The `SELECT` that yields this run's `(course, user)` pairs, with `$pivot`
74+ /// bound to the fixed side. In-crate text, never client input.
75+ fn pairs(&self) -> String {
76+ match self {
77+ Axis::Member => format!(
78+ "SELECT VALUE {{ course: course, user: $pivot }} \
79+ FROM {CLASS_COURSE_TABLE} WHERE class = $class"
80+ ),
81+ Axis::Course => format!(
82+ "SELECT VALUE {{ course: $pivot, user: user }} \
83+ FROM {CLASS_MEMBER_TABLE} WHERE class = $class"
84+ ),
85+ }
86+ }
87+
88+ /// The enrollment rows a *detached* link of this axis is responsible for,
89+ /// as a `WHERE` fragment over `enrollment`. Read off the deleted link row
90+ /// rather than a bound parameter, so one loop serves a single detach and a
91+ /// user's whole membership alike.
92+ fn scope(&self) -> &'static str {
93+ match self {
94+ Axis::Member => "user = $link.user",
95+ Axis::Course => "course = $link.course",
96+ }
97+ }
98+
99+ /// The class counter this axis's link rows are counted on. Taken off the
100+ /// axis rather than passed in beside it, because the two are one fact and a
101+ /// call site that paired the member axis with the course counter would
102+ /// compile, pass every test — both are `&str` — and desync the class delete
103+ /// guard forever.
104+ fn counter(&self) -> &'static str {
105+ match self {
106+ Axis::Member => CLASS_MEMBER_COUNT_FIELD,
107+ Axis::Course => CLASS_COURSE_COUNT_FIELD,
108+ }
109+ }
110+}
111+
112+/// Whether a [`detach`] also reconciles the enrollment rows its links pumped.
113+pub(crate) enum Sweep {
114+ /// Repair or delete them, per the rule in [`detach`].
115+ Rows,
116+ /// Release the counters and touch nothing else, because something else owns
117+ /// the enrollment side of this same event.
118+ CounterOnly,
119+}
120+
121+/// Write `link` and enroll everything it implies, or write nothing at all.
122+///
123+/// The order is the one [`cap::claim_and_create`] settled on and for the same
124+/// reason: the link is looked for *before* any counter moves, so "you are
125+/// already in" outranks "there is no room" — a caller whose row a rival placed
126+/// a moment ago must not be told a course is full about seats they already
127+/// hold.
128+///
129+/// The class counter is claimed by a conditional write rather than a bare
130+/// increment, so a class deleted out from under this run matches nothing and
131+/// the whole cascade aborts: [`Attached::Gone`] instead of a counter on a row
132+/// that no longer exists.
133+///
134+/// Every enrollment in the loop is *skipped* when the pair already has a row —
135+/// no seat charged, and the existing row's `source` left exactly as it was, so
136+/// a hand-placed student is never quietly adopted by a class. Only the pairs
137+/// that had no row at all are charged, each against its own course's capacity.
138+///
139+/// On admissibility ([`crate::database::transaction_with_retry`]): every
140+/// `CREATE` here is preceded by its own in-transaction existence check, so an
141+/// "already exists" can only come from a rival that landed inside that window —
142+/// and re-sending the whole cascade then *sees* the row and takes the other
143+/// branch. The retry converges instead of re-asking a settled question, which
144+/// is the restriction's actual test.
145+pub(crate) async fn attach<T: SurrealValue + Clone>(
146+ class: &ClassGroupId,
147+ axis: Axis,
148+ link: &RecordId,
149+ row: &T,
150+ pivot: RecordId,
151+ by: RecordId,
152+ db: &Database,
153+) -> Result<Attached<T>, AppError> {
154+ let count_field = axis.counter();
155+ let pairs = axis.pairs();
156+ let sql = format!(
157+ "BEGIN TRANSACTION;
158+ LET $held = (SELECT VALUE id FROM $link);
159+ IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }};
160+ LET $counted = (UPDATE $class SET {count_field} = ({count_field} ?? 0) + 1 \
161+ WHERE ({count_field} ?? 0) < $unlimited RETURN VALUE id);
162+ IF array::len($counted) = 0 {{ THROW '{GONE_MARK}' }};
163+ CREATE $link CONTENT $row;
164+ FOR $pair IN (({pairs}) ?? []) {{
165+ LET $seat_of = type::record('{ENROLLMENT_TABLE}', string::concat(
166+ record::id($pair.course), '_', record::id($pair.user)));
167+ IF array::len((SELECT VALUE id FROM $seat_of)) = 0 {{
168+ LET $seat = (UPDATE $pair.course SET {ENROLLMENT_COUNT_FIELD} = \
169+ ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \
170+ WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \
171+ RETURN VALUE id);
172+ IF array::len($seat) = 0 {{
173+ THROW '{FULL_MARK}' + <string>$pair.course
174+ }};
175+ CREATE $seat_of CONTENT {{ course: $pair.course, user: $pair.user, \
176+ enrolled_by: $by, source: $class }};
177+ }};
178+ }};
179+ COMMIT TRANSACTION;"
180+ );
181+ let (mut result, mut errors) = transaction_with_retry(
182+ db,
183+ &sql,
184+ &[
185+ ("class".into(), class.record().into_value()),
186+ ("link".into(), link.clone().into_value()),
187+ ("row".into(), row.clone().into_value()),
188+ ("pivot".into(), pivot.into_value()),
189+ ("by".into(), by.into_value()),
190+ ("unlimited".into(), cap::UNLIMITED.into_value()),
191+ ],
192+ &[HELD_MARK, GONE_MARK, FULL_MARK],
193+ )
194+ .await?;
195+ // "Already linked" is read first: it outranks both refusals below, and the
196+ // gate aborts before either could fire.
197+ //
198+ // Only the `THROW` is read, never an `is_already_exists` off the `CREATE`
199+ // itself. A rival landing in the window between the gate and the create
200+ // makes the store answer "already exists", which
201+ // [`transaction_with_retry`] treats as a lost round and re-sends — and that
202+ // re-send is the right answer, because the second pass *sees* the row at
203+ // the gate. Reading it here would also mis-file the enrollment `CREATE`'s
204+ // version of the same answer as "already in this class".
205+ if errors
206+ .values()
207+ .any(|error| error.to_string().contains(HELD_MARK))
208+ {
209+ return Ok(Attached::Duplicate);
210+ }
211+ if errors
212+ .values()
213+ .any(|error| error.to_string().contains(GONE_MARK))
214+ {
215+ return Ok(Attached::Gone);
216+ }
217+ if let Some(course) = errors
218+ .values()
219+ .find_map(|error| full_course(&error.to_string()))
220+ {
221+ return Ok(Attached::Full(course));
222+ }
223+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
224+ return Err(error.into());
225+ }
226+ // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5.
227+ result
228+ .take::<Vec<T>>(5)?
229+ .into_iter()
230+ .next()
231+ .map(Attached::Made)
232+ .ok_or_else(|| AppError::Internal("the class pump wrote no link row".into()))
233+}
234+
235+/// The course id out of a `class_full:<table>:<key>` abort. Table names and the
236+/// generated ULID keys here are alphanumeric and `:` joins them, so the id ends
237+/// where the store's own wrapping around the thrown text begins.
238+fn full_course(message: &str) -> Option<String> {
239+ let id: String = message
240+ .split_once(FULL_MARK)?
241+ .1
242+ .chars()
243+ .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | ':'))
244+ .collect();
245+ (!id.is_empty()).then_some(id)
246+}
247+
248+/// Drop the link rows `links` names, give each class its counter back, and
249+/// sweep the enrollment rows those links pumped. Answers how many link rows
250+/// went, so a caller whose link was a single pair can turn zero into a 404.
251+///
252+/// The sweep is *repair-first*: an enrollment this class wrote is only deleted
253+/// once no other class still claims it. Two classes attached to the same course
254+/// share a student — the second attach skipped the row the first had already
255+/// written, so the row carries only the first class's name — and deleting it on
256+/// the first class's way out would unenroll a student the second class is still
257+/// responsible for. So the row is re-tagged to that rival instead, and only a
258+/// row nobody is left to claim is deleted and its seat given back. The heir is
259+/// the lowest class id among the claimants: a deterministic pick, so a repeat
260+/// of the same sweep lands on the same class.
261+///
262+/// Sweeps tolerate rows that are already gone. `Course::delete` wipes a
263+/// course's enrollments wholesale while the `class_member` rows survive it, so
264+/// "this class has a member" and "that member has a live pumped row" are
265+/// independent facts and the loop simply finds nothing to sweep.
266+///
267+/// [`Sweep::CounterOnly`] is the deliberate half of this: dropping a *user's*
268+/// whole membership releases the counters and nothing else, because
269+/// `Enrollment::delete_for_user` owns the enrollment side of that same event and
270+/// a second decrement of the same seat is a bug, not a belt.
271+///
272+/// Admissible by construction: `DELETE` and `UPDATE` only, so no statement in
273+/// the cascade can answer "already exists" and every lost round is a plain
274+/// re-send.
275+pub(crate) async fn detach(
276+ links: &str,
277+ axis: Axis,
278+ sweep: Sweep,
279+ bindings: &[(String, Value)],
280+ db: &Database,
281+) -> Result<i64, AppError> {
282+ let count_field = axis.counter();
283+ let sweep = match sweep {
284+ Sweep::CounterOnly => String::new(),
285+ Sweep::Rows => {
286+ let scope = axis.scope();
287+ format!(
288+ "FOR $row IN ((SELECT id, course, user FROM {ENROLLMENT_TABLE} \
289+ WHERE {scope} AND source = $link.class) ?? []) {{
290+ LET $rivals = (SELECT VALUE class FROM {CLASS_COURSE_TABLE} \
291+ WHERE course = $row.course AND class != $link.class);
292+ LET $heir = array::first(array::sort((SELECT VALUE class \
293+ FROM {CLASS_MEMBER_TABLE} WHERE user = $row.user AND class IN $rivals)));
294+ IF $heir != NONE {{
295+ UPDATE $row.id SET source = $heir;
296+ }} ELSE {{
297+ DELETE $row.id;
298+ UPDATE $row.course SET {ENROLLMENT_COUNT_FIELD} = \
299+ math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]);
300+ }};
301+ }};"
302+ )
303+ }
304+ };
305+ let sql = format!(
306+ "BEGIN TRANSACTION;
307+ LET $gone = (DELETE {links} RETURN BEFORE);
308+ FOR $link IN ($gone ?? []) {{
309+ UPDATE $link.class SET {count_field} = math::max([({count_field} ?? 0) - 1, 0]);
310+ {sweep}
311+ }};
312+ RETURN array::len($gone);
313+ COMMIT TRANSACTION;"
314+ );
315+ let (mut result, mut errors) = transaction_with_retry(db, &sql, bindings, &[]).await?;
316+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
317+ return Err(error.into());
318+ }
319+ // Slots count BEGIN, the LET and the FOR: the RETURN is slot 3.
320+ Ok(result.take::<Vec<i64>>(3)?.into_iter().next().unwrap_or(0))
321+}
322+
323+/// A composite id for a `(class, other)` link, the shape
324+/// [`crate::domain::enrollment::EnrollmentId::composite`] uses: the same pair
325+/// always maps to the same record, so one row per pair holds by construction
326+/// and a duplicate is something the store can *see* rather than something a
327+/// find-then-insert has to race.
328+pub(crate) fn link_id(table: &str, class: &ClassGroupId, other: &str) -> RecordId {
329+ RecordId::new(table, format!("{}_{}", class.key(), other))
330+}
331+
332+#[cfg(test)]
333+mod tests {
334+ use super::*;
335+ use crate::constant::{CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE};
336+ use crate::domain::class_group::ClassGroupId;
337+ use crate::domain::class_member::ClassMember;
338+ use crate::domain::class_member::tests::{a_class, counter, rows};
339+ use crate::domain::user::UserId;
340+ use crate::error::AppError;
341+
342+ /// The class counter is claimed conditionally, so a class that is not there
343+ /// stops the cascade before anything is written — rather than leaving a
344+ /// counter, a link row and a pumped enrollment hanging off a record that
345+ /// does not exist.
346+ #[tokio::test]
347+ async fn an_attach_onto_a_missing_class_writes_nothing() {
348+ let db = crate::database::init_mem().await.unwrap();
349+ let ghost = ClassGroupId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");
350+
351+ let refused = ClassMember::add(
352+ &ghost,
353+ &UserId::from_key("student"),
354+ &UserId::from_key("manager"),
355+ &db,
356+ )
357+ .await;
358+ assert!(
359+ matches!(refused, Err(AppError::NotFound)),
360+ "a class that is gone is a 404, not a counter on nothing: {refused:?}"
361+ );
362+ assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
363+ assert_eq!(rows("SELECT VALUE id FROM class_group", &db).await, 0);
364+ }
365+
366+ /// [`detach`] is written to take *many* link rows at once — that is what
367+ /// makes a user's whole membership one statement — and every one of them
368+ /// releases its own class's counter. Called straight, because the public
369+ /// `delete_for_user` throws the count away.
370+ #[tokio::test]
371+ async fn a_detach_releases_every_class_it_unlinked() {
372+ let db = crate::database::init_mem().await.unwrap();
373+ let manager = UserId::from_key("manager");
374+ let student = UserId::from_key("student");
375+ let classes = [
376+ a_class("9-A", &db).await,
377+ a_class("9-B", &db).await,
378+ a_class("club", &db).await,
379+ ];
380+ for class in &classes {
381+ ClassMember::add(class, &student, &manager, &db)
382+ .await
383+ .unwrap();
384+ }
385+
386+ let gone = detach(
387+ &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
388+ Axis::Member,
389+ Sweep::CounterOnly,
390+ &[("usr".into(), student.record().into_value())],
391+ &db,
392+ )
393+ .await
394+ .unwrap();
395+ assert_eq!(
396+ gone, 3,
397+ "every link row must be counted, not just the first"
398+ );
399+ for class in &classes {
400+ assert_eq!(
401+ counter(CLASS_MEMBER_COUNT_FIELD, class.record(), &db).await,
402+ 0,
403+ "each class gets its own counter back"
404+ );
405+ }
406+
407+ // And a run that unlinks nothing answers zero, which is what turns a
408+ // single-pair detach into a 404 instead of a silent success.
409+ let again = detach(
410+ &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
411+ Axis::Member,
412+ Sweep::CounterOnly,
413+ &[("usr".into(), student.record().into_value())],
414+ &db,
415+ )
416+ .await
417+ .unwrap();
418+ assert_eq!(again, 0);
419+ }
420+
421+ #[test]
422+ fn a_full_abort_names_its_course() {
423+ assert_eq!(
424+ full_course("An error occurred: class_full:course:01J8XZ0K3Q"),
425+ Some("course:01J8XZ0K3Q".to_string())
426+ );
427+ assert_eq!(
428+ full_course("class_full:course:algebra'"),
429+ Some("course:algebra".into())
430+ );
431+ assert_eq!(full_course("class_held"), None);
432+ assert_eq!(full_course("class_full:"), None);
433+ }
434+}
src/domain/mod.rsmodified+3 -0
@@ -13,7 +13,10 @@ pub mod board_stroke;
13 pub mod cap;13 pub mod cap;
14 pub mod chatbot_message;14 pub mod chatbot_message;
15 pub mod chatbot_thread;15 pub mod chatbot_thread;
16+pub mod class_course;
16 pub mod class_group;17 pub mod class_group;
18+pub mod class_member;
19+pub mod class_pump;
17 pub mod course;20 pub mod course;
18 pub mod course_session;21 pub mod course_session;
19 pub mod dietary_profile;22 pub mod dietary_profile;
src/web/users.rsmodified+7 -0
@@ -7,6 +7,7 @@ use utoipa_axum::router::OpenApiRouter;
7 use utoipa_axum::routes;7 use utoipa_axum::routes;
8 8
9 use crate::database::Database;9 use crate::database::Database;
10+use crate::domain::class_member::ClassMember;
10 use crate::domain::course::Course;11 use crate::domain::course::Course;
11 use crate::domain::enrollment::Enrollment;12 use crate::domain::enrollment::Enrollment;
12 use crate::domain::parent_link::ParentLink;13 use crate::domain::parent_link::ParentLink;
@@ -398,7 +399,13 @@ async fn set_role(
398 // Parent links get the same sweep on both sides: only students are399 // Parent links get the same sweep on both sides: only students are
399 // observed and only parents observe, so a role change off either end400 // observed and only parents observe, so a role change off either end
400 // drops the rows instead of leaving dead grants around.401 // drops the rows instead of leaving dead grants around.
402+ // The class memberships go first and the enrollments second: the class
403+ // sweep deliberately leaves the enrollment rows alone, so running it after
404+ // would find nothing to repair and running it before costs nothing either
405+ // way. Both are needed — a membership left behind would keep pumping the
406+ // user back into courses and make its class undeletable.
401 if role != Role::Student {407 if role != Role::Student {
408+ ClassMember::delete_for_user(&target, &st.db).await?;
402 Enrollment::delete_for_user(&target, &st.db).await?;409 Enrollment::delete_for_user(&target, &st.db).await?;
403 ParentLink::delete_where_student(&target, &st.db).await?;410 ParentLink::delete_where_student(&target, &st.db).await?;
404 }411 }