forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

class_group.rs930 lines, 37.2 KiBHistoryRawDownload
1//! The `class_group` table: the row, its academic-year reference claimed
2//! through the [`crate::db::cap`] shapes in the same statement as the link,
3//! and the 0/0 delete guard. The archived-year guard and the route-facing
4//! wrappers live in [`crate::service::class_group`].
5
6use crate::constant::{ACADEMIC_YEAR_CLASS_COUNT_FIELD, CLASS_GROUP_TABLE};
7use crate::database::{Database, tx_with_retry};
8use crate::db::field_update::{FieldUpdate, Refcount};
9use crate::db::page::PagedList;
10use crate::domain::academic_year::AcademicYearId;
11use crate::domain::class_group::{ClassGroup, ClassGroupId, ClassName};
12use crate::domain::grade::GradeLevel;
13use crate::domain::user::UserId;
14use crate::error::{AppError, ValidationError};
15
16/// The refusal a section write naming a year that is not there gets — the mirror
17/// of [`crate::domain::term::gone_error`], one layer up the calendar.
18fn year_gone() -> AppError {
19 AppError::Validation(ValidationError::Invalid {
20 field: "year",
21 reason: "academic year does not exist",
22 })
23}
24
25/// What a PATCH's `year` field owes the refcounts: the year to claim and the
26/// one to give back. Covers all three moves — set (none→some), move
27/// (some→other) and clear (some→none) — and moves nothing for a PATCH that
28/// omitted the field or re-stated the link it already had. The same shape
29/// [`crate::domain::term::ref_move`] gives the term link.
30fn year_ref_move(
31 current: Option<&AcademicYearId>,
32 patch: &Option<Option<AcademicYearId>>,
33) -> (Option<AcademicYearId>, Option<AcademicYearId>) {
34 match patch {
35 None => (None, None),
36 Some(next) if next.as_ref() == current => (None, None),
37 Some(next) => (*next, current.copied()),
38 }
39}
40
41/// Create the class, claiming a reference on the academic year it links (if
42/// any) in the *same statement* as the row, exactly as
43/// [`crate::db::course::create`] did for the term: the claim is a conditional
44/// write on the year row, so it fails when the year is already gone, it makes
45/// the year undeletable the instant this link exists, and — the claim and the
46/// insert being one CTE — no crash and no refused claim can leave either half
47/// without the other.
48pub async fn create(
49 db: &Database,
50 creator: &UserId,
51 name: ClassName,
52 grade_level: GradeLevel,
53 year: Option<AcademicYearId>,
54 teacher: Option<UserId>,
55) -> Result<ClassGroup, AppError> {
56 let id = ClassGroupId::generate();
57 match &year {
58 Some(year) => {
59 // The claim and the insert are one statement: atomic without an
60 // explicit transaction, exactly like every other
61 // single-statement guard.
62 let written = sqlx::query_as!(
63 ClassGroup,
64 r#"WITH seat AS (
65 UPDATE academic_year SET class_count = class_count + 1
66 WHERE id = $1
67 RETURNING 1)
68 INSERT INTO class_group (id, creator, name, grade_level, year, teacher)
69 SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat)
70 RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId",
71 name AS "name: ClassName", grade_level AS "grade_level: GradeLevel",
72 year AS "year: AcademicYearId", teacher AS "teacher: UserId""#,
73 year.uuid(),
74 id.uuid(),
75 creator.uuid(),
76 name.as_str(),
77 grade_level.get(),
78 teacher.as_ref().map(UserId::uuid)
79 )
80 .fetch_optional(db)
81 .await;
82 match written {
83 Ok(Some(created)) => Ok(created),
84 // Uncapped, so a zero-row claim can only mean the conditional
85 // write matched no year row at all — the claim doubles as the
86 // existence check.
87 Ok(None) => Err(year_gone()),
88 // The year row is locked by the claim's own UPDATE, so this
89 // is unreachable; a defensible answer beats a 500.
90 Err(e) if crate::database::foreign_key_violation(&e) => Err(year_gone()),
91 // Unreachable: the id was minted one line above.
92 Err(e) if crate::database::unique_violation(&e).is_some() => {
93 Err(AppError::Internal("failed to create class".into()))
94 }
95 Err(e) => Err(e.into()),
96 }
97 }
98 None => {
99 let created = sqlx::query_as!(
100 ClassGroup,
101 r#"INSERT INTO class_group (id, creator, name, grade_level, year, teacher)
102 VALUES ($1, $2, $3, $4, $5, $6)
103 RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId",
104 name AS "name: ClassName", grade_level AS "grade_level: GradeLevel",
105 year AS "year: AcademicYearId", teacher AS "teacher: UserId""#,
106 id.uuid(),
107 creator.uuid(),
108 name.as_str(),
109 grade_level.get(),
110 year.as_ref().map(AcademicYearId::uuid),
111 teacher.as_ref().map(UserId::uuid)
112 )
113 .fetch_optional(db)
114 .await?;
115 // Unreachable: the id is a v7 uuid this call just generated.
116 created.ok_or_else(|| AppError::Internal("failed to create class".into()))
117 }
118 }
119}
120
121pub async fn read(db: &Database, id: &ClassGroupId) -> Result<Option<ClassGroup>, AppError> {
122 let class = sqlx::query_as!(
123 ClassGroup,
124 r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId",
125 name AS "name: ClassName", grade_level AS "grade_level: GradeLevel",
126 year AS "year: AcademicYearId", teacher AS "teacher: UserId"
127 FROM class_group WHERE id = $1"#,
128 id.uuid()
129 )
130 .fetch_optional(db)
131 .await?;
132 Ok(class)
133}
134
135/// Every class, newest first — or one rung's, when `grade_level` narrows it:
136/// `Some(level)` is the sections carrying that exact ladder position (the
137/// same equality [`list_for_grade`] and the blueprint keyed by that rung
138/// use), `None` the whole list.
139///
140/// The narrowing is the `WHERE`, so the `total` [`PagedList`] counts is the
141/// filtered set and a client can page through it.
142pub async fn list_all(
143 db: &Database,
144 grade_level: Option<GradeLevel>,
145 limit: Option<i64>,
146 offset: i64,
147) -> Result<(Vec<ClassGroup>, i64), AppError> {
148 let list = match grade_level {
149 None => PagedList::new(CLASS_GROUP_TABLE, "ORDER BY id DESC"),
150 Some(grade_level) => PagedList::new(
151 format!("{CLASS_GROUP_TABLE} WHERE grade_level = $1"),
152 "ORDER BY id DESC",
153 )
154 .bind(grade_level.get() as i64),
155 };
156 list.run(limit, offset, db).await
157}
158
159/// Write only the fields the PATCH carried — `None` means the request
160/// omitted it, so the column is left alone rather than re-stated from the
161/// snapshot this struct was read into. `grade_level` is a plain `Option`
162/// (the column is NOT NULL: a PATCH may set a rung, never clear it);
163/// `year` and `teacher` are nullable, so they take the outer/inner
164/// `Option<Option<_>>`: `None` = omitted (keep), `Some(None)` = clear.
165///
166/// A year move claims the new year and releases the old one inside the very
167/// transaction that moves the link, exactly as in
168/// [`crate::db::course::update`] did for the term: both counters and the link
169/// commit together, so no crash can strand a count on a year nothing links.
170pub async fn update(
171 db: &Database,
172 class: ClassGroup,
173 name: Option<ClassName>,
174 grade_level: Option<GradeLevel>,
175 year: Option<Option<AcademicYearId>>,
176 teacher: Option<Option<UserId>>,
177) -> Result<ClassGroup, AppError> {
178 let (claim, release) = year_ref_move(class.year.as_ref(), &year);
179 let expected = class.year.as_ref().map(AcademicYearId::uuid);
180 FieldUpdate::new(CLASS_GROUP_TABLE, class.id.uuid())
181 .set("name", name.map(|name| name.as_str().to_string()))
182 // `Param` has no i16 arm (and db/page.rs is a shared seam): the rung
183 // rides as BIGINT, which Postgres assignment-casts into the SMALLINT
184 // column.
185 .set("grade_level", grade_level.map(|grade| grade.get() as i64))
186 .set("year", year.map(|year| year.map(|year| year.uuid())))
187 // Not refcounted: a homeroom assignment is a label, so it rides the
188 // plain `set` path and never arms the year CAS.
189 .set(
190 "teacher",
191 teacher.map(|teacher| teacher.map(|teacher| teacher.uuid())),
192 )
193 .refcount(Refcount {
194 counter_table: "academic_year",
195 counter_field: ACADEMIC_YEAR_CLASS_COUNT_FIELD,
196 link: "year",
197 expected,
198 claim: claim.map(|year| year.uuid()),
199 release: release.map(|year| year.uuid()),
200 refused: year_gone(),
201 })
202 .run::<ClassGroup>(db)
203 .await
204}
205
206/// The classes `ids` name, in no particular order — the join behind
207/// "which class section is this student in", where the ids come from
208/// `class_member` rows already paged. Ids that name no row are simply
209/// absent.
210pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result<Vec<ClassGroup>, AppError> {
211 if ids.is_empty() {
212 return Ok(Vec::new());
213 }
214 let ids: Vec<uuid::Uuid> = ids.iter().map(ClassGroupId::uuid).collect();
215 let classes = sqlx::query_as!(
216 ClassGroup,
217 r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId",
218 name AS "name: ClassName", grade_level AS "grade_level: GradeLevel",
219 year AS "year: AcademicYearId", teacher AS "teacher: UserId"
220 FROM class_group WHERE id = ANY($1)"#,
221 &ids
222 )
223 .fetch_all(db)
224 .await?;
225 Ok(classes)
226}
227
228/// Every class section at one ladder rung, in no particular order — what a
229/// grade blueprint pumps. Unpaged on purpose: the caller is reconciling all
230/// of them, and a page would silently stock only the first window.
231pub async fn list_for_grade(
232 db: &Database,
233 grade_level: GradeLevel,
234) -> Result<Vec<ClassGroup>, AppError> {
235 let classes = sqlx::query_as!(
236 ClassGroup,
237 r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId",
238 name AS "name: ClassName", grade_level AS "grade_level: GradeLevel",
239 year AS "year: AcademicYearId", teacher AS "teacher: UserId"
240 FROM class_group WHERE grade_level = $1"#,
241 grade_level.get()
242 )
243 .fetch_all(db)
244 .await?;
245 Ok(classes)
246}
247
248/// Every class of one academic year, newest first — the rollover's input list
249/// ([`crate::service::academic_year::rollover`]). Unpaged for the same reason
250/// [`list_for_grade`] is: the caller reconciles all of them.
251pub async fn list_for_year(
252 db: &Database,
253 year: &AcademicYearId,
254) -> Result<Vec<ClassGroup>, AppError> {
255 let classes = sqlx::query_as!(
256 ClassGroup,
257 r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId",
258 name AS "name: ClassName", grade_level AS "grade_level: GradeLevel",
259 year AS "year: AcademicYearId", teacher AS "teacher: UserId"
260 FROM class_group WHERE year = $1 ORDER BY id"#,
261 year.uuid()
262 )
263 .fetch_all(db)
264 .await?;
265 Ok(classes)
266}
267
268/// Every class `user` is the homeroom teacher of, newest first — the same
269/// order [`list_all`] gives, since this is a narrowing of that list and not a
270/// second one.
271///
272/// It is the read behind "which sections do I run": the homeroom teacher of a
273/// section may act on every instance of it (D10, the third arm of
274/// [`crate::service::class_course::ensure_instance_teacher`]) without being a
275/// member of it or assigned to the instance — and without a read like this the
276/// section would be invisible to them, so their own instances' exams,
277/// sessions and homework could not be listed at all.
278///
279/// Unpaged like [`list_for_grade`] and [`list_for_year`]: the caller resolves
280/// a *visible set*, and a page would silently hide the sections past the
281/// window. A user who homerooms nothing — including one every sweep has
282/// cleared (`unassign_everywhere`) — simply gets an empty list.
283pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<ClassGroup>, AppError> {
284 let classes = sqlx::query_as!(
285 ClassGroup,
286 r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId",
287 name AS "name: ClassName", grade_level AS "grade_level: GradeLevel",
288 year AS "year: AcademicYearId", teacher AS "teacher: UserId"
289 FROM class_group WHERE teacher = $1 ORDER BY id DESC"#,
290 user.uuid()
291 )
292 .fetch_all(db)
293 .await?;
294 Ok(classes)
295}
296
297/// Clear the homeroom teacher everywhere `user` held one — the
298/// sweep for a user demoted below `teacher`, who may no longer hold one.
299/// The mirror of [`crate::db::course::unassign_everywhere`];
300/// nothing is counted on this column, so there is no reference to give back.
301pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {
302 sqlx::query!(
303 r#"UPDATE class_group SET teacher = NULL WHERE teacher = $1"#,
304 user.uuid()
305 )
306 .execute(db)
307 .await?;
308 Ok(())
309}
310
311/// Delete the class and give its academic-year reference back. A class that
312/// still holds students or courses is refused outright, because dropping it
313/// silently would leave the enrollments it pumped behind with nothing left to
314/// sweep them. What the guard cannot see is the *history* standing beside the
315/// live rows, and that is what this delete sweeps first: every `class_member`
316/// stint of the class (a soft-left student holds no seat, so the 0/0 guard
317/// passes while their row still stands, and `class_member.class` would refuse
318/// the delete as a `23503`), plus the provenance tags naming it from rows that
319/// outlive it — a rollover copy's `source_class_group` and a handed-over
320/// enrollment's `source`, both hard foreign keys into this table. Dropping a
321/// section takes its own history with it; a row that merely *remembers* the section
322/// keeps standing, untagged. An event aimed at the class keeps standing with
323/// `audience_class` cleared — the course twin's documented outcome
324/// (`db::course::delete`): the roster resolves live, so it simply reads empty.
325///
326/// `false` = refused, nothing was written — not even the sweeps below. The
327/// guard locks the class row (`FOR UPDATE`) and reads its own two counters, so
328/// a member or an attach racing this either claims first (and the delete is
329/// refused, untouched) or finds the row gone (and is refused itself).
330/// `Err(NotFound)` keeps the answer a concurrent *delete* used to get — and
331/// unlike the old one-statement guard, this one tells the two apart without a
332/// second read. The row lock is what makes the sweeps safe to run before the
333/// final delete: no counter can move under this transaction, so the verdict
334/// this read settled is still the verdict when the children are gone.
335pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError> {
336 tx_with_retry(db, false, async move |tx| {
337 // The guard and the lock, in one read — the shape
338 // [`crate::db::course::delete`] uses. A refused delete must leave the
339 // class's history exactly as it found it, so nothing may be swept
340 // until this verdict is in.
341 let guard = sqlx::query!(
342 r#"SELECT class_member_count, class_course_count, year AS "year: uuid::Uuid"
343 FROM class_group WHERE id = $1 FOR UPDATE"#,
344 class.id.uuid()
345 )
346 .fetch_optional(&mut *tx)
347 .await?;
348 let Some(guard) = guard else {
349 return Err(AppError::NotFound);
350 };
351 if guard.class_member_count != 0 || guard.class_course_count != 0 {
352 return Ok(false);
353 }
354 // Events aimed at this class keep standing, audience cleared — the
355 // hard FK on `event.audience_class` would otherwise refuse the delete
356 // outright, and a dangling audience resolves to an empty roster.
357 sqlx::query!(
358 r#"UPDATE event SET audience_class = NULL WHERE audience_class = $1"#,
359 class.id.uuid()
360 )
361 .execute(&mut *tx)
362 .await?;
363 // The roster history goes with the section. The 0/0 guard counts *live*
364 // stints, so a class whose last student soft-left passes it with the
365 // history row still standing — and `class_member.class` is a hard
366 // foreign key, which would answer the delete below as a `23503`.
367 sqlx::query!(
368 r#"DELETE FROM class_member WHERE class = $1"#,
369 class.id.uuid()
370 )
371 .execute(&mut *tx)
372 .await?;
373 // …and the same key from the *other* side: a stint another section holds
374 // remembers where it came from (a rollover copy's `source_class_group`)
375 // and an enrollment a class wrote remembers which class pumped it
376 // (its `source`). Both are hard keys into this row, so both would
377 // refuse the delete. The rows outlive the section and stay; only the tag
378 // goes.
379 sqlx::query!(
380 r#"UPDATE class_member SET source_class_group = NULL WHERE source_class_group = $1"#,
381 class.id.uuid()
382 )
383 .execute(&mut *tx)
384 .await?;
385 sqlx::query!(
386 r#"UPDATE enrollment SET source = NULL WHERE source = $1"#,
387 class.id.uuid()
388 )
389 .execute(&mut *tx)
390 .await?;
391 // Last, and FK-silent: every child row whose key names this class is
392 // either taken or untagged by now.
393 sqlx::query!(r#"DELETE FROM class_group WHERE id = $1"#, class.id.uuid())
394 .execute(&mut *tx)
395 .await?;
396 if let Some(year) = guard.year {
397 sqlx::query!(
398 r#"UPDATE academic_year
399 SET class_count = GREATEST(class_count - 1, 0)
400 WHERE id = $1"#,
401 year
402 )
403 .execute(&mut *tx)
404 .await?;
405 }
406 Ok(true)
407 })
408 .await
409}
410
411#[cfg(test)]
412mod tests {
413 use super::*;
414 use sqlx::Row as _;
415
416 use crate::domain::academic_year::{AcademicYear, AcademicYearName};
417
418 /// A real `app_user` row: creator, teacher, and attached-by are foreign
419 /// keys now, so every fixture participant is a row, not a fabricated id.
420 async fn a_named_user(db: &Database, username: &str) -> UserId {
421 // The username is unique: a second call for the same name must adopt
422 // the existing row, not collide with it.
423 sqlx::query(
424 "INSERT INTO app_user (id, username, created_at, role) \
425 VALUES ($1, $2, 0, 'teacher') ON CONFLICT DO NOTHING",
426 )
427 .bind(UserId::generate().uuid())
428 .bind(username)
429 .execute(db)
430 .await
431 .unwrap();
432 let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1")
433 .bind(username)
434 .fetch_one(db)
435 .await
436 .unwrap()
437 .try_get(0)
438 .unwrap();
439 UserId::from_key(&id.to_string())
440 }
441
442 /// A real academic year: the section's year link is a foreign key now, and
443 /// the class-count claim it carries is what these tests are about.
444 async fn a_year(name: &str, db: &Database) -> AcademicYear {
445 let at = crate::domain::timestamp::Timestamp::from_millis;
446 crate::db::academic_year::create(
447 db,
448 &a_named_user(db, "manager").await,
449 AcademicYearName::try_new(name).unwrap(),
450 at(100),
451 at(200),
452 Vec::new(),
453 )
454 .await
455 .unwrap()
456 }
457
458 async fn class_on(year: Option<AcademicYearId>, db: &Database) -> ClassGroup {
459 let manager = a_named_user(db, "manager").await;
460 create(
461 db,
462 &manager,
463 ClassName::try_new("9-A").unwrap(),
464 GradeLevel::new(9).unwrap(),
465 year,
466 None,
467 )
468 .await
469 .unwrap()
470 }
471
472 /// A class with a homeroom teacher, no year.
473 async fn class_of(teacher: Option<UserId>, db: &Database) -> ClassGroup {
474 let manager = a_named_user(db, "manager").await;
475 create(
476 db,
477 &manager,
478 ClassName::try_new("9-A").unwrap(),
479 GradeLevel::new(9).unwrap(),
480 None,
481 teacher,
482 )
483 .await
484 .unwrap()
485 }
486
487 /// The stored `teacher` column, re-read.
488 async fn teacher_of(class: &ClassGroupId, db: &Database) -> Option<UserId> {
489 read(db, class)
490 .await
491 .unwrap()
492 .unwrap()
493 .get_teacher()
494 .cloned()
495 }
496
497 /// The single integer `sql` selects — the stored counter, re-read, never
498 /// off a return value. The SQL is built from literals in this module, so
499 /// the audit wrapper is a formality.
500 async fn one_i64(db: &Database, sql: String) -> i64 {
501 sqlx::query(sqlx::AssertSqlSafe(sql))
502 .fetch_one(db)
503 .await
504 .unwrap()
505 .try_get::<i64, _>(0)
506 .unwrap()
507 }
508
509 /// The stored `class_count` on one academic year, absent counting as zero.
510 async fn count_on(year: &AcademicYearId, db: &Database) -> i64 {
511 one_i64(
512 db,
513 format!(
514 "SELECT COALESCE(class_count, 0) FROM academic_year WHERE id = '{}'",
515 year.uuid()
516 ),
517 )
518 .await
519 }
520
521 /// How many rows `table` holds.
522 async fn row_count(db: &Database, table: &str) -> i64 {
523 one_i64(db, format!("SELECT count(*) FROM {table}")).await
524 }
525
526 /// The homeroom teacher survives a create, is set and cleared by a PATCH,
527 /// and — the part a `.content(self)` save would break — is left alone by a
528 /// PATCH of another field. A row written before the column exists carries
529 /// no key at all, which must read back as `None`, not fail the decode.
530 #[tokio::test]
531 async fn the_homeroom_teacher_is_stored_set_cleared_and_left_alone() {
532 let (db, _leases) = crate::database::init_test_db().await;
533 let ada = a_named_user(&db, "ada").await;
534 let boole = a_named_user(&db, "boole").await;
535
536 let bare = class_of(None, &db).await;
537 assert_eq!(teacher_of(bare.get_id(), &db).await, None);
538 let held = class_of(Some(ada), &db).await;
539 assert_eq!(teacher_of(held.get_id(), &db).await, Some(ada));
540
541 // A name-only PATCH must not re-state the teacher out of its snapshot.
542 let renamed = update(
543 &db,
544 held,
545 Some(ClassName::try_new("9-B").unwrap()),
546 None,
547 None,
548 None,
549 )
550 .await
551 .unwrap();
552 assert_eq!(renamed.get_name().as_str(), "9-B");
553 assert_eq!(teacher_of(renamed.get_id(), &db).await, Some(ada));
554
555 let moved = update(&db, renamed, None, None, None, Some(Some(boole)))
556 .await
557 .unwrap();
558 assert_eq!(teacher_of(moved.get_id(), &db).await, Some(boole));
559
560 let cleared = update(&db, moved, None, None, None, Some(None))
561 .await
562 .unwrap();
563 assert_eq!(teacher_of(cleared.get_id(), &db).await, None);
564
565 // …and the mirror: a teacher-only PATCH leaves the name alone.
566 let again = update(
567 &db,
568 cleared,
569 None,
570 None,
571 None,
572 Some(Some(a_named_user(&db, "ada").await)),
573 )
574 .await
575 .unwrap();
576 assert_eq!(again.get_name().as_str(), "9-B");
577
578 // A row without a homeroom: the column reads back as NULL, not a
579 // decode failure.
580 sqlx::query("UPDATE class_group SET teacher = NULL WHERE id = $1")
581 .bind(bare.get_id().uuid())
582 .execute(&db)
583 .await
584 .unwrap();
585 assert_eq!(teacher_of(bare.get_id(), &db).await, None);
586 }
587
588 /// The demotion sweep: a user who drops below `teacher` is cleared from
589 /// *every* class they homeroomed, and nobody else's is touched.
590 #[tokio::test]
591 async fn unassign_everywhere_clears_only_that_users_classes() {
592 let (db, _leases) = crate::database::init_test_db().await;
593 let ada = a_named_user(&db, "ada").await;
594 let boole = a_named_user(&db, "boole").await;
595 let first = class_of(Some(ada), &db).await;
596 let second = class_of(Some(ada), &db).await;
597 let other = class_of(Some(boole), &db).await;
598 let none = class_of(None, &db).await;
599
600 unassign_everywhere(&db, &ada).await.unwrap();
601 for class in [&first, &second] {
602 assert_eq!(
603 teacher_of(class.get_id(), &db).await,
604 None,
605 "every class the demoted user homeroomed must be cleared"
606 );
607 }
608 assert_eq!(
609 teacher_of(other.get_id(), &db).await,
610 Some(boole),
611 "…and nobody else's"
612 );
613 assert_eq!(teacher_of(none.get_id(), &db).await, None);
614 }
615
616 /// The bite test for the class half of the academic-year delete guard
617 /// (D3): a year is undeletable while a *section* links it, on its own
618 /// column, and every way that link can end gives the reference back.
619 /// Claiming into `term_count` instead would pass the first assert and
620 /// fail the roundtrip through the year's own delete.
621 #[tokio::test]
622 async fn a_year_is_deletable_only_once_no_class_links_it() {
623 let (db, _leases) = crate::database::init_test_db().await;
624 let year = a_year("2026-2027", &db).await;
625
626 let linked = class_on(Some(*year.get_id()), &db).await;
627 let patched = class_on(Some(*year.get_id()), &db).await;
628 assert_eq!(
629 one_i64(
630 &db,
631 "SELECT COALESCE(class_count, 0) FROM academic_year".to_string()
632 )
633 .await,
634 2,
635 "classes must count on class_count, not term_count"
636 );
637 assert_eq!(
638 one_i64(
639 &db,
640 "SELECT COALESCE(term_count, 0) FROM academic_year".to_string()
641 )
642 .await,
643 0,
644 "the terms' counter is seeded from term rows and must stay untouched"
645 );
646 assert!(
647 !crate::db::academic_year::delete(&db, year.clone())
648 .await
649 .unwrap(),
650 "two linked classes must refuse the delete"
651 );
652
653 update(&db, patched, None, None, Some(None), None)
654 .await
655 .unwrap();
656 assert!(
657 !crate::db::academic_year::delete(&db, year.clone())
658 .await
659 .unwrap(),
660 "one link is still one link"
661 );
662
663 assert!(delete(&db, linked).await.unwrap());
664 assert!(
665 crate::db::academic_year::delete(&db, year.clone())
666 .await
667 .unwrap(),
668 "the last link gone, the year may go"
669 );
670 let again = crate::db::academic_year::delete(&db, year).await;
671 assert!(
672 matches!(again, Err(AppError::NotFound)),
673 "a second delete is a 404, not a refusal: {again:?}"
674 );
675 }
676
677 /// The bite test for the class delete guard, both arms: either count above
678 /// zero refuses, having written nothing — the year reference least of all,
679 /// which a refusal that released it would strand.
680 #[tokio::test]
681 async fn a_class_with_members_or_courses_refuses_to_delete() {
682 for field in ["class_member_count", "class_course_count"] {
683 let (db, _leases) = crate::database::init_test_db().await;
684 let year = a_year("2026-2027", &db).await;
685 let class = class_on(Some(*year.get_id()), &db).await;
686 sqlx::query(sqlx::AssertSqlSafe(format!(
687 "UPDATE class_group SET {field} = 1 WHERE id = $1"
688 )))
689 .bind(class.get_id().uuid())
690 .execute(&db)
691 .await
692 .unwrap();
693
694 assert!(
695 !delete(&db, class.clone()).await.unwrap(),
696 "{field} above zero must refuse the delete"
697 );
698 assert!(
699 read(&db, class.get_id()).await.unwrap().is_some(),
700 "a refused delete may write nothing"
701 );
702 assert_eq!(
703 count_on(year.get_id(), &db).await,
704 1,
705 "…the year reference least of all"
706 );
707
708 // Back to zero, and the same class deletes and releases the year.
709 sqlx::query(sqlx::AssertSqlSafe(format!(
710 "UPDATE class_group SET {field} = 0 WHERE id = $1"
711 )))
712 .bind(class.get_id().uuid())
713 .execute(&db)
714 .await
715 .unwrap();
716 assert!(delete(&db, class.clone()).await.unwrap());
717 assert_eq!(count_on(year.get_id(), &db).await, 0);
718 let again = delete(&db, class).await;
719 assert!(
720 matches!(again, Err(AppError::NotFound)),
721 "a second delete is a 404, not a refusal: {again:?}"
722 );
723 }
724 }
725
726 /// The class half of the invariant on the create path: a refused create
727 /// leaves neither the row nor a count stranded on a year (which the year's
728 /// delete guard reads, so a stray one would make it undeletable forever).
729 #[tokio::test]
730 async fn a_refused_create_writes_neither_row_nor_count() {
731 let (db, _leases) = crate::database::init_test_db().await;
732 let year = a_year("2026-2027", &db).await;
733 let id = *year.get_id();
734 assert!(crate::db::academic_year::delete(&db, year).await.unwrap());
735
736 let error = create(
737 &db,
738 &a_named_user(&db, "manager").await,
739 ClassName::try_new("9-A").unwrap(),
740 GradeLevel::anaokulu(),
741 Some(id),
742 None,
743 )
744 .await
745 .expect_err("a year that is gone must not be linkable");
746 assert!(error.to_string().contains("academic year does not exist"));
747 assert_eq!(
748 row_count(&db, "class_group").await,
749 0,
750 "a refused create may write no row"
751 );
752 assert_eq!(
753 row_count(&db, "academic_year").await,
754 0,
755 "…and least of all a count on a year it just brought back"
756 );
757 }
758
759 /// The class mirror of
760 /// [`crate::db::course`]'s move tests: a year move carries the count with
761 /// the link, and a move to a year that is gone rolls the release back with
762 /// the abort (the transaction releases before it claims, so the old count
763 /// would be 0 if the abort did not undo it).
764 #[tokio::test]
765 async fn a_class_year_move_moves_the_count_or_neither() {
766 let (db, _leases) = crate::database::init_test_db().await;
767 let from = a_year("2026-2027", &db).await;
768 let to = a_year("2027-2028", &db).await;
769 let dead = a_year("2028-2029", &db).await;
770 let dead_id = *dead.get_id();
771 assert!(crate::db::academic_year::delete(&db, dead).await.unwrap());
772 let class = class_on(Some(*from.get_id()), &db).await;
773
774 let error = update(
775 &db,
776 class.clone(),
777 Some(ClassName::try_new("9-B").unwrap()),
778 None,
779 Some(Some(dead_id)),
780 None,
781 )
782 .await
783 .expect_err("a year that is gone must not be linkable");
784 assert!(error.to_string().contains("academic year does not exist"));
785 let stored = read(&db, class.get_id()).await.unwrap().unwrap();
786 assert_eq!(stored.get_year(), Some(from.get_id()), "the link stays put");
787 assert_eq!(stored.get_name().as_str(), "9-A", "…and so does the row");
788 assert_eq!(
789 count_on(from.get_id(), &db).await,
790 1,
791 "the release must roll back with the abort"
792 );
793
794 let moved = update(&db, class, None, None, Some(Some(*to.get_id())), None)
795 .await
796 .unwrap();
797 assert_eq!(moved.get_year(), Some(to.get_id()));
798 assert_eq!(
799 count_on(from.get_id(), &db).await,
800 0,
801 "the old year is free"
802 );
803 assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");
804 }
805
806 /// The class twin of [`crate::db::course`]'s
807 /// `a_stale_mover_is_refused_and_claims_nothing` and
808 /// `a_stale_re_stater_is_refused_and_reverts_nothing`, in one: both
809 /// PATCHes compute their counter move from the row as *they* read it, so a
810 /// second one running on the pre-move struct would claim a second seat for
811 /// one link (the mover) or drag the link back and strand the winner's claim
812 /// (the re-stater, which shifts no counter at all and so is only ever
813 /// stopped by a guard armed off the *carried column*). Both must be refused
814 /// with the counts reading as if they never ran.
815 #[tokio::test]
816 async fn a_stale_class_year_write_is_refused_and_moves_no_count() {
817 let (db, _leases) = crate::database::init_test_db().await;
818 let from = a_year("2026-2027", &db).await;
819 let to = a_year("2027-2028", &db).await;
820 let other = a_year("2028-2029", &db).await;
821 let class = class_on(Some(*from.get_id()), &db).await;
822 let stale = class.clone();
823 update(&db, class, None, None, Some(Some(*to.get_id())), None)
824 .await
825 .unwrap();
826
827 // The mover: its snapshot says `from`, so it would release `from` and
828 // claim `other` on top of the winner's claim on `to`.
829 let error = update(
830 &db,
831 stale.clone(),
832 None,
833 None,
834 Some(Some(*other.get_id())),
835 None,
836 )
837 .await
838 .expect_err("a mover that read a link it no longer holds must be refused");
839 assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
840 // The re-stater: shifts no counter, so only the CAS can stop it.
841 let error = update(
842 &db,
843 stale.clone(),
844 None,
845 None,
846 Some(Some(*from.get_id())),
847 None,
848 )
849 .await
850 .expect_err("re-stating a link someone else moved must be refused");
851 assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
852
853 let stored = read(&db, stale.get_id()).await.unwrap().unwrap();
854 assert_eq!(stored.get_year(), Some(to.get_id()), "the winner's link");
855 assert_eq!(count_on(from.get_id(), &db).await, 0, "released once");
856 assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once");
857 assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed");
858
859 // A genuine no-op re-state still lands and still moves nothing.
860 let same = update(&db, stored, None, None, Some(Some(*to.get_id())), None)
861 .await
862 .expect("re-stating the link the row really holds is not a conflict");
863 assert_eq!(same.get_year(), Some(to.get_id()));
864 assert_eq!(count_on(to.get_id(), &db).await, 1, "still one seat");
865 }
866
867 /// The delete guard counts *live* stints, and a soft-left student holds
868 /// none — so the class passes it with the history row still standing, and
869 /// `class_member.class` (a hard foreign key) is what used to answer this
870 /// delete, as a `23503` the route turns into a 500. The roster history
871 /// goes with the section it belongs to.
872 #[tokio::test]
873 async fn a_soft_left_member_does_not_block_the_delete_and_goes_with_it() {
874 use crate::db::class_pump::{self, Attached};
875
876 let (db, _leases) = crate::database::init_test_db().await;
877 let manager = a_named_user(&db, "manager").await;
878 let class = class_of(None, &db).await;
879 // The pump's member axis claims the `student` role on the user row,
880 // and a stint is a real write, not a row fabricated into place.
881 let student = a_named_user(&db, "ada").await;
882 sqlx::query("UPDATE app_user SET role = 'student' WHERE id = $1")
883 .bind(student.uuid())
884 .execute(&db)
885 .await
886 .unwrap();
887 assert!(matches!(
888 class_pump::add_member(&db, class.get_id(), &student, &manager)
889 .await
890 .unwrap(),
891 Attached::Made(_)
892 ));
893
894 assert_eq!(
895 class_pump::leave_member(&db, class.get_id(), &student)
896 .await
897 .unwrap(),
898 1,
899 "the one live stint is the one the leave ends"
900 );
901 // Exactly what the guard is blind to: the counters read zero, the
902 // history does not.
903 assert_eq!(
904 one_i64(
905 &db,
906 format!(
907 "SELECT class_member_count FROM class_group WHERE id = '{}'",
908 class.get_id().uuid()
909 )
910 )
911 .await,
912 0
913 );
914 assert_eq!(row_count(&db, "class_member").await, 1);
915
916 assert!(
917 delete(&db, class.clone()).await.unwrap(),
918 "a soft-left member must not block the delete"
919 );
920 assert_eq!(
921 row_count(&db, "class_member").await,
922 0,
923 "…and the roster history goes with the şube"
924 );
925 assert!(
926 matches!(delete(&db, class).await, Err(AppError::NotFound)),
927 "a second delete is still a 404"
928 );
929 }
930}