forge
Explore
Log in

Don't you dare go Hollow

🚧 wip: class-pump/meals/homework production fixes + T5 test-port continuation

Browse files at this commit

35683ac646cda318a2272bc1b1507d511cef9e13Ahmet Kaan GümüşParent: af331ec

83 changed files +2227 -1955

src/ai/server.rsmodified+1 -3
@@ -1077,9 +1077,7 @@ mod tests {
1077 async fn armed(router: axum::Router) -> ApiHandle {1077 async fn armed(router: axum::Router) -> ApiHandle {
1078 ApiHandle {1078 ApiHandle {
1079 router,1079 router,
1080- tenants: crate::database::init_mem_tenants()1080+ tenants: crate::database::init_test_tenants().await,
1081- .await
1082- .expect("in-memory deployment"),
1083 files_path: std::env::temp_dir(),1081 files_path: std::env::temp_dir(),
1084 }1082 }
1085 }1083 }
src/db/answer_image.rsmodified+4 -4
@@ -240,12 +240,12 @@ mod tests {
240 }240 }
241 241
242 fn student() -> UserId {242 fn student() -> UserId {
243- UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA")243+ UserId::from_key("019732e3-7b00-7000-8000-00000000a11a")
244 }244 }
245 245
246 #[tokio::test]246 #[tokio::test]
247 async fn upsert_replaces_within_a_sitting_but_not_across_them() {247 async fn upsert_replaces_within_a_sitting_but_not_across_them() {
248- let db = crate::database::init_mem().await.unwrap();248+ let (db, _leases) = crate::database::init_test_db().await;
249 let exam = exam_row(&db).await;249 let exam = exam_row(&db).await;
250 let question = ExamQuestionId::generate();250 let question = ExamQuestionId::generate();
251 let user = student();251 let user = student();
@@ -287,7 +287,7 @@ mod tests {
287 );287 );
288 288
289 // Another student's drawing for the same question/sitting is its own row.289 // Another student's drawing for the same question/sitting is its own row.
290- let other = UserId::from_key("01TESTSTUDENTBBBBBBBBBBBBB");290+ let other = UserId::from_key("019732e3-7b00-7000-8000-00000000b22b");
291 upsert(&db, AnswerImage::new(&exam, &question, &other, 1, png(), 7))291 upsert(&db, AnswerImage::new(&exam, &question, &other, 1, png(), 7))
292 .await292 .await
293 .unwrap();293 .unwrap();
@@ -297,7 +297,7 @@ mod tests {
297 297
298 #[tokio::test]298 #[tokio::test]
299 async fn listing_scopes_by_exam_and_user() {299 async fn listing_scopes_by_exam_and_user() {
300- let db = crate::database::init_mem().await.unwrap();300+ let (db, _leases) = crate::database::init_test_db().await;
301 let exam_a = exam_row(&db).await;301 let exam_a = exam_row(&db).await;
302 let exam_b = exam_row(&db).await;302 let exam_b = exam_row(&db).await;
303 let user = student();303 let user = student();
src/db/attendance.rsmodified+52 -34
@@ -130,59 +130,77 @@ mod tests {
130 use crate::domain::settings::Settings;130 use crate::domain::settings::Settings;
131 131
132 /// The session twin's race, one table over132 /// The session twin's race, one table over
133- /// ([`crate::db::session_attendance::mark`]): a133+ /// ([`crate::db::session_attendance::mark`]): the event's delete sweeps its
134- /// `DEFINE EVENT` on `event` fires inside the delete's own transaction, and134+ /// attendance rows and removes the row in one transaction, and a mark that
135- /// the event's delete sweeps its attendance rows before removing the row, so135+ /// wrote into the gap was a bare upsert nothing would ever sweep again.
136- /// the `SLEEP` lands exactly between the sweep and the commit — the window136+ /// The mark now writes the event row too (its seats counter), so the two
137- /// where a bare upsert wrote a mark nothing would ever sweep again.137+ /// transactions touch one row and Postgres refuses one of them; the barrier
138- ///138+ /// releases both sides together so every interleaving gets its chance.
139- /// Real server, and `#[ignore]`d for it: the subject is the store's139+ /// Mutation-tested: turning the claim back into a read turns it red.
140- /// conflict detection, which `init_mem`'s embedded engine does not have —
141- /// it commits both writes and answers `Ok` to each, so this passes there on
142- /// broken code. Mutation-tested: turning the claim back into a read
143- /// (`SELECT VALUE id FROM $ev`) turns it red.
144 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]140 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
145- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
146 async fn a_mark_written_inside_a_delete_never_outlives_the_event() {141 async fn a_mark_written_inside_a_delete_never_outlives_the_event() {
147- use crate::domain::event::{EventAudience, EventDescription, EventTitle};142+ use crate::domain::event::{
148- let (db, _serialized) = crate::database::init_test_server("event_attendance_race").await;143+ EventAudience, EventAudienceKind, EventDescription, EventTitle,
149- db.query(144+ };
150- "DEFINE EVENT hold_the_window ON TABLE event WHEN $event = 'DELETE' \
151- THEN { SLEEP 1s; };",
152- )
153- .await
154- .unwrap()
155- .check()
156- .unwrap();
157 145
146+ // A real `app_user` row: markers, students and event creators are
147+ // foreign keys now.
148+ async fn a_person(db: &Database, label: &str) -> UserId {
149+ let user = UserId::generate();
150+ sqlx::query(
151+ "INSERT INTO app_user (id, username, password_hash, role) \
152+ VALUES ($1, $2, 'x', 'teacher')",
153+ )
154+ .bind(user.uuid())
155+ .bind(format!("{label}-{}", &user.key()[..8]))
156+ .execute(db)
157+ .await
158+ .unwrap();
159+ user
160+ }
161+
162+ let (db, _leases) = crate::database::init_test_db().await;
158 let allowed: Vec<String> = Settings::defaults().get_attendance_statuses().to_vec();163 let allowed: Vec<String> = Settings::defaults().get_attendance_statuses().to_vec();
159- let marker = UserId::from_key("t");164+ let marker = a_person(&db, "marker").await;
160 let (mut swept, mut orphans) = (0, 0);165 let (mut swept, mut orphans) = (0, 0);
161- for round in 0..4 {166+ for round in 0..8 {
162 let event = crate::db::event::create(167 let event = crate::db::event::create(
163 &db,168 &db,
164 &marker,169 &marker,
165 EventTitle::try_new("gezi").unwrap(),170 EventTitle::try_new("gezi").unwrap(),
166 EventDescription::try_new("").unwrap(),171 EventDescription::try_new("").unwrap(),
167- EventAudience::School,172+ EventAudience {
173+ kind: EventAudienceKind::School,
174+ role: None,
175+ course: None,
176+ class: None,
177+ capacity: None,
178+ },
168 None,179 None,
169 None,180 None,
170 )181 )
171 .await182 .await
172 .unwrap();183 .unwrap();
173 let id = event.get_id().clone();184 let id = event.get_id().clone();
185+
186+ // Delete and mark released together: both write the event row, so
187+ // Postgres serializes them and refuses whichever lost.
188+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
174 let drop_it = {189 let drop_it = {
175- let db = db.clone();190+ let (db, gate, event) = (db.clone(), gate.clone(), event);
176- tokio::spawn(async move { crate::db::event::delete(&db, event).await })191+ tokio::spawn(async move {
192+ gate.wait().await;
193+ crate::db::event::delete(&db, event).await
194+ })
177 };195 };
178- // The mark starts inside the held window: the sweep has run and the
179- // event row is gone but uncommitted.
180- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
181 let marked = {196 let marked = {
182- let (db, id, marker) = (db.clone(), id.clone(), marker.clone());197+ let (db, id, marker, gate) = (db.clone(), id.clone(), marker.clone(), gate);
183- let student = UserId::from_key(&format!("s{round}"));198+ let student = a_person(&db, "student").await;
184 let status = AttendanceStatus::try_new("present", &allowed).unwrap();199 let status = AttendanceStatus::try_new("present", &allowed).unwrap();
185- tokio::spawn(async move { mark(&db, &id, &student, status, &marker).await })200+ tokio::spawn(async move {
201+ gate.wait().await;
202+ mark(&db, &id, &student, status, &marker).await
203+ })
186 };204 };
187 let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap());205 let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap());
188 assert!(206 assert!(
@@ -198,7 +216,7 @@ mod tests {
198 panic!("round {round}: the delete reported success but the event is still there");216 panic!("round {round}: the delete reported success but the event is still there");
199 }217 }
200 }218 }
201- eprintln!("Event::delete raced by a mark: {swept}/4 rounds deleted the event");219+ eprintln!("Event::delete raced by a mark: {swept}/8 rounds deleted the event");
202 assert!(220 assert!(
203 swept > 0,221 swept > 0,
204 "no round ever deleted the event, so the window was never reached"222 "no round ever deleted the event, so the window was never reached"
src/db/badge.rsmodified+9 -9
@@ -111,7 +111,7 @@ pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> {
111 SET earned_at = badge_award.earned_at \111 SET earned_at = badge_award.earned_at \
112 WHERE badge_award.earned_at IS NULL"112 WHERE badge_award.earned_at IS NULL"
113 )))113 )))
114- .bind(user.uuid())114+.bind(user.uuid())
115 .bind(badge)115 .bind(badge)
116 .bind(now)116 .bind(now)
117 .execute(db)117 .execute(db)
@@ -124,7 +124,7 @@ pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> {
124 mod tests {124 mod tests {
125 use super::*;125 use super::*;
126 use crate::constant::BADGE_AWARD_TABLE;126 use crate::constant::BADGE_AWARD_TABLE;
127- use crate::database::init_mem;127+ use crate::database::init_test_db;
128 use crate::domain::user::{Password, Username};128 use crate::domain::user::{Password, Username};
129 129
130 async fn a_user(username: &str, db: &Database) -> crate::domain::user::User {130 async fn a_user(username: &str, db: &Database) -> crate::domain::user::User {
@@ -142,9 +142,9 @@ mod tests {
142 }142 }
143 143
144 async fn count_awards(db: &Database, user: &UserId) -> i64 {144 async fn count_awards(db: &Database, user: &UserId) -> i64 {
145- let (count,): (i64,) = sqlx::query_as(&format!(145+ let (count,): (i64,) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
146 "SELECT count(*) FROM {BADGE_AWARD_TABLE} WHERE app_user = $1"146 "SELECT count(*) FROM {BADGE_AWARD_TABLE} WHERE app_user = $1"
147- ))147+ )))
148 .bind(user.uuid())148 .bind(user.uuid())
149 .fetch_one(db)149 .fetch_one(db)
150 .await150 .await
@@ -161,7 +161,7 @@ mod tests {
161 161
162 #[tokio::test]162 #[tokio::test]
163 async fn load_defaults_every_counter_to_zero() {163 async fn load_defaults_every_counter_to_zero() {
164- let db = init_mem().await.unwrap();164+ let (db, _leases) = init_test_db().await;
165 let user = a_user("badge-sifir", &db).await;165 let user = a_user("badge-sifir", &db).await;
166 166
167 let stats = load(&db, user.get_id()).await.unwrap();167 let stats = load(&db, user.get_id()).await.unwrap();
@@ -177,12 +177,12 @@ mod tests {
177 177
178 #[tokio::test]178 #[tokio::test]
179 async fn sync_is_idempotent_and_keeps_the_first_stamp() {179 async fn sync_is_idempotent_and_keeps_the_first_stamp() {
180- let db = init_mem().await.unwrap();180+ let (db, _leases) = init_test_db().await;
181 let user = a_user("badge-ali", &db).await;181 let user = a_user("badge-ali", &db).await;
182 182
183 // Seed two submitted homeworks: enough for the first badge tier.183 // Seed two submitted homeworks: enough for the first badge tier.
184 sqlx::query("UPDATE app_user SET homework_submitted_total = 2 WHERE id = $1")184 sqlx::query("UPDATE app_user SET homework_submitted_total = 2 WHERE id = $1")
185- .bind(user.uuid())185+ .bind(user.get_id().uuid())
186 .execute(&db)186 .execute(&db)
187 .await187 .await
188 .unwrap();188 .unwrap();
@@ -195,7 +195,7 @@ mod tests {
195 // A second sync with the counter moved *further* writes nothing: the195 // A second sync with the counter moved *further* writes nothing: the
196 // stamps are from the first crossing, and no row is duplicated.196 // stamps are from the first crossing, and no row is duplicated.
197 sqlx::query("UPDATE app_user SET homework_submitted_total = 5 WHERE id = $1")197 sqlx::query("UPDATE app_user SET homework_submitted_total = 5 WHERE id = $1")
198- .bind(user.uuid())198+ .bind(user.get_id().uuid())
199 .execute(&db)199 .execute(&db)
200 .await200 .await
201 .unwrap();201 .unwrap();
@@ -218,7 +218,7 @@ mod tests {
218 218
219 #[tokio::test]219 #[tokio::test]
220 async fn sync_writes_nothing_for_a_earned_nothing() {220 async fn sync_writes_nothing_for_a_earned_nothing() {
221- let db = init_mem().await.unwrap();221+ let (db, _leases) = init_test_db().await;
222 let user = a_user("badge-bos", &db).await;222 let user = a_user("badge-bos", &db).await;
223 sync(&db, user.get_id()).await.unwrap();223 sync(&db, user.get_id()).await.unwrap();
224 assert_eq!(224 assert_eq!(
src/db/bank_question.rsmodified+35 -39
@@ -414,33 +414,33 @@ mod tests {
414 .unwrap()414 .unwrap()
415 }415 }
416 416
417- /// A row stored before `visibility` existed has no such key — it must decode417+ /// A row without a visibility of its own must decode as `private`, the
418- /// as `private`, the safe value. Asserted on the decoder itself, so no418+ /// safe value. The old engine could store a row with the field absent;
419- /// schema DEFAULT can paper over it: a `school` default here would publish419+ /// Postgres carries the same guarantee in the schema instead — the column
420- /// every pre-existing template in the school at once.420+ /// is `NOT NULL DEFAULT 'private'`, so a `school` default here would
421+ /// publish every pre-existing template in the school at once. The insert
422+ /// below is written exactly as a pre-visibility row arrives: no column.
421 #[tokio::test]423 #[tokio::test]
422 async fn a_row_without_the_field_decodes_private() {424 async fn a_row_without_the_field_decodes_private() {
423- use surrealdb::types::Value;425+ let (db, _leases) = crate::database::init_test_db().await;
424-426+ let owner = UserId::generate();
425- let db = crate::database::init_mem().await.unwrap();427+ sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'q', 'x')")
426- let question = create(428+ .bind(owner.uuid())
427- &db,429+ .execute(&db)
428- UserId::generate(),430+ .await
429- SubjectId::generate(),431+ .unwrap();
430- QuestionText::try_new("q").unwrap(),432+ let id = BankQuestionId::generate();
431- QuestionPoints::try_new(1).unwrap(),433+ sqlx::query(
432- spec(),434+ "INSERT INTO bank_question (id, owner, text, kind, points, created_at) \
435+ VALUES ($1, $2, 'q', 'multiple_choice', 1, 0)",
433 )436 )
437+ .bind(id.uuid())
438+ .bind(owner.uuid())
439+ .execute(&db)
434 .await440 .await
435 .unwrap();441 .unwrap();
436- assert_eq!(question.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE);
437 442
438- let mut stored = question.into_value();443+ let old = read(&db, &id).await.unwrap().expect("the row is there");
439- let Value::Object(map) = &mut stored else {
440- panic!("a bank question serializes to an object");
441- };
442- assert!(map.remove("visibility").is_some());
443- let old = BankQuestion::from_value(stored).unwrap();
444 assert_eq!(old.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE);444 assert_eq!(old.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE);
445 assert!(!old.get_visibility().is_school());445 assert!(!old.get_visibility().is_school());
446 }446 }
@@ -449,7 +449,7 @@ mod tests {
449 /// page can contain — never someone else's private templates.449 /// page can contain — never someone else's private templates.
450 #[tokio::test]450 #[tokio::test]
451 async fn list_hides_private_templates_from_others() {451 async fn list_hides_private_templates_from_others() {
452- let db = crate::database::init_mem().await.unwrap();452+ let (db, _leases) = crate::database::init_test_db().await;
453 let owner = UserId::generate();453 let owner = UserId::generate();
454 let other = UserId::generate();454 let other = UserId::generate();
455 let private = create(455 let private = create(
@@ -516,7 +516,7 @@ mod tests {
516 /// still answer `Ok`.516 /// still answer `Ok`.
517 #[tokio::test]517 #[tokio::test]
518 async fn a_merge_built_on_a_stale_snapshot_is_refused() {518 async fn a_merge_built_on_a_stale_snapshot_is_refused() {
519- let db = crate::database::init_mem().await.unwrap();519+ let (db, _leases) = crate::database::init_test_db().await;
520 let owner = UserId::generate();520 let owner = UserId::generate();
521 let stale = create(521 let stale = create(
522 &db,522 &db,
@@ -564,7 +564,7 @@ mod tests {
564 /// row, and `private` means "my own drafts" for everyone but an admin.564 /// row, and `private` means "my own drafts" for everyone but an admin.
565 #[tokio::test]565 #[tokio::test]
566 async fn visibility_filter_narrows_never_widens() {566 async fn visibility_filter_narrows_never_widens() {
567- let db = crate::database::init_mem().await.unwrap();567+ let (db, _leases) = crate::database::init_test_db().await;
568 let owner = UserId::generate();568 let owner = UserId::generate();
569 let other = UserId::generate();569 let other = UserId::generate();
570 let mine = |text: &str| {570 let mine = |text: &str| {
@@ -638,14 +638,10 @@ mod tests {
638 /// "0"), and questions authored by hand never counted.638 /// "0"), and questions authored by hand never counted.
639 #[tokio::test]639 #[tokio::test]
640 async fn usage_counts_tallies_a_page_in_one_statement() {640 async fn usage_counts_tallies_a_page_in_one_statement() {
641- // One statement, so a page costs one round trip — a `;` here would mean641+ // One statement, so a page costs one round trip: the tally is a single
642- // the per-row N+1 crept back in.642+ // static `query!` (a `GROUP BY` with no loop around it), which the
643- assert!(643+ // compiler now checks the way the old constant asserted.
644- !USAGE_COUNTS_SQL.contains(';'),644+ let (db, _leases) = crate::database::init_test_db().await;
645- "usage_counts must be one statement"
646- );
647-
648- let db = crate::database::init_mem().await.unwrap();
649 let owner = UserId::generate();645 let owner = UserId::generate();
650 let template = |text: &str| {646 let template = |text: &str| {
651 create(647 create(
@@ -712,10 +708,10 @@ mod tests {
712 708
713 let ids = [used_twice.get_id(), used_once.get_id(), unused.get_id()];709 let ids = [used_twice.get_id(), used_once.get_id(), unused.get_id()];
714 let counts = usage_counts(&db, &ids).await.unwrap();710 let counts = usage_counts(&db, &ids).await.unwrap();
715- assert_eq!(counts.get(used_twice.get_id().key()).copied(), Some(2));711+ assert_eq!(counts.get(&used_twice.get_id().key()).copied(), Some(2));
716- assert_eq!(counts.get(used_once.get_id().key()).copied(), Some(1));712+ assert_eq!(counts.get(&used_once.get_id().key()).copied(), Some(1));
717 assert_eq!(713 assert_eq!(
718- counts.get(unused.get_id().key()),714+ counts.get(&unused.get_id().key()),
719 None,715 None,
720 "unused stays absent"716 "unused stays absent"
721 );717 );
@@ -724,14 +720,14 @@ mod tests {
724 // A template outside the page is never counted into it.720 // A template outside the page is never counted into it.
725 let narrow = usage_counts(&db, &[used_once.get_id()]).await.unwrap();721 let narrow = usage_counts(&db, &[used_once.get_id()]).await.unwrap();
726 assert_eq!(narrow.len(), 1);722 assert_eq!(narrow.len(), 1);
727- assert_eq!(narrow.get(used_once.get_id().key()).copied(), Some(1));723+ assert_eq!(narrow.get(&used_once.get_id().key()).copied(), Some(1));
728 // An empty page asks nothing at all.724 // An empty page asks nothing at all.
729 assert!(usage_counts(&db, &[]).await.unwrap().is_empty());725 assert!(usage_counts(&db, &[]).await.unwrap().is_empty());
730 }726 }
731 727
732 #[tokio::test]728 #[tokio::test]
733 async fn list_is_school_wide() {729 async fn list_is_school_wide() {
734- let db = crate::database::init_mem().await.unwrap();730+ let (db, _leases) = crate::database::init_test_db().await;
735 for _ in 0..2 {731 for _ in 0..2 {
736 create(732 create(
737 &db,733 &db,
@@ -755,7 +751,7 @@ mod tests {
755 /// The window is SQL, not an in-memory slice, and `total` ignores it.751 /// The window is SQL, not an in-memory slice, and `total` ignores it.
756 #[tokio::test]752 #[tokio::test]
757 async fn list_pages_newest_first_and_filters_text() {753 async fn list_pages_newest_first_and_filters_text() {
758- let db = crate::database::init_mem().await.unwrap();754+ let (db, _leases) = crate::database::init_test_db().await;
759 let owner = UserId::generate();755 let owner = UserId::generate();
760 for i in 0..5 {756 for i in 0..5 {
761 create(757 create(
@@ -806,7 +802,7 @@ mod tests {
806 /// Turkish `İ`/`ı` must not split the search into two disjoint halves.802 /// Turkish `İ`/`ı` must not split the search into two disjoint halves.
807 #[tokio::test]803 #[tokio::test]
808 async fn list_text_filter_folds_turkish_casing() {804 async fn list_text_filter_folds_turkish_casing() {
809- let db = crate::database::init_mem().await.unwrap();805+ let (db, _leases) = crate::database::init_test_db().await;
810 create(806 create(
811 &db,807 &db,
812 UserId::generate(),808 UserId::generate(),
src/db/bank_question_image.rsmodified+3 -3
@@ -232,7 +232,7 @@ mod tests {
232 232
233 #[tokio::test]233 #[tokio::test]
234 async fn upsert_replaces_per_slot() {234 async fn upsert_replaces_per_slot() {
235- let db = crate::database::init_mem().await.unwrap();235+ let (db, _leases) = crate::database::init_test_db().await;
236 let question = a_template(&db).await;236 let question = a_template(&db).await;
237 237
238 let (first, retired) = upsert(&db, BankQuestionImage::new(&question, None, png(), 3))238 let (first, retired) = upsert(&db, BankQuestionImage::new(&question, None, png(), 3))
@@ -255,7 +255,7 @@ mod tests {
255 /// picture, and only a removed option's picture goes.255 /// picture, and only a removed option's picture goes.
256 #[tokio::test]256 #[tokio::test]
257 async fn only_the_dropped_options_lose_their_pictures() {257 async fn only_the_dropped_options_lose_their_pictures() {
258- let db = crate::database::init_mem().await.unwrap();258+ let (db, _leases) = crate::database::init_test_db().await;
259 let question = a_template(&db).await;259 let question = a_template(&db).await;
260 let ids = choice_ids();260 let ids = choice_ids();
261 upsert(&db, BankQuestionImage::new(&question, None, png(), 1))261 upsert(&db, BankQuestionImage::new(&question, None, png(), 1))
@@ -278,7 +278,7 @@ mod tests {
278 278
279 #[tokio::test]279 #[tokio::test]
280 async fn an_empty_keep_set_clears_every_option_picture() {280 async fn an_empty_keep_set_clears_every_option_picture() {
281- let db = crate::database::init_mem().await.unwrap();281+ let (db, _leases) = crate::database::init_test_db().await;
282 let question = a_template(&db).await;282 let question = a_template(&db).await;
283 let ids = choice_ids();283 let ids = choice_ids();
284 upsert(&db, BankQuestionImage::new(&question, None, png(), 1))284 upsert(&db, BankQuestionImage::new(&question, None, png(), 1))
src/db/board.rsmodified+2 -2
@@ -331,7 +331,7 @@ mod tests {
331 /// the meantime is a 404 — not a silent success.331 /// the meantime is a 404 — not a silent success.
332 #[tokio::test]332 #[tokio::test]
333 async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() {333 async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() {
334- let db = crate::database::init_mem().await.unwrap();334+ let (db, _leases) = crate::database::init_test_db().await;
335 let creator = UserId::generate();335 let creator = UserId::generate();
336 let board = create(336 let board = create(
337 &db,337 &db,
@@ -362,7 +362,7 @@ mod tests {
362 /// board row, and deleting a board hands the seat back.362 /// board row, and deleting a board hands the seat back.
363 #[tokio::test]363 #[tokio::test]
364 async fn the_cap_refuses_and_delete_releases_the_seat() {364 async fn the_cap_refuses_and_delete_releases_the_seat() {
365- let db = crate::database::init_mem().await.unwrap();365+ let (db, _leases) = crate::database::init_test_db().await;
366 let creator = UserId::generate();366 let creator = UserId::generate();
367 for index in 0..MAX_BOARDS_PER_CREATOR {367 for index in 0..MAX_BOARDS_PER_CREATOR {
368 create(368 create(
src/db/builder.rsmodified+1 -1
@@ -116,7 +116,7 @@ mod tests {
116 116
117 #[tokio::test]117 #[tokio::test]
118 async fn a_builder_session_round_trips_and_deletes() {118 async fn a_builder_session_round_trips_and_deletes() {
119- let tenants = Tenants::new_mem().await.unwrap();119+ let tenants = crate::database::init_test_tenants().await;
120 let control = tenants.control();120 let control = tenants.control();
121 builder::ensure(121 builder::ensure(
122 control,122 control,
src/db/chatbot_message.rsmodified+22 -9
@@ -315,16 +315,29 @@ mod tests {
315 // `id` tie-break decides the thread's order. With a random ULID this315 // `id` tie-break decides the thread's order. With a random ULID this
316 // inverted a fifth of the pairs; here every pair must read back316 // inverted a fifth of the pairs; here every pair must read back
317 // question-then-answer, from both read paths.317 // question-then-answer, from both read paths.
318- let db = crate::database::init_mem().await.unwrap();318+ let (db, _leases) = crate::database::init_test_db().await;
319 // A real thread row: every turn is written through it, so a turn with319 // A real thread row: every turn is written through it, so a turn with
320- // no thread is refused (see [`insert`]).320+ // no thread is refused (see [`insert`]). The owner is a foreign key
321- db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0")321+ // now, so both fixture rows are real, under fixed keys.
322- .await322+ let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cafe");
323- .unwrap()323+ let thread = ChatbotThreadId::from_key("019732e3-7b00-7000-8000-00000000beef");
324- .check()324+ sqlx::query(
325- .unwrap();325+ "INSERT INTO app_user (id, username, password_hash) \
326- let thread = ChatbotThreadId::from_key("c");326+ VALUES ($1, 'chat-fixture', 'x')",
327- let user = UserId::from_key("u");327+ )
328+ .bind(user.uuid())
329+ .execute(&db)
330+ .await
331+ .unwrap();
332+ sqlx::query(
333+ "INSERT INTO chatbot_thread (id, user_id, created_at, updated_at) \
334+ VALUES ($1, $2, 0, 0)",
335+ )
336+ .bind(thread.uuid())
337+ .bind(user.uuid())
338+ .execute(&db)
339+ .await
340+ .unwrap();
328 const TURNS: usize = 200;341 const TURNS: usize = 200;
329 342
330 for turn in 0..TURNS {343 for turn in 0..TURNS {
src/db/chatbot_thread.rsmodified+46 -58
@@ -193,34 +193,41 @@ pub async fn delete(db: &Database, thread: ChatbotThread) -> Result<ChatbotThrea
193 #[cfg(test)]193 #[cfg(test)]
194 mod tests {194 mod tests {
195 use super::*;195 use super::*;
196- use surrealdb::types::RecordId;196+ use sqlx::Row as _;
197 197
198 use crate::db::chatbot_message;198 use crate::db::chatbot_message;
199 use crate::domain::chatbot_message::ChatContent;199 use crate::domain::chatbot_message::ChatContent;
200 use crate::domain::settings::{Settings, SettingsParams};200 use crate::domain::settings::{Settings, SettingsParams};
201 201
202+ /// The fixed fixture person, by a valid id every helper can name.
203+ const U: &str = "019732e3-7b00-7000-8000-00000000aaaa";
204+
202 /// The owner's counter and the threads it counts, both re-read out of the205 /// The owner's counter and the threads it counts, both re-read out of the
203- /// store — never off a return value, which the in-memory engine forges206+ /// store — never off a return value.
204- /// wins on (see [`cap`]).
205 async fn stored(db: &Database) -> (i64, usize) {207 async fn stored(db: &Database) -> (i64, usize) {
206- let mut result = db208+ let counter =
207- .query("SELECT VALUE (chatbot_thread_count ?? 0) FROM user:u")209+ sqlx::query("SELECT chatbot_thread_count FROM app_user WHERE id = $1")
208- .query("SELECT VALUE id FROM chatbot_thread")210+ .bind(UserId::from_key(U).uuid())
211+ .fetch_one(db)
212+ .await
213+ .unwrap()
214+ .try_get::<i64, _>(0)
215+ .unwrap();
216+ let rows = sqlx::query("SELECT count(*) FROM chatbot_thread")
217+ .fetch_one(db)
209 .await218 .await
210 .unwrap()219 .unwrap()
211- .check()220+ .try_get::<i64, _>(0)
212 .unwrap();221 .unwrap();
213- let counter = result.take::<Vec<i64>>(0).unwrap();222+ (counter, rows as usize)
214- let rows = result.take::<Vec<RecordId>>(1).unwrap();
215- (counter[0], rows.len())
216 }223 }
217 224
218 async fn a_user_capped_at(threads: i64) -> Database {225 async fn a_user_capped_at(threads: i64) -> Database {
219- let db = crate::database::init_mem().await.unwrap();226+ let (db, _leases) = crate::database::init_test_db().await;
220- db.query("CREATE user:u SET username = 'u', password_hash = 'x';")227+ sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'u', 'x')")
228+ .bind(UserId::from_key(U).uuid())
229+ .execute(&db)
221 .await230 .await
222- .unwrap()
223- .check()
224 .unwrap();231 .unwrap();
225 crate::db::settings::save(232 crate::db::settings::save(
226 &db,233 &db,
@@ -241,7 +248,7 @@ mod tests {
241 #[tokio::test]248 #[tokio::test]
242 async fn a_capped_create_moves_the_counter_with_the_row() {249 async fn a_capped_create_moves_the_counter_with_the_row() {
243 let db = a_user_capped_at(1).await;250 let db = a_user_capped_at(1).await;
244- let user = UserId::from_key("u");251+ let user = UserId::from_key(U);
245 252
246 create_capped(&db, &user, None).await.expect("first thread");253 create_capped(&db, &user, None).await.expect("first thread");
247 assert_eq!(stored(&db).await, (1, 1));254 assert_eq!(stored(&db).await, (1, 1));
@@ -262,7 +269,7 @@ mod tests {
262 #[tokio::test]269 #[tokio::test]
263 async fn a_turn_writes_its_thread_and_dies_with_it() {270 async fn a_turn_writes_its_thread_and_dies_with_it() {
264 let db = a_user_capped_at(2).await;271 let db = a_user_capped_at(2).await;
265- let user = UserId::from_key("u");272+ let user = UserId::from_key(U);
266 let thread = create_capped(&db, &user, None).await.expect("thread");273 let thread = create_capped(&db, &user, None).await.expect("thread");
267 let opened = thread.get_updated_at().as_millis();274 let opened = thread.get_updated_at().as_millis();
268 275
@@ -322,16 +329,15 @@ mod tests {
322 const LEAD: i64 = 1_000;329 const LEAD: i64 = 1_000;
323 330
324 let db = a_user_capped_at(1).await;331 let db = a_user_capped_at(1).await;
325- let user = UserId::from_key("u");332+ let user = UserId::from_key(U);
326 let thread = create_capped(&db, &user, None).await.expect("thread");333 let thread = create_capped(&db, &user, None).await.expect("thread");
327 334
328 let parked = Timestamp::now().as_millis() + LEAD;335 let parked = Timestamp::now().as_millis() + LEAD;
329- db.query("UPDATE $id SET updated_at = $parked")336+ sqlx::query("UPDATE chatbot_thread SET updated_at = $1 WHERE id = $2")
330- .bind(("id", thread.get_id().record()))337+ .bind(parked)
331- .bind(("parked", parked))338+ .bind(thread.get_id().uuid())
339+ .execute(&db)
332 .await340 .await
333- .unwrap()
334- .check()
335 .unwrap();341 .unwrap();
336 342
337 for _ in 0..2 {343 for _ in 0..2 {
@@ -377,51 +383,33 @@ mod tests {
377 /// row ([`touch_and_write`]) instead of reading it — the two transactions383 /// row ([`touch_and_write`]) instead of reading it — the two transactions
378 /// then touch one key and the store refuses to commit both.384 /// then touch one key and the store refuses to commit both.
379 ///385 ///
380- /// The window is opened by the database itself rather than by a lucky386+ /// The window the schema event used to force open is the thread row's own
381- /// interleaving: a `DEFINE EVENT` on `chatbot_thread` fires *inside* the387+ /// lock now: a turn is written *through* the row ([`touch_and_write`]),
382- /// delete's own transaction, the instant the row goes, so the `SLEEP` lands388+ /// so a turn racing the delete serializes on that row instead of
383- /// after the message sweep and before the commit every single time.389+ /// committing past the sweep. A barrier start lets both orders happen,
384- ///390+ /// and the invariant must hold in each.
385- /// Real server, and `#[ignore]`d for it: the subject is the store's
386- /// conflict detection, which `init_mem`'s embedded engine does not have —
387- /// it commits both writes and answers `Ok` to each, which would fail this
388- /// test on correct code (see [`crate::database::init_test_server`]).
389 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]391 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
390- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
391 async fn a_turn_written_inside_a_delete_never_outlives_the_thread() {392 async fn a_turn_written_inside_a_delete_never_outlives_the_thread() {
392- let (db, _serialized) = crate::database::init_test_server("chat_delete_race").await;393+ let db = a_user_capped_at(4).await;
393- db.query("CREATE user:u SET username = 'u', password_hash = 'x';")
394- .await
395- .unwrap()
396- .check()
397- .unwrap();
398- // Hold the delete open for a full second after the thread row is gone,
399- // while its transaction still has to commit.
400- db.query(
401- "DEFINE EVENT hold_the_window ON TABLE chatbot_thread WHEN $event = 'DELETE' \
402- THEN { SLEEP 1s; };",
403- )
404- .await
405- .unwrap()
406- .check()
407- .unwrap();
408 394
409- let user = UserId::from_key("u");395+ let user = UserId::from_key(U);
410 let (mut orphans, mut swept) = (0, 0);396 let (mut orphans, mut swept) = (0, 0);
411- for round in 0..4 {397+ for round in 0..8 {
412 let thread = create_capped(&db, &user, None).await.expect("thread");398 let thread = create_capped(&db, &user, None).await.expect("thread");
413 let id = thread.get_id().clone();399 let id = thread.get_id().clone();
414 400
401+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
415 let drop_it = {402 let drop_it = {
416- let db = db.clone();403+ let (db, thread, gate) = (db.clone(), thread, gate.clone());
417- tokio::spawn(async move { delete(&db, thread).await })404+ tokio::spawn(async move {
405+ gate.wait().await;
406+ delete(&db, thread).await
407+ })
418 };408 };
419- // The turn starts inside the held window — the thread row is gone
420- // but uncommitted, which is exactly what a read believes.
421- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
422 let turn = {409 let turn = {
423- let (id, db, user) = (id.clone(), db.clone(), user.clone());410+ let (id, db, user, gate) = (id.clone(), db.clone(), user.clone(), gate);
424 tokio::spawn(async move {411 tokio::spawn(async move {
412+ gate.wait().await;
425 chatbot_message::append_user(413 chatbot_message::append_user(
426 &db,414 &db,
427 &id,415 &id,
@@ -451,10 +439,10 @@ mod tests {
451 panic!("round {round}: the delete reported success but the thread is still there");439 panic!("round {round}: the delete reported success but the thread is still there");
452 }440 }
453 }441 }
454- eprintln!("chatbot_thread::delete raced by a turn: {swept}/4 rounds deleted the thread");442+ eprintln!("chatbot_thread::delete raced by a turn: {swept}/8 rounds deleted the thread");
455 assert!(443 assert!(
456 swept > 0,444 swept > 0,
457- "no round ever deleted the thread, so the window was never reached"445+ "no round ever deleted the thread, so the race never actually ran"
458 );446 );
459 assert_eq!(orphans, 0, "a turn outlived its thread");447 assert_eq!(orphans, 0, "a turn outlived its thread");
460 }448 }
src/db/class_group.rsmodified+89 -81
@@ -292,12 +292,31 @@ pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError>
292 #[cfg(test)]292 #[cfg(test)]
293 mod tests {293 mod tests {
294 use super::*;294 use super::*;
295+ use sqlx::Row as _;
296+
295 use crate::domain::term::{Term, TermName};297 use crate::domain::term::{Term, TermName};
296 298
299+ /// A real `app_user` row: creator, teacher, and attached-by are foreign
300+ /// keys now, so every fixture participant is a row, not a fabricated id.
301+ async fn a_named_user(db: &Database, username: &str) -> UserId {
302+ let user = UserId::generate();
303+ sqlx::query(
304+ "INSERT INTO app_user (id, username, password_hash, role) \
305+ VALUES ($1, $2, 'x', 'teacher')",
306+ )
307+ .bind(user.uuid())
308+ .bind(username)
309+ .execute(db)
310+ .await
311+ .unwrap();
312+ user
313+ }
314+
297 async fn class_on(term: Option<TermId>, db: &Database) -> ClassGroup {315 async fn class_on(term: Option<TermId>, db: &Database) -> ClassGroup {
316+ let manager = a_named_user(db, "manager").await;
298 create(317 create(
299 db,318 db,
300- &UserId::from_key("manager"),319+ &manager,
301 ClassName::try_new("9-A").unwrap(),320 ClassName::try_new("9-A").unwrap(),
302 None,321 None,
303 term,322 term,
@@ -309,9 +328,10 @@ mod tests {
309 328
310 /// A class with a homeroom teacher, no term.329 /// A class with a homeroom teacher, no term.
311 async fn class_of(teacher: Option<UserId>, db: &Database) -> ClassGroup {330 async fn class_of(teacher: Option<UserId>, db: &Database) -> ClassGroup {
331+ let manager = a_named_user(db, "manager").await;
312 create(332 create(
313 db,333 db,
314- &UserId::from_key("manager"),334+ &manager,
315 ClassName::try_new("9-A").unwrap(),335 ClassName::try_new("9-A").unwrap(),
316 None,336 None,
317 None,337 None,
@@ -338,41 +358,30 @@ mod tests {
338 .unwrap()358 .unwrap()
339 }359 }
340 360
341- /// The stored counter, re-read — never off a return value, which the361+ /// The single integer `sql` selects — the stored counter, re-read, never
342- /// in-memory engine forges wins on (see [`crate::db::cap`]).362+ /// off a return value. The SQL is built from literals in this module, so
343- async fn stored_count(sql: &str, db: &Database) -> i64 {363+ /// the audit wrapper is a formality.
344- let mut result = db.query(sql).await.unwrap().check().unwrap();364+ async fn one_i64(db: &Database, sql: String) -> i64 {
345- result365+ sqlx::query(sqlx::AssertSqlSafe(sql))
346- .take::<Vec<i64>>(0)366+ .fetch_one(db)
367+ .await
347 .unwrap()368 .unwrap()
348- .first()369+ .try_get::<i64, _>(0)
349- .copied()
350 .unwrap()370 .unwrap()
351 }371 }
352 372
353 /// The stored `class_count` on one term, absent counting as zero.373 /// The stored `class_count` on one term, absent counting as zero.
354 async fn count_on(term: &TermId, db: &Database) -> i64 {374 async fn count_on(term: &TermId, db: &Database) -> i64 {
355- let mut result = db375+ one_i64(
356- .query(format!(376+ db,
357- "SELECT VALUE ({TERM_CLASS_COUNT_FIELD} ?? 0) FROM $term"377+ format!("SELECT COALESCE(class_count, 0) FROM term WHERE id = '{}'", term.uuid()),
358- ))378+ )
359- .bind(("term", term.record()))379+ .await
360- .await
361- .unwrap()
362- .check()
363- .unwrap();
364- result
365- .take::<Vec<i64>>(0)
366- .unwrap()
367- .first()
368- .copied()
369- .unwrap_or(0)
370 }380 }
371 381
372- /// How many rows `sql` selects ids for.382+ /// How many rows `table` holds.
373- async fn rows(sql: &str, db: &Database) -> usize {383+ async fn row_count(db: &Database, table: &str) -> i64 {
374- let mut result = db.query(sql).await.unwrap().check().unwrap();384+ one_i64(db, format!("SELECT count(*) FROM {table}")).await
375- result.take::<Vec<RecordId>>(0).unwrap().len()
376 }385 }
377 386
378 /// The homeroom teacher survives a create, is set and cleared by a PATCH,387 /// The homeroom teacher survives a create, is set and cleared by a PATCH,
@@ -381,9 +390,9 @@ mod tests {
381 /// no key at all, which must read back as `None`, not fail the decode.390 /// no key at all, which must read back as `None`, not fail the decode.
382 #[tokio::test]391 #[tokio::test]
383 async fn the_homeroom_teacher_is_stored_set_cleared_and_left_alone() {392 async fn the_homeroom_teacher_is_stored_set_cleared_and_left_alone() {
384- let db = crate::database::init_mem().await.unwrap();393+ let (db, _leases) = crate::database::init_test_db().await;
385- let ada = UserId::from_key("ada");394+ let ada = a_named_user(&db, "ada").await;
386- let boole = UserId::from_key("boole");395+ let boole = a_named_user(&db, "boole").await;
387 396
388 let bare = class_of(None, &db).await;397 let bare = class_of(None, &db).await;
389 assert_eq!(teacher_of(bare.get_id(), &db).await, None);398 assert_eq!(teacher_of(bare.get_id(), &db).await, None);
@@ -421,18 +430,18 @@ mod tests {
421 None,430 None,
422 None,431 None,
423 None,432 None,
424- Some(Some(UserId::from_key("ada"))),433+ Some(Some(a_named_user(&db, "ada").await)),
425 )434 )
426 .await435 .await
427 .unwrap();436 .unwrap();
428 assert_eq!(again.get_name().as_str(), "9-B");437 assert_eq!(again.get_name().as_str(), "9-B");
429 438
430- // A row that predates the column: absent key, not NULL.439+ // A row without a homeroom: the column reads back as NULL, not a
431- db.query("UPDATE $class UNSET teacher")440+ // decode failure.
432- .bind(("class", bare.get_id().record()))441+ sqlx::query("UPDATE class_group SET teacher = NULL WHERE id = $1")
442+ .bind(bare.get_id().uuid())
443+ .execute(&db)
433 .await444 .await
434- .unwrap()
435- .check()
436 .unwrap();445 .unwrap();
437 assert_eq!(teacher_of(bare.get_id(), &db).await, None);446 assert_eq!(teacher_of(bare.get_id(), &db).await, None);
438 }447 }
@@ -441,9 +450,9 @@ mod tests {
441 /// *every* class they homeroomed, and nobody else's is touched.450 /// *every* class they homeroomed, and nobody else's is touched.
442 #[tokio::test]451 #[tokio::test]
443 async fn unassign_everywhere_clears_only_that_users_classes() {452 async fn unassign_everywhere_clears_only_that_users_classes() {
444- let db = crate::database::init_mem().await.unwrap();453+ let (db, _leases) = crate::database::init_test_db().await;
445- let ada = UserId::from_key("ada");454+ let ada = a_named_user(&db, "ada").await;
446- let boole = UserId::from_key("boole");455+ let boole = a_named_user(&db, "boole").await;
447 let first = class_of(Some(ada.clone()), &db).await;456 let first = class_of(Some(ada.clone()), &db).await;
448 let second = class_of(Some(ada.clone()), &db).await;457 let second = class_of(Some(ada.clone()), &db).await;
449 let other = class_of(Some(boole.clone()), &db).await;458 let other = class_of(Some(boole.clone()), &db).await;
@@ -471,18 +480,18 @@ mod tests {
471 /// instead would pass the first assert and fail the roundtrip through boot.480 /// instead would pass the first assert and fail the roundtrip through boot.
472 #[tokio::test]481 #[tokio::test]
473 async fn a_term_is_deletable_only_once_no_class_links_it() {482 async fn a_term_is_deletable_only_once_no_class_links_it() {
474- let db = crate::database::init_mem().await.unwrap();483+ let (db, _leases) = crate::database::init_test_db().await;
475 let term = a_term(&db).await;484 let term = a_term(&db).await;
476 485
477 let linked = class_on(Some(term.get_id().clone()), &db).await;486 let linked = class_on(Some(term.get_id().clone()), &db).await;
478 let patched = class_on(Some(term.get_id().clone()), &db).await;487 let patched = class_on(Some(term.get_id().clone()), &db).await;
479 assert_eq!(488 assert_eq!(
480- stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,489+ one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await,
481 2,490 2,
482 "classes must count on class_count, not course_count"491 "classes must count on class_count, not course_count"
483 );492 );
484 assert_eq!(493 assert_eq!(
485- stored_count("SELECT VALUE course_count ?? 0 FROM term", &db).await,494+ one_i64(&db, "SELECT COALESCE(course_count, 0) FROM term".to_string()).await,
486 0,495 0,
487 "the courses' counter is seeded from course rows and must stay untouched"496 "the courses' counter is seeded from course rows and must stay untouched"
488 );497 );
@@ -511,15 +520,16 @@ mod tests {
511 /// which a refusal that released it would strand.520 /// which a refusal that released it would strand.
512 #[tokio::test]521 #[tokio::test]
513 async fn a_class_with_members_or_courses_refuses_to_delete() {522 async fn a_class_with_members_or_courses_refuses_to_delete() {
514- for field in [CLASS_MEMBER_COUNT_FIELD, CLASS_COURSE_COUNT_FIELD] {523+ for field in ["class_member_count", "class_course_count"] {
515- let db = crate::database::init_mem().await.unwrap();524+ let (db, _leases) = crate::database::init_test_db().await;
516 let term = a_term(&db).await;525 let term = a_term(&db).await;
517 let class = class_on(Some(term.get_id().clone()), &db).await;526 let class = class_on(Some(term.get_id().clone()), &db).await;
518- db.query(format!("UPDATE $class SET {field} = 1"))527+ sqlx::query(sqlx::AssertSqlSafe(format!(
519- .bind(("class", class.get_id().record()))528+ "UPDATE class_group SET {field} = 1 WHERE id = $1"
529+ )))
530+ .bind(class.get_id().uuid())
531+ .execute(&db)
520 .await532 .await
521- .unwrap()
522- .check()
523 .unwrap();533 .unwrap();
524 534
525 assert!(535 assert!(
@@ -531,21 +541,22 @@ mod tests {
531 "a refused delete may write nothing"541 "a refused delete may write nothing"
532 );542 );
533 assert_eq!(543 assert_eq!(
534- stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,544+ one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await,
535 1,545 1,
536 "…the term reference least of all"546 "…the term reference least of all"
537 );547 );
538 548
539 // Back to zero, and the same class deletes and releases the term.549 // Back to zero, and the same class deletes and releases the term.
540- db.query(format!("UPDATE $class SET {field} = 0"))550+ sqlx::query(sqlx::AssertSqlSafe(format!(
541- .bind(("class", class.get_id().record()))551+ "UPDATE class_group SET {field} = 0 WHERE id = $1"
552+ )))
553+ .bind(class.get_id().uuid())
554+ .execute(&db)
542 .await555 .await
543- .unwrap()
544- .check()
545 .unwrap();556 .unwrap();
546 assert!(delete(&db, class.clone()).await.unwrap());557 assert!(delete(&db, class.clone()).await.unwrap());
547 assert_eq!(558 assert_eq!(
548- stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,559+ one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await,
549 0560 0
550 );561 );
551 let again = delete(&db, class).await;562 let again = delete(&db, class).await;
@@ -561,14 +572,14 @@ mod tests {
561 /// delete guard reads, so a stray one would make it undeletable forever).572 /// delete guard reads, so a stray one would make it undeletable forever).
562 #[tokio::test]573 #[tokio::test]
563 async fn a_refused_create_writes_neither_row_nor_count() {574 async fn a_refused_create_writes_neither_row_nor_count() {
564- let db = crate::database::init_mem().await.unwrap();575+ let (db, _leases) = crate::database::init_test_db().await;
565 let term = a_term(&db).await;576 let term = a_term(&db).await;
566 let id = term.get_id().clone();577 let id = term.get_id().clone();
567 assert!(crate::db::term::delete(&db, term).await.unwrap());578 assert!(crate::db::term::delete(&db, term).await.unwrap());
568 579
569 let error = create(580 let error = create(
570 &db,581 &db,
571- &UserId::from_key("manager"),582+ &a_named_user(&db, "manager").await,
572 ClassName::try_new("9-A").unwrap(),583 ClassName::try_new("9-A").unwrap(),
573 None,584 None,
574 Some(id),585 Some(id),
@@ -578,12 +589,12 @@ mod tests {
578 .expect_err("a term that is gone must not be linkable");589 .expect_err("a term that is gone must not be linkable");
579 assert!(error.to_string().contains("term does not exist"));590 assert!(error.to_string().contains("term does not exist"));
580 assert_eq!(591 assert_eq!(
581- rows("SELECT VALUE id FROM class_group", &db).await,592+ row_count(&db, "class_group").await,
582 0,593 0,
583 "a refused create may write no row"594 "a refused create may write no row"
584 );595 );
585 assert_eq!(596 assert_eq!(
586- rows("SELECT VALUE id FROM term", &db).await,597+ row_count(&db, "term").await,
587 0,598 0,
588 "…and least of all a count on a term it just brought back"599 "…and least of all a count on a term it just brought back"
589 );600 );
@@ -596,7 +607,7 @@ mod tests {
596 /// so the old count would be 0 if the abort did not undo it).607 /// so the old count would be 0 if the abort did not undo it).
597 #[tokio::test]608 #[tokio::test]
598 async fn a_class_term_move_moves_both_counts_or_neither() {609 async fn a_class_term_move_moves_both_counts_or_neither() {
599- let db = crate::database::init_mem().await.unwrap();610+ let (db, _leases) = crate::database::init_test_db().await;
600 let at = crate::domain::timestamp::Timestamp::from_millis;611 let at = crate::domain::timestamp::Timestamp::from_millis;
601 let from = a_term(&db).await;612 let from = a_term(&db).await;
602 let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))613 let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))
@@ -660,7 +671,7 @@ mod tests {
660 /// with the counts reading as if they never ran.671 /// with the counts reading as if they never ran.
661 #[tokio::test]672 #[tokio::test]
662 async fn a_stale_class_term_write_is_refused_and_moves_no_count() {673 async fn a_stale_class_term_write_is_refused_and_moves_no_count() {
663- let db = crate::database::init_mem().await.unwrap();674+ let (db, _leases) = crate::database::init_test_db().await;
664 let at = crate::domain::timestamp::Timestamp::from_millis;675 let at = crate::domain::timestamp::Timestamp::from_millis;
665 let from = a_term(&db).await;676 let from = a_term(&db).await;
666 let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))677 let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))
@@ -738,8 +749,8 @@ mod tests {
738 async fn deleting_a_course_sweeps_its_class_attachments() {749 async fn deleting_a_course_sweeps_its_class_attachments() {
739 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};750 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
740 751
741- let db = crate::database::init_mem().await.unwrap();752+ let (db, _leases) = crate::database::init_test_db().await;
742- let manager = UserId::from_key("manager");753+ let manager = a_named_user(&db, "manager").await;
743 let course = crate::db::course::create(754 let course = crate::db::course::create(
744 &db,755 &db,
745 &manager,756 &manager,
@@ -752,30 +763,27 @@ mod tests {
752 .await763 .await
753 .unwrap();764 .unwrap();
754 let class = class_on(None, &db).await;765 let class = class_on(None, &db).await;
755- db.query(format!(766+ sqlx::query("INSERT INTO class_course (class, course, attached_by) VALUES ($1, $2, $3)")
756- "CREATE class_course SET class = $class, course = $course, attached_by = $usr;767+ .bind(class.get_id().uuid())
757- UPDATE $class SET {CLASS_COURSE_COUNT_FIELD} = 1;"768+ .bind(course.get_id().uuid())
758- ))769+ .bind(manager.uuid())
759- .bind(("class", class.get_id().record()))770+ .execute(&db)
760- .bind(("course", course.get_id().record()))771+ .await
761- .bind(("usr", manager.record()))772+ .unwrap();
762- .await773+ sqlx::query("UPDATE class_group SET class_course_count = 1 WHERE id = $1")
763- .unwrap()774+ .bind(class.get_id().uuid())
764- .check()775+ .execute(&db)
765- .unwrap();776+ .await
777+ .unwrap();
766 778
767 assert!(crate::db::course::delete(&db, course).await.unwrap());779 assert!(crate::db::course::delete(&db, course).await.unwrap());
768 assert_eq!(780 assert_eq!(
769- rows("SELECT VALUE id FROM class_course", &db).await,781+ row_count(&db, "class_course").await,
770 0,782 0,
771 "the attachment rows must go with the course"783 "the attachment rows must go with the course"
772 );784 );
773 assert_eq!(785 assert_eq!(
774- stored_count(786+ one_i64(&db, "SELECT COALESCE(class_course_count, 0) FROM class_group".to_string()).await,
775- &format!("SELECT VALUE {CLASS_COURSE_COUNT_FIELD} ?? 0 FROM class_group"),
776- &db
777- )
778- .await,
779 0,787 0,
780 "…and each class must get its count back"788 "…and each class must get its count back"
781 );789 );
src/db/class_member.rsmodified+90 -28
@@ -50,14 +50,41 @@ pub async fn list_for_user(
50 #[cfg(test)]50 #[cfg(test)]
51 pub(crate) mod tests {51 pub(crate) mod tests {
52 use super::*;52 use super::*;
53- use crate::domain::class_group::ClassName;53+ use crate::domain::class_group::{ClassGroupId, ClassName};
54 use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle};54 use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle};
55- use surrealdb::types::RecordId;55+ use crate::domain::user::UserId;
56+
57+ /// A real `app_user` row for fixtures, by username — the username is
58+ /// unique, so every call for the same name shares one row, whichever call
59+ /// minted it. Creators, graders, and `added_by` are foreign keys now, so
60+ use sqlx::Row as _;
61+
62+ /// fixture actors are rows, not fabricated ids.
63+ pub(crate) async fn fixture_user(db: &Database, username: &str) -> UserId {
64+ sqlx::query(
65+ "INSERT INTO app_user (id, username, password_hash, role) \
66+ VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING",
67+ )
68+ .bind(crate::domain::user::UserId::generate().uuid())
69+ .bind(username)
70+ .execute(db)
71+ .await
72+ .unwrap();
73+ let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1")
74+ .bind(username)
75+ .fetch_one(db)
76+ .await
77+ .unwrap()
78+ .try_get(0)
79+ .unwrap();
80+ UserId::from_key(&id.to_string())
81+ }
56 82
57 pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId {83 pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId {
84+ let manager = fixture_user(db, "manager").await;
58 crate::db::class_group::create(85 crate::db::class_group::create(
59 db,86 db,
60- &UserId::from_key("manager"),87+ &manager,
61 ClassName::try_new(name).unwrap(),88 ClassName::try_new(name).unwrap(),
62 None,89 None,
63 None,90 None,
@@ -70,9 +97,10 @@ pub(crate) mod tests {
70 }97 }
71 98
72 pub(crate) async fn a_course(title: &str, capacity: Option<i64>, db: &Database) -> CourseId {99 pub(crate) async fn a_course(title: &str, capacity: Option<i64>, db: &Database) -> CourseId {
100+ let manager = fixture_user(db, "manager").await;
73 crate::db::course::create(101 crate::db::course::create(
74 db,102 db,
75- &UserId::from_key("manager"),103+ &manager,
76 CourseTitle::try_new(title).unwrap(),104 CourseTitle::try_new(title).unwrap(),
77 CourseDescription::try_new("").unwrap(),105 CourseDescription::try_new("").unwrap(),
78 CourseKind::course(),106 CourseKind::course(),
@@ -85,40 +113,74 @@ pub(crate) mod tests {
85 .clone()113 .clone()
86 }114 }
87 115
88- /// A counter, re-read out of the store — never off a return value, which116+ /// A counter column on its row, re-read out of the store — never off a
89- /// the in-memory engine forges wins on (see [`crate::db::cap`]).117+ /// return value. The column name picks the table: every `*_count` these
90- pub(crate) async fn counter(field: &str, of: RecordId, db: &Database) -> i64 {118+ /// suites read lives on exactly one.
91- let mut result = db119+ pub(crate) async fn counter(field: &str, of: uuid::Uuid, db: &Database) -> i64 {
92- .query(format!("SELECT VALUE {field} ?? 0 FROM $of"))120+ let table = match field {
93- .bind(("of", of))121+ "enrollment_count" => "course",
122+ "class_member_count" | "class_course_count" => "class_group",
123+ other => panic!("no table known for the counter {other}"),
124+ };
125+ sqlx::query(sqlx::AssertSqlSafe(format!(
126+ "SELECT COALESCE({field}, 0) FROM {table} WHERE id = $1"
127+ )))
128+ .bind(of)
129+ .fetch_one(db)
94 .await130 .await
95 .unwrap()131 .unwrap()
96- .check()132+ .try_get::<i64, _>(0)
97- .unwrap();133+ .unwrap()
98- result134+ }
99- .take::<Vec<i64>>(0)135+
136+ /// How many rows `table` holds.
137+ pub(crate) async fn rows(table: &str, db: &Database) -> i64 {
138+ sqlx::query(sqlx::AssertSqlSafe(format!("SELECT count(*) FROM {table}")))
139+ .fetch_one(db)
140+ .await
100 .unwrap()141 .unwrap()
101- .first()142+ .try_get::<i64, _>(0)
102- .copied()
103 .unwrap()143 .unwrap()
104 }144 }
105 145
106- /// How many rows `sql` selects ids for.146+ /// Whether the course row is still there.
107- pub(crate) async fn rows(sql: &str, db: &Database) -> usize {147+ pub(crate) async fn course_exists(course: &CourseId, db: &Database) -> bool {
108- let mut result = db.query(sql).await.unwrap().check().unwrap();148+ sqlx::query("SELECT 1 FROM course WHERE id = $1")
109- result.take::<Vec<RecordId>>(0).unwrap().len()149+ .bind(course.uuid())
150+ .fetch_optional(db)
151+ .await
152+ .unwrap()
153+ .is_some()
110 }154 }
111 155
112- /// Whether `id` names a live row.156+ /// Whether the enrollment pair still has its row.
113- pub(crate) async fn exists(id: RecordId, db: &Database) -> bool {157+ pub(crate) async fn enrollment_exists(
114- let mut result = db158+ course: &CourseId,
115- .query("SELECT VALUE id FROM $id")159+ user: &UserId,
116- .bind(("id", id))160+ db: &Database,
161+ ) -> bool {
162+ sqlx::query("SELECT 1 FROM enrollment WHERE course = $1 AND app_user = $2")
163+ .bind(course.uuid())
164+ .bind(user.uuid())
165+ .fetch_optional(db)
117 .await166 .await
118 .unwrap()167 .unwrap()
119- .check()168+ .is_some()
120- .unwrap();169+ }
121- !result.take::<Vec<RecordId>>(0).unwrap().is_empty()170+
171+ /// Whether the class-course link is still attached.
172+ pub(crate) async fn link_exists(
173+ class: &ClassGroupId,
174+ course: &CourseId,
175+ db: &Database,
176+ ) -> bool {
177+ sqlx::query("SELECT 1 FROM class_course WHERE class = $1 AND course = $2")
178+ .bind(class.uuid())
179+ .bind(course.uuid())
180+ .fetch_optional(db)
181+ .await
182+ .unwrap()
183+ .is_some()
122 }184 }
123 185
124 /// The class that wrote an enrollment, or `None` for a hand-placed row.186 /// The class that wrote an enrollment, or `None` for a hand-placed row.
src/db/class_pump.rsmodified+86 -118
@@ -379,7 +379,7 @@ pub(crate) async fn add_member(
379 let added_at = Timestamp::now();379 let added_at = Timestamp::now();
380 let class = class.clone();380 let class = class.clone();
381 let (user, by) = (*user, *by);381 let (user, by) = (*user, *by);
382- tx_with_retry(db, false, async move |tx| {382+ let outcome = tx_with_retry(db, false, async move |tx| {
383 if let Some(early) =383 if let Some(early) =
384 early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await?384 early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await?
385 {385 {
@@ -439,11 +439,7 @@ pub(crate) async fn add_member(
439 .fetch_all(&mut *tx)439 .fetch_all(&mut *tx)
440 .await?;440 .await?;
441 let pairs = courses.into_iter().map(|course| (course, user.uuid()));441 let pairs = courses.into_iter().map(|course| (course, user.uuid()));
442- match enroll_pairs(tx, &class, pairs, &by).await? {442+ enroll_pairs(tx, &class, pairs, &by).await?;
443- Sweep::Done => {}
444- Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)),
445- Sweep::Full(course) => return Ok(Attached::Full(course)),
446- }
447 Ok(Attached::Made(ClassMember {443 Ok(Attached::Made(ClassMember {
448 class: class.clone(),444 class: class.clone(),
449 user,445 user,
@@ -451,7 +447,8 @@ pub(crate) async fn add_member(
451 added_at: Some(added_at),447 added_at: Some(added_at),
452 }))448 }))
453 })449 })
454- .await450+ .await;
451+ map_sweep_abort(outcome)
455 }452 }
456 453
457 /// Write the course link and enroll the class's whole roster into it, or454 /// Write the course link and enroll the class's whole roster into it, or
@@ -478,7 +475,7 @@ pub(crate) async fn attach_course(
478 let course = course.clone();475 let course = course.clone();
479 let by = *by;476 let by = *by;
480 let source = source.cloned();477 let source = source.cloned();
481- tx_with_retry(db, false, async move |tx| {478+ let outcome = tx_with_retry(db, false, async move |tx| {
482 if let Some(early) = early_verdicts(479 if let Some(early) = early_verdicts(
483 tx,480 tx,
484 &class,481 &class,
@@ -536,11 +533,7 @@ pub(crate) async fn attach_course(
536 .fetch_all(&mut *tx)533 .fetch_all(&mut *tx)
537 .await?;534 .await?;
538 let pairs = members.into_iter().map(|user| (course.uuid(), user));535 let pairs = members.into_iter().map(|user| (course.uuid(), user));
539- match enroll_pairs(tx, &class, pairs, &by).await? {536+ enroll_pairs(tx, &class, pairs, &by).await?;
540- Sweep::Done => {}
541- Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)),
542- Sweep::Full(course) => return Ok(Attached::Full(course)),
543- }
544 Ok(Attached::Made(ClassCourse {537 Ok(Attached::Made(ClassCourse {
545 class: class.clone(),538 class: class.clone(),
546 course: course.clone(),539 course: course.clone(),
@@ -549,17 +542,31 @@ pub(crate) async fn attach_course(
549 attached_at: Some(attached_at),542 attached_at: Some(attached_at),
550 }))543 }))
551 })544 })
552- .await545+ .await;
546+ map_sweep_abort(outcome)
553 }547 }
554 548
555-/// What the shared enrollment loop settled for its pairs.549+/// Abort markers the pair loop raises where the old transaction `THROW` did,
556-enum Sweep {550+/// in the [`crate::db::field_update`] style: a refusal found *after* earlier
557- /// Every pair holds the row it owes.551+/// pairs wrote must take the whole run down with it — returning it as `Ok`
558- Done,552+/// would COMMIT the partial enrollment. The marker carries the course's key
559- /// One of the pairs' courses is gone, named by its key: a stale link.553+/// and is mapped back to [`Attached`] right after [`tx_with_retry`] returns
560- CourseGone(String),554+/// ([`map_sweep_abort`]); it never reaches the wire.
561- /// One of the pairs' courses has no free seat, named by its key.555+const COURSE_GONE_MARK: &str = "class_pump_course_gone:";
562- Full(String),556+const COURSE_FULL_MARK: &str = "class_pump_course_full:";
557+
558+/// The pair loop's abort markers back into their [`Attached`] refusals —
559+/// every other outcome passes through untouched.
560+fn map_sweep_abort<T>(outcome: Result<Attached<T>, AppError>) -> Result<Attached<T>, AppError> {
561+ match outcome {
562+ Err(AppError::Internal(m)) if m.starts_with(COURSE_GONE_MARK) => Ok(Attached::CourseGone(
563+ m[COURSE_GONE_MARK.len()..].to_string(),
564+ )),
565+ Err(AppError::Internal(m)) if m.starts_with(COURSE_FULL_MARK) => {
566+ Ok(Attached::Full(m[COURSE_FULL_MARK.len()..].to_string()))
567+ }
568+ other => other,
569+ }
563 }570 }
564 571
565 /// Enroll every `(course, user)` pair that has no row yet, each against its572 /// Enroll every `(course, user)` pair that has no row yet, each against its
@@ -583,7 +590,7 @@ async fn enroll_pairs(
583 class: &ClassGroupId,590 class: &ClassGroupId,
584 pairs: impl Iterator<Item = (uuid::Uuid, uuid::Uuid)>,591 pairs: impl Iterator<Item = (uuid::Uuid, uuid::Uuid)>,
585 by: &UserId,592 by: &UserId,
586-) -> Result<Sweep, AppError> {593+) -> Result<(), AppError> {
587 for (course, user) in pairs {594 for (course, user) in pairs {
588 let held = sqlx::query_scalar!(595 let held = sqlx::query_scalar!(
589 r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#,596 r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#,
@@ -601,7 +608,7 @@ async fn enroll_pairs(
601 .await?608 .await?
602 .is_some();609 .is_some();
603 if !alive {610 if !alive {
604- return Ok(Sweep::CourseGone(course.to_string()));611+ return Err(AppError::Internal(format!("{COURSE_GONE_MARK}{course}")));
605 }612 }
606 let seat = sqlx::query_scalar!(613 let seat = sqlx::query_scalar!(
607 r#"UPDATE course SET enrollment_count = enrollment_count + 1614 r#"UPDATE course SET enrollment_count = enrollment_count + 1
@@ -614,7 +621,7 @@ async fn enroll_pairs(
614 .await?621 .await?
615 .is_some();622 .is_some();
616 if !seat {623 if !seat {
617- return Ok(Sweep::Full(course.to_string()));624+ return Err(AppError::Internal(format!("{COURSE_FULL_MARK}{course}")));
618 }625 }
619 let wrote = sqlx::query_scalar!(626 let wrote = sqlx::query_scalar!(
620 r#"INSERT INTO enrollment (course, app_user, enrolled_by, source)627 r#"INSERT INTO enrollment (course, app_user, enrolled_by, source)
@@ -655,7 +662,7 @@ async fn enroll_pairs(
655 Err(e) => return Err(e.into()),662 Err(e) => return Err(e.into()),
656 }663 }
657 }664 }
658- Ok(Sweep::Done)665+ Ok(())
659 }666 }
660 667
661 // The sweep a role change *off` `student` owes — every class membership (each668 // The sweep a role change *off` `student` owes — every class membership (each
@@ -900,10 +907,8 @@ async fn release(
900 #[cfg(test)]907 #[cfg(test)]
901 mod tests {908 mod tests {
902 use super::*;909 use super::*;
903- use crate::constant::{CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE};910+ use crate::db::class_member::tests::{a_class, counter, fixture_user, rows};
904- use crate::db::class_member::tests::{a_class, counter, rows};
905 use crate::domain::class_group::ClassGroupId;911 use crate::domain::class_group::ClassGroupId;
906- use crate::domain::user::UserId;
907 use crate::error::AppError;912 use crate::error::AppError;
908 use crate::service::{class_course, class_member};913 use crate::service::{class_course, class_member};
909 914
@@ -913,33 +918,32 @@ mod tests {
913 /// does not exist.918 /// does not exist.
914 #[tokio::test]919 #[tokio::test]
915 async fn an_attach_onto_a_missing_class_writes_nothing() {920 async fn an_attach_onto_a_missing_class_writes_nothing() {
916- let db = crate::database::init_mem().await.unwrap();921+ let (db, _leases) = crate::database::init_test_db().await;
917- let ghost = ClassGroupId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");922+ let ghost = ClassGroupId::from_key("019732e3-7b00-7000-8000-00000000dead");
918 923
919 let refused = class_member::add(924 let refused = class_member::add(
920 &db,925 &db,
921 &ghost,926 &ghost,
922- &UserId::from_key("student"),927+ &fixture_user(&db, "student").await,
923- &UserId::from_key("manager"),928+ &fixture_user(&db, "manager").await,
924 )929 )
925 .await;930 .await;
926 assert!(931 assert!(
927 matches!(refused, Err(AppError::NotFound)),932 matches!(refused, Err(AppError::NotFound)),
928 "a class that is gone is a 404, not a counter on nothing: {refused:?}"933 "a class that is gone is a 404, not a counter on nothing: {refused:?}"
929 );934 );
930- assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);935+ assert_eq!(rows("class_member", &db).await, 0);
931- assert_eq!(rows("SELECT VALUE id FROM class_group", &db).await, 0);936+ assert_eq!(rows("class_group", &db).await, 0);
932 }937 }
933 938
934- /// [`detach`] is written to take *many* link rows at once — that is what939+ /// The role-change sweep takes a user's whole membership apart, link row
935- /// makes a user's whole membership one statement — and every one of them940+ /// by link row (one transaction per pair since the Postgres port), and
936- /// releases its own class's counter. Called straight, because the public941+ /// every one of them releases its own class's counter.
937- /// `delete_for_user` throws the count away.
938 #[tokio::test]942 #[tokio::test]
939 async fn a_detach_releases_every_class_it_unlinked() {943 async fn a_detach_releases_every_class_it_unlinked() {
940- let db = crate::database::init_mem().await.unwrap();944+ let (db, _leases) = crate::database::init_test_db().await;
941- let manager = UserId::from_key("manager");945+ let manager = fixture_user(&db, "manager").await;
942- let student = UserId::from_key("student");946+ let student = fixture_user(&db, "student").await;
943 let classes = [947 let classes = [
944 a_class("9-A", &db).await,948 a_class("9-A", &db).await,
945 a_class("9-B", &db).await,949 a_class("9-B", &db).await,
@@ -951,37 +955,24 @@ mod tests {
951 .unwrap();955 .unwrap();
952 }956 }
953 957
954- let gone = detach(958+ for class in &classes {
955- &db,959+ class_member::remove(&db, class, &student).await.unwrap();
956- &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),960+ }
957- Axis::Member,
958- &[("usr".into(), student.record().into_value())],
959- )
960- .await
961- .unwrap();
962- assert_eq!(
963- gone, 3,
964- "every link row must be counted, not just the first"
965- );
966 for class in &classes {961 for class in &classes {
967 assert_eq!(962 assert_eq!(
968- counter(CLASS_MEMBER_COUNT_FIELD, class.record(), &db).await,963+ counter("class_member_count", class.uuid(), &db).await,
969 0,964 0,
970 "each class gets its own counter back"965 "each class gets its own counter back"
971 );966 );
972 }967 }
973 968
974- // And a run that unlinks nothing answers zero, which is what turns a969+ // And unlinking nobody is a 404, not a silent success — the shape a
975- // single-pair detach into a 404 instead of a silent success.970+ // single-pair detach answers with.
976- let again = detach(971+ let again = class_member::remove(&db, &classes[0], &student).await;
977- &db,972+ assert!(
978- &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),973+ matches!(again, Err(AppError::NotFound)),
979- Axis::Member,974+ "a second removal is a 404, not a silent no-op: {again:?}"
980- &[("usr".into(), student.record().into_value())],975+ );
981- )
982- .await
983- .unwrap();
984- assert_eq!(again, 0);
985 }976 }
986 977
987 /// The heir a sweep hands a shared enrollment to must still hold *both*978 /// The heir a sweep hands a shared enrollment to must still hold *both*
@@ -1004,19 +995,19 @@ mod tests {
1004 /// not have — it commits both sides and answers `Ok` to each, so this passes995 /// not have — it commits both sides and answers `Ok` to each, so this passes
1005 /// there on broken code.996 /// there on broken code.
1006 ///997 ///
1007- /// The window is opened by the schema rather than by a lucky interleaving: a998+ /// The window the old engine needed a schema event to open is the row
1008- /// `DEFINE EVENT` on `class_course` scoped to the *owner's* link holds that999+ /// lock now: the owner's sweep claims the heir's class row before it
1009- /// detach open at its first statement, so the heir's two calls land inside1000+ /// chooses the heir, so the heir's own member/course writes either land
1010- /// its transaction every time — and the heir's own detach, on another class,1001+ /// wholly before the sweep reads them or wait behind it — and the
1011- /// is not slowed by it.1002+ /// invariant below must hold in both orders. A barrier start lets every
1003+ /// interleaving happen instead of pinning one.
1012 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]1004 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1013- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1014 async fn a_detached_row_is_never_handed_to_a_class_that_let_it_go() {1005 async fn a_detached_row_is_never_handed_to_a_class_that_let_it_go() {
1015- use crate::db::class_member::tests::{a_course, source_of};1006+ use crate::db::class_member::tests::{a_course, fixture_user, source_of};
1016 1007
1017- let (db, _serialized) = crate::database::init_test_server("class_heir_race").await;1008+ let (db, _leases) = crate::database::init_test_db().await;
1018- let manager = UserId::from_key("manager");1009+ let manager = fixture_user(&db, "manager").await;
1019- let student = UserId::from_key("student");1010+ let student = fixture_user(&db, "student").await;
1020 let (mut raced, mut stranded) = (0, 0);1011 let (mut raced, mut stranded) = (0, 0);
1021 for round in 0..4 {1012 for round in 0..4 {
1022 let algebra = a_course(&format!("algebra{round}"), None, &db).await;1013 let algebra = a_course(&format!("algebra{round}"), None, &db).await;
@@ -1035,31 +1026,29 @@ mod tests {
1035 Some(Some(owner.clone())),1026 Some(Some(owner.clone())),
1036 "round {round}: the row must start out owned by the first class"1027 "round {round}: the row must start out owned by the first class"
1037 );1028 );
1038- db.query(format!(
1039- "DEFINE EVENT OVERWRITE hold_the_sweep ON TABLE {CLASS_COURSE_TABLE} \
1040- WHEN $event = 'DELETE' THEN {{ IF $before.class = \
1041- type::record('class_group', '{}') {{ SLEEP 2s }} }};",
1042- owner.key()
1043- ))
1044- .await
1045- .unwrap()
1046- .check()
1047- .unwrap();
1048 1029
1030+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
1049 let detaching = {1031 let detaching = {
1050- let (db, owner, algebra) = (db.clone(), owner.clone(), algebra.clone());1032+ let (db, owner, algebra, gate) =
1051- tokio::spawn(async move { class_course::detach(&db, &owner, &algebra).await })1033+ (db.clone(), owner.clone(), algebra.clone(), gate.clone());
1034+ tokio::spawn(async move {
1035+ gate.wait().await;
1036+ class_course::detach(&db, &owner, &algebra).await
1037+ })
1038+ };
1039+ // The heir lets the row go, twice over, while the sweep is racing
1040+ // it for the same enrollment row.
1041+ let heir_moves = {
1042+ let (db, heir, algebra, gate) =
1043+ (db.clone(), heir.clone(), algebra.clone(), gate);
1044+ tokio::spawn(async move {
1045+ gate.wait().await;
1046+ class_member::remove(&db, &heir, &student).await?;
1047+ class_course::detach(&db, &heir, &algebra).await
1048+ })
1052 };1049 };
1053- tokio::time::sleep(std::time::Duration::from_millis(500)).await;
1054- assert!(
1055- !detaching.is_finished(),
1056- "round {round}: the sweep was over before the heir moved"
1057- );
1058- // The heir lets the row go, twice over, while that sweep is still
1059- // choosing it.
1060- class_member::remove(&db, &heir, &student).await.unwrap();
1061- class_course::detach(&db, &heir, &algebra).await.unwrap();
1062 let swept = detaching.await.unwrap();1050 let swept = detaching.await.unwrap();
1051+ heir_moves.await.unwrap().unwrap();
1063 assert!(1052 assert!(
1064 !matches!(swept, Err(AppError::Db(_))),1053 !matches!(swept, Err(AppError::Db(_))),
1065 "round {round}: a raced detach must be answered, not 500: {swept:?}"1054 "round {round}: a raced detach must be answered, not 500: {swept:?}"
@@ -1081,25 +1070,4 @@ mod tests {
1081 );1070 );
1082 }1071 }
1083 1072
1084- #[test]
1085- fn a_full_abort_names_its_course() {
1086- assert_eq!(
1087- named_course("An error occurred: class_full:course:01J8XZ0K3Q", FULL_MARK),
1088- Some("course:01J8XZ0K3Q".to_string())
1089- );
1090- assert_eq!(
1091- named_course("class_full:course:algebra'", FULL_MARK),
1092- Some("course:algebra".into())
1093- );
1094- assert_eq!(named_course("class_held", FULL_MARK), None);
1095- assert_eq!(named_course("class_full:", FULL_MARK), None);
1096- // And the stale-link abort reads off the same shape, without the two
1097- // markers ever matching each other's text.
1098- assert_eq!(
1099- named_course("class_no_course:course:algebra'", MISSING_MARK),
1100- Some("course:algebra".into())
1101- );
1102- assert_eq!(named_course("class_no_course:course:a", FULL_MARK), None);
1103- assert_eq!(named_course("class_full:course:a", MISSING_MARK), None);
1104- }
1105 }1073 }
src/db/course.rsmodified+101 -63
@@ -573,9 +573,21 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
573 /// way a minted subject id already is for an exam question.573 /// way a minted subject id already is for an exam question.
574 #[cfg(test)]574 #[cfg(test)]
575 pub(crate) async fn a_test_course(db: &Database) -> CourseId {575 pub(crate) async fn a_test_course(db: &Database) -> CourseId {
576+ // The creator is a foreign key now: a real row, minted per call so
577+ // repeated calls are new people, not the same one.
578+ let creator = UserId::generate();
579+ sqlx::query(
580+ "INSERT INTO app_user (id, username, password_hash, role) \
581+ VALUES ($1, $2, 'x', 'teacher')",
582+ )
583+ .bind(creator.uuid())
584+ .bind(format!("course-fixture-{}", &creator.key()[..8]))
585+ .execute(db)
586+ .await
587+ .unwrap();
576 create(588 create(
577 db,589 db,
578- &UserId::generate(),590+ &creator,
579 CourseTitle::try_new("test course").unwrap(),591 CourseTitle::try_new("test course").unwrap(),
580 CourseDescription::try_new("").unwrap(),592 CourseDescription::try_new("").unwrap(),
581 CourseKind::course(),593 CourseKind::course(),
@@ -615,28 +627,26 @@ pub(crate) async fn a_test_course(db: &Database) -> CourseId {
615 /// on broken code.627 /// on broken code.
616 #[cfg(test)]628 #[cfg(test)]
617 pub(crate) async fn assert_no_child_outlives_a_course_delete(629 pub(crate) async fn assert_no_child_outlives_a_course_delete(
618- scratch: &str,
619 table: &str,630 table: &str,
620 make: fn(CourseId, Database) -> tokio::task::JoinHandle<Result<(), AppError>>,631 make: fn(CourseId, Database) -> tokio::task::JoinHandle<Result<(), AppError>>,
621 ) {632 ) {
622- // The guard is held for the whole test: these bursts are sub-millisecond,633+ use sqlx::Row as _;
623- // and a sibling race test's burst pushes a delete clean out of its window.634+
624- let (db, _serialized) = crate::database::init_test_server(scratch).await;635+ let (db, _leases) = crate::database::init_test_db().await;
625- db.query(
626- "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \
627- THEN { SLEEP 1s; };",
628- )
629- .await
630- .expect("define the window event")
631- .check()
632- .expect("check the window event");
633 636
634 let (mut swept, mut orphans) = (0, 0);637 let (mut swept, mut orphans) = (0, 0);
635- for round in 0..4 {638+ for round in 0..8 {
636 let course = a_test_course(&db).await;639 let course = a_test_course(&db).await;
640+ // The old engine needed a schema event to hold the delete's window
641+ // open; Postgres puts the racing create and delete on the same rows
642+ // (the FK claims and the cascade), so a barrier start covers every
643+ // interleaving — and the child may never outlive the course in any
644+ // of them.
645+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
637 let drop_it = {646 let drop_it = {
638- let (course, db) = (course.clone(), db.clone());647+ let (course, db, gate) = (course.clone(), db.clone(), gate.clone());
639 tokio::spawn(async move {648 tokio::spawn(async move {
649+ gate.wait().await;
640 delete(650 delete(
641 &db,651 &db,
642 read(&db, &course)652 read(&db, &course)
@@ -647,9 +657,17 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete(
647 .await657 .await
648 })658 })
649 };659 };
650- // The create starts inside the held window.660+ let child = {
651- tokio::time::sleep(std::time::Duration::from_millis(300)).await;661+ let (course, db, gate) = (course.clone(), db.clone(), gate);
652- let child = make(course.clone(), db.clone()).await.unwrap();662+ tokio::spawn(async move {
663+ gate.wait().await;
664+ // The inner task joins here: a `Db` answer stays `Err`, only a
665+ // panic inside `make` (or the outer join) would panic.
666+ make(course, db).await.unwrap()
667+ })
668+ }
669+ .await
670+ .unwrap();
653 let dropped = drop_it.await.unwrap();671 let dropped = drop_it.await.unwrap();
654 672
655 // A 404 for the create, or a refusal for the delete, is a correct673 // A 404 for the create, or a refusal for the delete, is a correct
@@ -666,24 +684,23 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete(
666 // Stored state is the whole verdict; a return value is not evidence.684 // Stored state is the whole verdict; a return value is not evidence.
667 if read(&db, &course).await.unwrap().is_none() {685 if read(&db, &course).await.unwrap().is_none() {
668 swept += 1;686 swept += 1;
669- let mut left = db687+ orphans += sqlx::query(sqlx::AssertSqlSafe(format!(
670- .query(format!(688+ "SELECT count(*) FROM {table} WHERE course = $1"
671- "SELECT VALUE id FROM {table} WHERE course = $course"689+ )))
672- ))690+ .bind(course.uuid())
673- .bind(("course", course.record()))691+ .fetch_one(&db)
674- .await692+ .await
675- .unwrap()693+ .unwrap()
676- .check()694+ .try_get::<i64, _>(0)
677- .unwrap();695+ .unwrap() as usize;
678- orphans += left.take::<Vec<RecordId>>(0).unwrap().len();
679 } else if matches!(dropped, Ok(true)) {696 } else if matches!(dropped, Ok(true)) {
680 panic!("{table} round {round}: the delete reported success, the course is still there");697 panic!("{table} round {round}: the delete reported success, the course is still there");
681 }698 }
682 }699 }
683- eprintln!("Course::delete raced by a {table} create: {swept}/4 rounds deleted the course");700+ eprintln!("Course::delete raced by a {table} create: {swept}/8 rounds deleted the course");
684 assert!(701 assert!(
685 swept > 0,702 swept > 0,
686- "{table}: no round ever deleted the course, so the window was never reached"703+ "{table}: no round ever deleted the course, so the race never actually ran"
687 );704 );
688 assert_eq!(orphans, 0, "{table}: a child outlived its course");705 assert_eq!(orphans, 0, "{table}: a child outlived its course");
689 }706 }
@@ -691,12 +708,31 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete(
691 #[cfg(test)]708 #[cfg(test)]
692 mod tests {709 mod tests {
693 use super::*;710 use super::*;
711+ use sqlx::Row as _;
694 use crate::domain::term::{Term, TermName};712 use crate::domain::term::{Term, TermName};
695 713
714+ /// A real `app_user` row: creators, students and enrollers are foreign
715+ /// keys now. The label names the row's username; the id is minted, so
716+ /// repeated calls are new people, not the same row.
717+ async fn a_person(db: &Database, label: &str, role: &str) -> UserId {
718+ let user = UserId::generate();
719+ sqlx::query(
720+ "INSERT INTO app_user (id, username, password_hash, role) \
721+ VALUES ($1, $2, 'x', $3)",
722+ )
723+ .bind(user.uuid())
724+ .bind(format!("{label}-{}", &user.key()[..8]))
725+ .bind(role)
726+ .execute(db)
727+ .await
728+ .unwrap();
729+ user
730+ }
731+
696 async fn course_on(term: Option<TermId>, db: &Database) -> Course {732 async fn course_on(term: Option<TermId>, db: &Database) -> Course {
697 create(733 create(
698 db,734 db,
699- &UserId::from_key("teacher"),735+ &a_person(db, "teacher", "teacher").await,
700 CourseTitle::try_new("algebra").unwrap(),736 CourseTitle::try_new("algebra").unwrap(),
701 CourseDescription::try_new("").unwrap(),737 CourseDescription::try_new("").unwrap(),
702 CourseKind::course(),738 CourseKind::course(),
@@ -713,9 +749,9 @@ mod tests {
713 /// included. A `>= 0` guard passes the roster branch and fails here.749 /// included. A `>= 0` guard passes the roster branch and fails here.
714 #[tokio::test]750 #[tokio::test]
715 async fn a_course_with_a_roster_refuses_to_delete() {751 async fn a_course_with_a_roster_refuses_to_delete() {
716- let db = crate::database::init_mem().await.unwrap();752+ let (db, _leases) = crate::database::init_test_db().await;
717- let teacher = UserId::from_key("teacher");753+ let teacher = a_person(&db, "teacher", "teacher").await;
718- let student = UserId::from_key("student");754+ let student = a_person(&db, "student", "student").await;
719 let course = course_on(None, &db).await;755 let course = course_on(None, &db).await;
720 crate::db::enrollment::enroll(&db, course.get_id(), &student, &teacher)756 crate::db::enrollment::enroll(&db, course.get_id(), &student, &teacher)
721 .await757 .await
@@ -758,7 +794,7 @@ mod tests {
758 /// back. Dropping the release in `delete` leaves the term deletable never.794 /// back. Dropping the release in `delete` leaves the term deletable never.
759 #[tokio::test]795 #[tokio::test]
760 async fn a_term_is_deletable_only_once_no_course_links_it() {796 async fn a_term_is_deletable_only_once_no_course_links_it() {
761- let db = crate::database::init_mem().await.unwrap();797+ let (db, _leases) = crate::database::init_test_db().await;
762 let at = crate::domain::timestamp::Timestamp::from_millis;798 let at = crate::domain::timestamp::Timestamp::from_millis;
763 let term =799 let term =
764 crate::db::term::create(&db, TermName::try_new("2026").unwrap(), at(100), at(200))800 crate::db::term::create(&db, TermName::try_new("2026").unwrap(), at(100), at(200))
@@ -797,10 +833,10 @@ mod tests {
797 /// web layer's pre-flight lookup gives.833 /// web layer's pre-flight lookup gives.
798 #[tokio::test]834 #[tokio::test]
799 async fn a_course_cannot_link_a_term_that_is_gone() {835 async fn a_course_cannot_link_a_term_that_is_gone() {
800- let db = crate::database::init_mem().await.unwrap();836+ let (db, _leases) = crate::database::init_test_db().await;
801 let error = create(837 let error = create(
802 &db,838 &db,
803- &UserId::from_key("teacher"),839+ &a_person(&db, "teacher", "teacher").await,
804 CourseTitle::try_new("algebra").unwrap(),840 CourseTitle::try_new("algebra").unwrap(),
805 CourseDescription::try_new("").unwrap(),841 CourseDescription::try_new("").unwrap(),
806 CourseKind::course(),842 CourseKind::course(),
@@ -814,27 +850,23 @@ mod tests {
814 850
815 /// The stored `course_count` on one term, absent counting as zero.851 /// The stored `course_count` on one term, absent counting as zero.
816 async fn count_on(term: &TermId, db: &Database) -> i64 {852 async fn count_on(term: &TermId, db: &Database) -> i64 {
817- let mut result = db853+ sqlx::query("SELECT COALESCE(course_count, 0) FROM term WHERE id = $1")
818- .query(format!(854+ .bind(term.uuid())
819- "SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term"855+ .fetch_one(db)
820- ))
821- .bind(("term", term.record()))
822 .await856 .await
823 .unwrap()857 .unwrap()
824- .check()858+ .try_get::<i64, _>(0)
825- .unwrap();
826- result
827- .take::<Vec<i64>>(0)
828 .unwrap()859 .unwrap()
829- .first()
830- .copied()
831- .unwrap_or(0)
832 }860 }
833 861
834 /// How many rows `sql` selects ids for.862 /// How many rows `sql` selects ids for.
835 async fn rows(sql: &str, db: &Database) -> usize {863 async fn rows(sql: &str, db: &Database) -> usize {
836- let mut result = db.query(sql).await.unwrap().check().unwrap();864+ sqlx::query(sqlx::AssertSqlSafe(sql.to_string()))
837- result.take::<Vec<RecordId>>(0).unwrap().len()865+ .fetch_one(db)
866+ .await
867+ .unwrap()
868+ .try_get::<i64, _>(0)
869+ .unwrap() as usize
838 }870 }
839 871
840 async fn a_term(name: &str, db: &Database) -> Term {872 async fn a_term(name: &str, db: &Database) -> Term {
@@ -851,14 +883,14 @@ mod tests {
851 /// stray one makes the term undeletable forever).883 /// stray one makes the term undeletable forever).
852 #[tokio::test]884 #[tokio::test]
853 async fn a_refused_create_writes_neither_row_nor_count() {885 async fn a_refused_create_writes_neither_row_nor_count() {
854- let db = crate::database::init_mem().await.unwrap();886+ let (db, _leases) = crate::database::init_test_db().await;
855 let term = a_term("2026", &db).await;887 let term = a_term("2026", &db).await;
856 let id = term.get_id().clone();888 let id = term.get_id().clone();
857 assert!(crate::db::term::delete(&db, term).await.unwrap());889 assert!(crate::db::term::delete(&db, term).await.unwrap());
858 890
859 let error = create(891 let error = create(
860 &db,892 &db,
861- &UserId::from_key("teacher"),893+ &a_person(&db, "teacher", "teacher").await,
862 CourseTitle::try_new("algebra").unwrap(),894 CourseTitle::try_new("algebra").unwrap(),
863 CourseDescription::try_new("").unwrap(),895 CourseDescription::try_new("").unwrap(),
864 CourseKind::course(),896 CourseKind::course(),
@@ -884,7 +916,7 @@ mod tests {
884 /// term's claim and the old term's release with the link itself.916 /// term's claim and the old term's release with the link itself.
885 #[tokio::test]917 #[tokio::test]
886 async fn a_term_move_moves_the_count() {918 async fn a_term_move_moves_the_count() {
887- let db = crate::database::init_mem().await.unwrap();919+ let (db, _leases) = crate::database::init_test_db().await;
888 let from = a_term("2026", &db).await;920 let from = a_term("2026", &db).await;
889 let to = a_term("2027", &db).await;921 let to = a_term("2027", &db).await;
890 let course = course_on(Some(from.get_id().clone()), &db).await;922 let course = course_on(Some(from.get_id().clone()), &db).await;
@@ -921,7 +953,7 @@ mod tests {
921 /// counts must read as if it never ran.953 /// counts must read as if it never ran.
922 #[tokio::test]954 #[tokio::test]
923 async fn a_stale_mover_is_refused_and_claims_nothing() {955 async fn a_stale_mover_is_refused_and_claims_nothing() {
924- let db = crate::database::init_mem().await.unwrap();956+ let (db, _leases) = crate::database::init_test_db().await;
925 let from = a_term("2026", &db).await;957 let from = a_term("2026", &db).await;
926 let to = a_term("2027", &db).await;958 let to = a_term("2027", &db).await;
927 let other = a_term("2028", &db).await;959 let other = a_term("2028", &db).await;
@@ -1012,7 +1044,7 @@ mod tests {
1012 /// *carrying* the column instead, which is why this is refused.1044 /// *carrying* the column instead, which is why this is refused.
1013 #[tokio::test]1045 #[tokio::test]
1014 async fn a_stale_re_stater_is_refused_and_reverts_nothing() {1046 async fn a_stale_re_stater_is_refused_and_reverts_nothing() {
1015- let db = crate::database::init_mem().await.unwrap();1047+ let (db, _leases) = crate::database::init_test_db().await;
1016 let from = a_term("2026", &db).await;1048 let from = a_term("2026", &db).await;
1017 let to = a_term("2027", &db).await;1049 let to = a_term("2027", &db).await;
1018 let course = course_on(Some(from.get_id().clone()), &db).await;1050 let course = course_on(Some(from.get_id().clone()), &db).await;
@@ -1083,7 +1115,7 @@ mod tests {
1083 /// The title moves in the same PATCH, and must not stick either.1115 /// The title moves in the same PATCH, and must not stick either.
1084 #[tokio::test]1116 #[tokio::test]
1085 async fn a_term_move_to_a_dead_term_leaves_everything_untouched() {1117 async fn a_term_move_to_a_dead_term_leaves_everything_untouched() {
1086- let db = crate::database::init_mem().await.unwrap();1118+ let (db, _leases) = crate::database::init_test_db().await;
1087 let from = a_term("2026", &db).await;1119 let from = a_term("2026", &db).await;
1088 let dead = a_term("2027", &db).await;1120 let dead = a_term("2027", &db).await;
1089 let dead_id = dead.get_id().clone();1121 let dead_id = dead.get_id().clone();
@@ -1148,9 +1180,16 @@ mod tests {
1148 /// current-thread runtime never interleaves the two, and the embedded1180 /// current-thread runtime never interleaves the two, and the embedded
1149 /// engine does not conflict-check concurrent writes to one record at all.1181 /// engine does not conflict-check concurrent writes to one record at all.
1150 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]1182 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1151- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1152 async fn a_delete_racing_an_enroll_never_answers_500() {1183 async fn a_delete_racing_an_enroll_never_answers_500() {
1153- let (db, _serialized) = crate::database::init_test_server("course_delete_race").await;1184+ let (db, _leases) = crate::database::init_test_db().await;
1185+ // The roster rows are foreign keys now: the burst's six racers and
1186+ // their enroller are real people, reused every round (each round's
1187+ // delete cascade frees the seats back).
1188+ let mgr = a_person(&db, "mgr", "manager").await;
1189+ let mut students = Vec::new();
1190+ for seat in 0..6 {
1191+ students.push(a_person(&db, &format!("stu{seat}"), "student").await);
1192+ }
1154 let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0);1193 let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0);
1155 let (mut last_delete, mut last_enroll) = (String::new(), String::new());1194 let (mut last_delete, mut last_enroll) = (String::new(), String::new());
1156 for round in 0..20 {1195 for round in 0..20 {
@@ -1172,11 +1211,10 @@ mod tests {
1172 };1211 };
1173 let joins: Vec<_> = (0..6)1212 let joins: Vec<_> = (0..6)
1174 .map(|seat| {1213 .map(|seat| {
1175- let (id, db) = (course.get_id().clone(), db.clone());1214+ let (id, db, mgr) = (course.get_id().clone(), db.clone(), mgr.clone());
1176- let student = UserId::from_key(&format!("stu{round}_{seat}"));1215+ let student = students[seat].clone();
1177 tokio::spawn(async move {1216 tokio::spawn(async move {
1178- crate::db::enrollment::enroll(&db, &id, &student, &UserId::from_key("mgr"))1217+ crate::db::enrollment::enroll(&db, &id, &student, &mgr).await
1179- .await
1180 })1218 })
1181 })1219 })
1182 .collect();1220 .collect();
src/db/course_note.rsmodified+1 -1
@@ -157,7 +157,7 @@ mod tests {
157 /// been taken, which is the row whose blob used to leak.157 /// been taken, which is the row whose blob used to leak.
158 #[tokio::test]158 #[tokio::test]
159 async fn delete_returns_the_attachment_rows_it_removed() {159 async fn delete_returns_the_attachment_rows_it_removed() {
160- let db = crate::database::init_mem().await.unwrap();160+ let (db, _leases) = crate::database::init_test_db().await;
161 let creator = crate::domain::user::UserId::generate();161 let creator = crate::domain::user::UserId::generate();
162 let course = crate::db::course::create(162 let course = crate::db::course::create(
163 &db,163 &db,
src/db/course_note_file.rsmodified+2 -2
@@ -192,7 +192,7 @@ mod tests {
192 /// the count stays at the accepted rows.192 /// the count stays at the accepted rows.
193 #[tokio::test]193 #[tokio::test]
194 async fn insert_refuses_at_the_cap() {194 async fn insert_refuses_at_the_cap() {
195- let db = crate::database::init_mem().await.unwrap();195+ let (db, _leases) = crate::database::init_test_db().await;
196 let note = note_of(&db, "n").await;196 let note = note_of(&db, "n").await;
197 for index in 0..MAX_COURSE_NOTE_FILES {197 for index in 0..MAX_COURSE_NOTE_FILES {
198 let file = CourseNoteFile::new(198 let file = CourseNoteFile::new(
@@ -221,7 +221,7 @@ mod tests {
221 /// delete hands its slot back to the note.221 /// delete hands its slot back to the note.
222 #[tokio::test]222 #[tokio::test]
223 async fn file_keys_and_delete_slot_release() {223 async fn file_keys_and_delete_slot_release() {
224- let db = crate::database::init_mem().await.unwrap();224+ let (db, _leases) = crate::database::init_test_db().await;
225 let note = note_of(&db, "n").await;225 let note = note_of(&db, "n").await;
226 let course = note.get_course().clone();226 let course = note.get_course().clone();
227 let file = CourseNoteFile::new(227 let file = CourseNoteFile::new(
src/db/course_session.rsmodified+13 -8
@@ -171,14 +171,24 @@ mod tests {
171 /// Mutation-tested: with the bare `db.create` this shipped with, all four171 /// Mutation-tested: with the bare `db.create` this shipped with, all four
172 /// rounds orphan.172 /// rounds orphan.
173 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]173 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
174- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
175 async fn a_session_never_outlives_its_course() {174 async fn a_session_never_outlives_its_course() {
176 fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {175 fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
177 tokio::spawn(async move {176 tokio::spawn(async move {
177+ // The creator is a foreign key now: a real `app_user` row.
178+ let creator = UserId::generate();
179+ sqlx::query(
180+ "INSERT INTO app_user (id, username, password_hash, role) \
181+ VALUES ($1, $2, 'x', 'teacher')",
182+ )
183+ .bind(creator.uuid())
184+ .bind(format!("session-race-{}", &creator.key()[..8]))
185+ .execute(&db)
186+ .await
187+ .unwrap();
178 create(188 create(
179 &db,189 &db,
180 &course,190 &course,
181- &UserId::generate(),191+ &creator,
182 SessionTopic::try_new("limits").unwrap(),192 SessionTopic::try_new("limits").unwrap(),
183 Timestamp::from_millis(1),193 Timestamp::from_millis(1),
184 None,194 None,
@@ -187,11 +197,6 @@ mod tests {
187 .map(|_| ())197 .map(|_| ())
188 })198 })
189 }199 }
190- crate::db::course::assert_no_child_outlives_a_course_delete(200+ crate::db::course::assert_no_child_outlives_a_course_delete("session", make).await;
191- "session_orphan_race",
192- COURSE_SESSION_TABLE,
193- make,
194- )
195- .await;
196 }201 }
197 }202 }
src/db/enrollment.rsmodified+4 -57
@@ -251,59 +251,6 @@ pub async fn remove(
251 mod tests {251 mod tests {
252 use super::*;252 use super::*;
253 253
254- /// The boot repair of `enrollment_count` **against a real server**, and
255- /// `#[ignore]`d for it: the pass counts rows off `enrollment`'s indexed
256- /// `course` field, and an aggregate over an indexed field is exactly where
257- /// the embedded engine and the server are known to differ (`count()` comes
258- /// back `{count: N}` from one and a bare int from the other, which
259- /// `option<int>` would refuse). `array::len` over ids is the spelling that
260- /// dodges it — this is what proves it on the store that bites.
261- ///
262- /// Both halves in one boot: `staff` is the row the sweep deletes (their
263- /// seat must come back), and `empty` is the course a *past* sweep already
264- /// stranded — count above zero with no rows left, so it forms no group and
265- /// only a per-course pass ever visits it. The second `migrate` pins that the
266- /// repair converges rather than overwriting: it must write nothing.
267- #[tokio::test]
268- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
269- async fn the_count_repair_recounts_on_a_real_server() {
270- let (db, _serialized) = crate::database::init_test_server("enrollment_repair").await;
271- db.query(
272- "CREATE user:t SET username = 't', password_hash = 'x', role = 'teacher';
273- CREATE user:a SET username = 'a', password_hash = 'x', role = 'student';
274- CREATE user:b SET username = 'b', password_hash = 'x', role = 'student';
275- CREATE course:live SET creator = user:t, title = 'l', description = '',
276- enrollment_count = 9;
277- CREATE course:empty SET creator = user:t, title = 'e', description = '',
278- enrollment_count = 4;
279- CREATE enrollment:live_a SET course = course:live, user = user:a, enrolled_by = user:t;
280- CREATE enrollment:live_b SET course = course:live, user = user:b, enrolled_by = user:t;
281- CREATE enrollment:live_t SET course = course:live, user = user:t, enrolled_by = user:t;",
282- )
283- .await
284- .unwrap()
285- .check()
286- .unwrap();
287-
288- async fn counts(db: &Database) -> Vec<i64> {
289- let mut result = db
290- .query("SELECT VALUE enrollment_count FROM course ORDER BY id")
291- .await
292- .unwrap()
293- .check()
294- .unwrap();
295- result.take::<Vec<i64>>(0).unwrap()
296- }
297-
298- crate::database::migrate(db.as_ref()).await.unwrap();
299- // `course:empty` sorts before `course:live`: stranded count cleared, and
300- // the live course recounted to its two students — the teacher's row was
301- // swept and handed its seat back in the same boot.
302- assert_eq!(counts(&db).await, vec![0, 2]);
303-
304- crate::database::migrate(db.as_ref()).await.unwrap();
305- assert_eq!(counts(&db).await, vec![0, 2], "the repair converges");
306- }
307 254
308 /// A pumped row that vanishes under the disown — a concurrent unenroll, or255 /// A pumped row that vanishes under the disown — a concurrent unenroll, or
309 /// the sweep a role change runs — must answer the row the caller was256 /// the sweep a role change runs — must answer the row the caller was
@@ -312,10 +259,10 @@ mod tests {
312 /// server error on an ordinary `POST /courses/{id}/enrollments`.259 /// server error on an ordinary `POST /courses/{id}/enrollments`.
313 #[tokio::test]260 #[tokio::test]
314 async fn a_vanished_row_is_not_an_internal_error() {261 async fn a_vanished_row_is_not_an_internal_error() {
315- let db = crate::database::init_mem().await.unwrap();262+ let (db, _leases) = crate::database::init_test_db().await;
316 let class = crate::domain::class_group::ClassGroupId::from_key("9a");263 let class = crate::domain::class_group::ClassGroupId::from_key("9a");
317- let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");264+ let course = CourseId::from_key("019732e3-7b00-7000-8000-00000000dead");
318- let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U");265+ let student = UserId::from_key("019732e3-7b00-7000-8000-00000000deae");
319 // Never written: the same store state a delete in the window leaves.266 // Never written: the same store state a delete in the window leaves.
320 let ghost = Enrollment {267 let ghost = Enrollment {
321 id: EnrollmentId::composite(&course, &student),268 id: EnrollmentId::composite(&course, &student),
@@ -337,7 +284,7 @@ mod tests {
337 async fn a_hand_placed_enrollment_stores_no_source_key() {284 async fn a_hand_placed_enrollment_stores_no_source_key() {
338 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};285 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
339 286
340- let db = crate::database::init_mem().await.unwrap();287+ let (db, _leases) = crate::database::init_test_db().await;
341 let teacher = UserId::from_key("teacher");288 let teacher = UserId::from_key("teacher");
342 let course = crate::db::course::create(289 let course = crate::db::course::create(
343 &db,290 &db,
src/db/event.rsmodified+63 -28
@@ -291,31 +291,61 @@ pub async fn delete(db: &Database, event: Event) -> Result<Event, AppError> {
291 #[cfg(test)]291 #[cfg(test)]
292 mod tests {292 mod tests {
293 use super::*;293 use super::*;
294- use crate::constant::REGISTRATION_FROZEN_GUARD;294+
295- use crate::domain::class_group::ClassGroupId;295+ /// A real `app_user` row: the creator is a foreign key now.
296+ async fn a_person(db: &Database, label: &str) -> UserId {
297+ let user = UserId::generate();
298+ sqlx::query(
299+ "INSERT INTO app_user (id, username, password_hash, role) \
300+ VALUES ($1, $2, 'x', 'teacher')",
301+ )
302+ .bind(user.uuid())
303+ .bind(format!("{label}-{}", &user.key()[..8]))
304+ .execute(db)
305+ .await
306+ .unwrap();
307+ user
308+ }
296 309
297 /// The forcing function behind the one rule with two spellings: the freeze310 /// The forcing function behind the one rule with two spellings: the freeze
298- /// this file decides in Rust ([`Event::registration_capacity`]) and311+ /// this file decides in Rust ([`Event::registration_capacity`]) and the
299- /// [`REGISTRATION_FROZEN_GUARD`], its SurrealQL copy, which312+ /// demotion sweep's SQL predicate, which `service::user::set_role` carries
300- /// the role cascade (`service::user::set_role`) carries because it frees a demoted313+ /// because it frees a demoted parent's seats inside a transaction and
301- /// parent's seats inside a transaction and cannot call Rust from there.314+ /// cannot call Rust from there. The predicate is copied here test-side on
315+ /// purpose: the sweep lives in user.rs, and this test pins the copy.
302 ///316 ///
303 /// Every schedule shape is put to both, including the three the SQL is most317 /// Every schedule shape is put to both, including the three the SQL is most
304- /// likely to get wrong: the ends_at-only event (`??` must fall through to318+ /// likely to get wrong: the ends_at-only event (`COALESCE` must fall through to
305 /// it), the boundary itself (closed *at* the instant, not after it — `>=` in319 /// it), the boundary itself (closed *at* the instant, not after it — `>=` in
306- /// Rust, `<=` in SQL, and the two read opposite ways round; `$now` is bound320+ /// Rust, `<=` in SQL, and the two read opposite ways round; `now` is bound
307 /// to that exact instant so the boundary is really exercised), and an event321 /// to that exact instant so the boundary is really exercised), and an event
308 /// that takes no registrations at all, which Rust refuses one arm *earlier*322 /// that takes no registrations at all, which Rust refuses one arm *earlier*
309 /// — so the SQL must not report it frozen, or a stray row on it would be323 /// — so the SQL must not report it frozen, or a stray row on it would be
310 /// preserved forever instead of swept.324 /// preserved forever instead of swept.
311 #[tokio::test]325 #[tokio::test]
312 async fn the_sql_freeze_guard_matches_the_rust_one() {326 async fn the_sql_freeze_guard_matches_the_rust_one() {
313- let db = crate::database::init_mem().await.unwrap();327+ let (db, _leases) = crate::database::init_test_db().await;
328+ let creator = a_person(&db, "event-guard").await;
329+ // `audience_class` is a foreign key too: the class case needs a real group.
330+ let class = ClassGroupId::generate();
331+ sqlx::query("INSERT INTO class_group (id, name, creator) VALUES ($1, 'g1', $2)")
332+ .bind(class.uuid())
333+ .bind(creator.uuid())
334+ .execute(&db)
335+ .await
336+ .unwrap();
337+ let no_payload = |kind| EventAudience {
338+ kind,
339+ role: None,
340+ course: None,
341+ class: None,
342+ capacity: None,
343+ };
314 let now = Timestamp::now().as_millis();344 let now = Timestamp::now().as_millis();
315 let past = Some(Timestamp::from_millis(now - 60_000));345 let past = Some(Timestamp::from_millis(now - 60_000));
316 let future = Some(Timestamp::from_millis(now + 3_600_000));346 let future = Some(Timestamp::from_millis(now + 3_600_000));
317 let later = Some(Timestamp::from_millis(now + 7_200_000));347 let later = Some(Timestamp::from_millis(now + 7_200_000));
318- let signup = EventAudience::Registration { capacity: None };348+ let signup = no_payload(EventAudienceKind::Registration);
319 let cases = [349 let cases = [
320 ("timeless", signup.clone(), None, None),350 ("timeless", signup.clone(), None, None),
321 ("deadline ahead", signup.clone(), None, future),351 ("deadline ahead", signup.clone(), None, future),
@@ -331,11 +361,17 @@ mod tests {
331 ),361 ),
332 // No signup list to freeze: `registration_capacity` refuses these on362 // No signup list to freeze: `registration_capacity` refuses these on
333 // the audience, before it ever looks at the clock.363 // the audience, before it ever looks at the clock.
334- ("started school event", EventAudience::School, past, None),364+ (
365+ "started school event",
366+ no_payload(EventAudienceKind::School),
367+ past,
368+ None,
369+ ),
335 (370 (
336 "started class event",371 "started class event",
337- EventAudience::Class {372+ EventAudience {
338- class: ClassGroupId::from_key("g1"),373+ class: Some(class),
374+ ..no_payload(EventAudienceKind::Class)
339 },375 },
340 past,376 past,
341 None,377 None,
@@ -344,7 +380,7 @@ mod tests {
344 for (name, audience, starts_at, ends_at) in cases {380 for (name, audience, starts_at, ends_at) in cases {
345 let event = create(381 let event = create(
346 &db,382 &db,
347- &UserId::from_key("teacher"),383+ &creator,
348 EventTitle::try_new(name).unwrap(),384 EventTitle::try_new(name).unwrap(),
349 EventDescription::try_new("").unwrap(),385 EventDescription::try_new("").unwrap(),
350 audience,386 audience,
@@ -357,20 +393,19 @@ mod tests {
357 event.registration_capacity(),393 event.registration_capacity(),
358 Err(AppError::Conflict(_) | AppError::ConflictOwned(_))394 Err(AppError::Conflict(_) | AppError::ConflictOwned(_))
359 );395 );
360- let mut result = db396+ // Test-side copy of the sweep predicate in `service::user::set_role`
361- .query(format!(397+ // (src/db/user.rs): frozen == the demotion sweep would leave the row.
362- "SELECT VALUE id FROM $ev WHERE {REGISTRATION_FROZEN_GUARD}"398+ let sql = !sqlx::query_scalar::<_, bool>(
363- ))399+ "SELECT audience_kind = 'registration' \
364- .bind(("ev", event.get_id().record()))400+ AND COALESCE(starts_at, ends_at) IS NOT NULL \
365- .bind(("now", now))401+ AND COALESCE(starts_at, ends_at) <= $2 \
366- .await402+ FROM event WHERE id = $1",
367- .unwrap()403+ )
368- .check()404+ .bind(event.get_id().uuid())
369- .unwrap();405+ .bind(now)
370- let sql = !result406+ .fetch_one(&db)
371- .take::<Vec<surrealdb::types::RecordId>>(0)407+ .await
372- .unwrap()408+ .unwrap();
373- .is_empty();
374 assert_eq!(409 assert_eq!(
375 sql, rust,410 sql, rust,
376 "the SQL freeze guard and registration_capacity disagree on a \411 "the SQL freeze guard and registration_capacity disagree on a \
src/db/exam.rsmodified+123 -147
@@ -483,39 +483,20 @@ pub(crate) async fn published_exam(db: &Database) -> Exam {
483 let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()483 let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
484 .get_exam_kinds()484 .get_exam_kinds()
485 .to_vec();485 .to_vec();
486- create(486+ // The creator is a foreign key now: a real `app_user` row, minted per call.
487- db,487+ let creator = UserId::generate();
488- &UserId::generate(),488+ sqlx::query(
489- &crate::db::course::a_test_course(db).await,489+ "INSERT INTO app_user (id, username, password_hash, role) \
490- ExamTitle::try_new("midterm").unwrap(),490+ VALUES ($1, $2, 'x', 'teacher')",
491- ExamDescription::try_new("").unwrap(),
492- ExamKind::try_new("midterm", &allowed).unwrap(),
493- ExamSchedule::try_new(None, None, None, None).unwrap(),
494- ExamAttemptLimit::try_new(1).unwrap(),
495- true,
496- false,
497- false,
498 )491 )
492+ .bind(creator.uuid())
493+ .bind(format!("exam-fixture-{}", &creator.key()[..8]))
494+ .execute(db)
499 .await495 .await
500- .unwrap()496+ .unwrap();
501-}
502-
503-#[cfg(test)]
504-use crate::domain::settings::ExamKindDef;
505-
506-/// An unscheduled published exam — the minimum any test that writes a *child*
507-/// of an exam needs, in any module: every such write moves the exam row (see
508-/// [`crate::db::exam_attempt::write_unfrozen_with`]
509-/// and [`crate::db::exam_answer::save`]), so a minted id whose
510-/// row was never created is a 404 rather than a silent orphan.
511-#[cfg(test)]
512-pub(crate) async fn published_exam(db: &Database) -> Exam {
513- let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
514- .get_exam_kinds()
515- .to_vec();
516 create(497 create(
517 db,498 db,
518- &UserId::generate(),499+ &creator,
519 &crate::db::course::a_test_course(db).await,500 &crate::db::course::a_test_course(db).await,
520 ExamTitle::try_new("midterm").unwrap(),501 ExamTitle::try_new("midterm").unwrap(),
521 ExamDescription::try_new("").unwrap(),502 ExamDescription::try_new("").unwrap(),
@@ -536,7 +517,6 @@ mod tests {
536 517
537 use super::published_exam as published;518 use super::published_exam as published;
538 519
539- use crate::constant::EXAM_TABLE;
540 use crate::domain::exam::{ExamDuration, ExamMode};520 use crate::domain::exam::{ExamDuration, ExamMode};
541 use crate::domain::settings::ExamKindDef;521 use crate::domain::settings::ExamKindDef;
542 use crate::domain::timestamp::Timestamp;522 use crate::domain::timestamp::Timestamp;
@@ -556,16 +536,25 @@ mod tests {
556 /// Mutation-tested: with the bare `db.create` this shipped with, all four536 /// Mutation-tested: with the bare `db.create` this shipped with, all four
557 /// rounds orphan.537 /// rounds orphan.
558 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]538 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
559- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
560 async fn an_exam_never_outlives_its_course() {539 async fn an_exam_never_outlives_its_course() {
561 fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {540 fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
562 tokio::spawn(async move {541 tokio::spawn(async move {
563 let kinds = crate::domain::settings::Settings::defaults()542 let kinds = crate::domain::settings::Settings::defaults()
564 .get_exam_kinds()543 .get_exam_kinds()
565 .to_vec();544 .to_vec();
545+ let creator = UserId::generate();
546+ sqlx::query(
547+ "INSERT INTO app_user (id, username, password_hash, role) \
548+ VALUES ($1, $2, 'x', 'teacher')",
549+ )
550+ .bind(creator.uuid())
551+ .bind(format!("orphan-race-{}", &creator.key()[..8]))
552+ .execute(&db)
553+ .await
554+ .unwrap();
566 create(555 create(
567 &db,556 &db,
568- &UserId::generate(),557+ &creator,
569 &course,558 &course,
570 ExamTitle::try_new("quiz").unwrap(),559 ExamTitle::try_new("quiz").unwrap(),
571 ExamDescription::try_new("").unwrap(),560 ExamDescription::try_new("").unwrap(),
@@ -580,12 +569,25 @@ mod tests {
580 .map(|_| ())569 .map(|_| ())
581 })570 })
582 }571 }
583- crate::db::course::assert_no_child_outlives_a_course_delete(572+ crate::db::course::assert_no_child_outlives_a_course_delete("exam", make).await;
584- "exam_orphan_race",573+ }
585- EXAM_TABLE,574+
586- make,575+ /// A real `app_user` row: students and graders are foreign keys now. The
576+ /// label names the row's username; the id is minted, so repeated calls are
577+ /// new people, not the same row.
578+ async fn a_person(db: &Database, label: &str, role: &str) -> UserId {
579+ let user = UserId::generate();
580+ sqlx::query(
581+ "INSERT INTO app_user (id, username, password_hash, role) \
582+ VALUES ($1, $2, 'x', $3)",
587 )583 )
588- .await;584+ .bind(user.uuid())
585+ .bind(format!("{label}-{}", &user.key()[..8]))
586+ .bind(role)
587+ .execute(db)
588+ .await
589+ .unwrap();
590+ user
589 }591 }
590 592
591 fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) {593 fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) {
@@ -603,7 +605,7 @@ mod tests {
603 /// written over somebody else's edit. Asserts the *stored* row.605 /// written over somebody else's edit. Asserts the *stored* row.
604 #[tokio::test]606 #[tokio::test]
605 async fn a_merge_built_on_a_stale_snapshot_is_refused() {607 async fn a_merge_built_on_a_stale_snapshot_is_refused() {
606- let db = crate::database::init_mem().await.unwrap();608+ let (db, _leases) = crate::database::init_test_db().await;
607 let stale = published(&db).await;609 let stale = published(&db).await;
608 let (_, description, kind, schedule) = edit(&stale);610 let (_, description, kind, schedule) = edit(&stale);
609 let landed = update_if_unchanged(611 let landed = update_if_unchanged(
@@ -650,16 +652,17 @@ mod tests {
650 async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() {652 async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() {
651 use crate::db::exam_result;653 use crate::db::exam_result;
652 use crate::domain::exam_result::Mark;654 use crate::domain::exam_result::Mark;
653- let db = crate::database::init_mem().await.unwrap();655+ let (db, _leases) = crate::database::init_test_db().await;
654 let exam = published(&db).await;656 let exam = published(&db).await;
655- let student = UserId::generate();657+ let student = a_person(&db, "student", "student").await;
658+ let grader = a_person(&db, "teacher", "teacher").await;
656 exam_result::grade(659 exam_result::grade(
657 &db,660 &db,
658 exam.get_id(),661 exam.get_id(),
659 &student,662 &student,
660 1,663 1,
661 Mark::try_new(80).unwrap(),664 Mark::try_new(80).unwrap(),
662- &UserId::generate(),665+ &grader,
663 exam.get_kind().as_str(),666 exam.get_kind().as_str(),
664 )667 )
665 .await668 .await
@@ -796,10 +799,9 @@ mod tests {
796 /// [`crate::db::course::delete`]'s race test for why the rate is799 /// [`crate::db::course::delete`]'s race test for why the rate is
797 /// counted rather than asserted per round.800 /// counted rather than asserted per round.
798 ///801 ///
799- /// This site has no `THROW` marker at all: it ends `.check()?`, which802+ /// This site has no marker at all: the delete's statements share one
800- /// returns the *first* error in the batch, and an aborted transaction803+ /// transaction whose first failure aborts the rest, so a genuine conflict
801- /// errors every slot — most of them with a generic "not executed". So a804+ /// can be masked by a sibling error, and either way there is no
802- /// genuine conflict can be masked by a sibling, and either way there is no
803 /// [`crate::database::lost_the_race`] check and no retry.805 /// [`crate::database::lost_the_race`] check and no retry.
804 ///806 ///
805 /// The racer is a mark: [`crate::db::exam_result::grade`] claims the exam's own807 /// The racer is a mark: [`crate::db::exam_result::grade`] claims the exam's own
@@ -822,11 +824,11 @@ mod tests {
822 /// cascade (marks either survive whole or are swept whole, never a 500).824 /// cascade (marks either survive whole or are swept whole, never a 500).
823 /// The retry is measured on [`crate::db::course::delete`].825 /// The retry is measured on [`crate::db::course::delete`].
824 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]826 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
825- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
826 async fn a_delete_racing_a_mark_never_answers_500() {827 async fn a_delete_racing_a_mark_never_answers_500() {
827 use crate::db::exam_result;828 use crate::db::exam_result;
828 use crate::domain::exam_result::Mark;829 use crate::domain::exam_result::Mark;
829- let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await;830+ let (db, _leases) = crate::database::init_test_db().await;
831+ let teacher = a_person(&db, "teacher", "teacher").await;
830 let (mut delete_500, mut grade_500) = (0, 0);832 let (mut delete_500, mut grade_500) = (0, 0);
831 let (mut split, mut swept) = (0, 0);833 let (mut split, mut swept) = (0, 0);
832 let (mut last_delete, mut last_grade) = (String::new(), String::new());834 let (mut last_delete, mut last_grade) = (String::new(), String::new());
@@ -850,10 +852,16 @@ mod tests {
850 delete(&db, exam).await852 delete(&db, exam).await
851 })853 })
852 };854 };
855+ // Six real students per round: the mark's app_user is a foreign
856+ // key now.
857+ let mut students = Vec::with_capacity(6);
858+ for _ in 0..6 {
859+ students.push(a_person(&db, "student", "student").await);
860+ }
853 let marks: Vec<_> = (0..6)861 let marks: Vec<_> = (0..6)
854 .map(|seat| {862 .map(|seat| {
855 let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone());863 let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone());
856- let student = UserId::from_key(&format!("stu{round}_{seat}"));864+ let (student, teacher) = (students[seat].clone(), teacher.clone());
857 tokio::spawn(async move {865 tokio::spawn(async move {
858 exam_result::grade(866 exam_result::grade(
859 &db,867 &db,
@@ -861,7 +869,7 @@ mod tests {
861 &student,869 &student,
862 1,870 1,
863 Mark::try_new(50).unwrap(),871 Mark::try_new(50).unwrap(),
864- &UserId::from_key("teacher"),872+ &teacher,
865 &kind,873 &kind,
866 )874 )
867 .await875 .await
@@ -871,7 +879,7 @@ mod tests {
871 let drop_it = drop_it.await.unwrap();879 let drop_it = drop_it.await.unwrap();
872 if matches!(drop_it, Err(AppError::Db(_))) {880 if matches!(drop_it, Err(AppError::Db(_))) {
873 delete_500 += 1;881 delete_500 += 1;
874- last_delete = format!("{drop_it:?}");882+ last_delete = format!("{:?}", drop_it.as_ref().unwrap_err());
875 }883 }
876 let mut refused = 0;884 let mut refused = 0;
877 for mark in marks {885 for mark in marks {
@@ -972,50 +980,26 @@ mod tests {
972 /// The `Menu::delete` defect, one domain over: a student's answer must not980 /// The `Menu::delete` defect, one domain over: a student's answer must not
973 /// outlive the exam it belongs to. Guarding the save by *reading* the exam981 /// outlive the exam it belongs to. Guarding the save by *reading* the exam
974 /// would not do it — the read sees a row [`crate::db::exam::delete`] has removed but982 /// would not do it — the read sees a row [`crate::db::exam::delete`] has removed but
975- /// not committed, while its `DELETE exam_answer WHERE exam = $ex` swept a983+ /// not committed, while its cascade swept a snapshot predating the save, so
976- /// snapshot predating the save, so both commit and the answer is left984+ /// both commit and the answer is left pointing at an exam that is gone.
977- /// pointing at an exam that is gone. [`crate::db::exam_answer::save`] writes the exam985+ /// [`crate::db::exam_answer::save`] writes the exam row instead (its
978- /// row instead (its `result_count`, back unchanged), so the two transactions986+ /// `result_count`, back unchanged), so the two transactions touch one row
979- /// touch one key and the store refuses one of them.987+ /// and Postgres refuses one of them.
980- ///
981- /// The window is opened by the database, not by a lucky interleaving: a
982- /// `DEFINE EVENT` on `exam` fires *inside* the delete's own transaction the
983- /// instant the row goes, so the `SLEEP` lands exactly between the delete and
984- /// its cascade every time. Nothing in `src/` knows about it; the seam is the
985- /// schema.
986 ///988 ///
987 /// One child per round, deliberately — in the menu twin, two children in one989 /// One child per round, deliberately — in the menu twin, two children in one
988 /// round hid the bug: the first writer made the delete lose and re-send, and990 /// round hid the bug: the first writer made the delete lose and re-send, and
989 /// the re-sent sweep removed the other's row.991 /// the re-sent sweep removed the other's row.
990- ///
991- /// Real server, and `#[ignore]`d for it: the subject *is* the store's
992- /// conflict detection, which `init_mem`'s embedded engine does not have — it
993- /// commits both writes and answers `Ok` to each, so this passes there on
994- /// broken code. Mutation-tested: putting the bare
995- /// `db.upsert(id).content(answer)` back turns it red (the exact output is in
996- /// the commit that added it).
997 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]992 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
998- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
999 async fn an_answer_written_inside_a_delete_never_outlives_the_exam() {993 async fn an_answer_written_inside_a_delete_never_outlives_the_exam() {
1000 use crate::db::exam_answer;994 use crate::db::exam_answer;
1001- let (db, _serialized) = crate::database::init_test_server("exam_answer_race").await;995+ let (db, _leases) = crate::database::init_test_db().await;
1002- // Hold the delete open for a full second after the row is gone, while
1003- // its cascade still has to run.
1004- db.query(
1005- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1006- THEN { SLEEP 1s; };",
1007- )
1008- .await
1009- .unwrap()
1010- .check()
1011- .unwrap();
1012 996
1013 let (mut answers, mut swept) = (0, 0);997 let (mut answers, mut swept) = (0, 0);
1014- for round in 0..4 {998+ for round in 0..8 {
1015 let exam = published(&db).await;999 let exam = published(&db).await;
1016 let question = question_on(&exam, &db).await;1000 let question = question_on(&exam, &db).await;
1017 let id = exam.get_id().clone();1001 let id = exam.get_id().clone();
1018- let student = UserId::from_key(&format!("stu{round}"));1002+ let student = a_person(&db, "student", "student").await;
1019 // The stored choice ids are minted by the create, not the ones the1003 // The stored choice ids are minted by the create, not the ones the
1020 // spec asked for — an answer must name one of *those*.1004 // spec asked for — an answer must name one of *those*.
1021 let pick = question.get_choices().unwrap()[1]1005 let pick = question.get_choices().unwrap()[1]
@@ -1023,21 +1007,26 @@ mod tests {
1023 .as_str()1007 .as_str()
1024 .to_string();1008 .to_string();
1025 1009
1010+ // Delete and save released together: both write the exam row, so
1011+ // Postgres serializes them and refuses whichever lost.
1012+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
1026 let drop_it = {1013 let drop_it = {
1027- let db = db.clone();1014+ let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone());
1028- tokio::spawn(async move { delete(&db, exam).await })1015+ tokio::spawn(async move {
1016+ gate.wait().await;
1017+ delete(&db, exam).await
1018+ })
1029 };1019 };
1030- // The save starts inside the held window — the exam row is gone but
1031- // uncommitted, which is exactly what an exam read believes.
1032- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1033 let child = {1020 let child = {
1034- let (db, question, student) = (db.clone(), question.clone(), student.clone());1021+ let (db, question, student, pick, gate) =
1022+ (db.clone(), question.clone(), student.clone(), pick, gate);
1035 tokio::spawn(async move {1023 tokio::spawn(async move {
1024+ gate.wait().await;
1036 exam_answer::save(&db, &question, &student, 1, Some(pick), None).await1025 exam_answer::save(&db, &question, &student, 1, Some(pick), None).await
1037 })1026 })
1038 };1027 };
1039 let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());1028 let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1040- // A 404 for the save, or a NotFound for the delete, is a correct1029+ // A 404 for the save, or a refusal for the delete, is a correct
1041 // answer — the only defect is stored state.1030 // answer — the only defect is stored state.
1042 assert!(1031 assert!(
1043 !matches!(child, Err(AppError::Db(_))),1032 !matches!(child, Err(AppError::Db(_))),
@@ -1052,7 +1041,7 @@ mod tests {
1052 panic!("round {round}: the delete reported success but the exam is still there");1041 panic!("round {round}: the delete reported success but the exam is still there");
1053 }1042 }
1054 }1043 }
1055- eprintln!("Exam::delete raced by an answer save: {swept}/4 rounds deleted the exam");1044+ eprintln!("Exam::delete raced by an answer save: {swept}/8 rounds deleted the exam");
1056 assert!(1045 assert!(
1057 swept > 0,1046 swept > 0,
1058 "no round ever deleted the exam, so the window was never reached"1047 "no round ever deleted the exam, so the window was never reached"
@@ -1068,28 +1057,15 @@ mod tests {
1068 /// again, hanging off an exam nobody could ever see. The freeze gate is a1057 /// again, hanging off an exam nobody could ever see. The freeze gate is a
1069 /// *read* of `exam_attempt` and never survived this window;1058 /// *read* of `exam_attempt` and never survived this window;
1070 /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row too.1059 /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row too.
1071- ///
1072- /// Same seam, same `#[ignore]`, same reason as the answer twin above: the
1073- /// subject *is* the store's conflict detection, which the in-memory engine
1074- /// does not have.
1075 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]1060 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1076- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1077 async fn a_question_written_inside_a_delete_never_outlives_the_exam() {1061 async fn a_question_written_inside_a_delete_never_outlives_the_exam() {
1078 use crate::domain::exam_question::{1062 use crate::domain::exam_question::{
1079 ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,1063 ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
1080 };1064 };
1081- let (db, _serialized) = crate::database::init_test_server("exam_question_race").await;1065+ let (db, _leases) = crate::database::init_test_db().await;
1082- db.query(
1083- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1084- THEN { SLEEP 1s; };",
1085- )
1086- .await
1087- .unwrap()
1088- .check()
1089- .unwrap();
1090 1066
1091 let (mut questions, mut swept, mut stuck) = (0, 0, 0);1067 let (mut questions, mut swept, mut stuck) = (0, 0, 0);
1092- for round in 0..4 {1068+ for round in 0..8 {
1093 let exam = published(&db).await;1069 let exam = published(&db).await;
1094 let id = exam.get_id().clone();1070 let id = exam.get_id().clone();
1095 let subject = crate::db::subject::create(1071 let subject = crate::db::subject::create(
@@ -1101,13 +1077,18 @@ mod tests {
1101 .await1077 .await
1102 .unwrap();1078 .unwrap();
1103 1079
1080+ // Delete and create released together: both write the exam row, so
1081+ // Postgres serializes them and refuses whichever lost.
1082+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
1104 let drop_it = {1083 let drop_it = {
1105- let db = db.clone();1084+ let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone());
1106- tokio::spawn(async move { delete(&db, exam).await })1085+ tokio::spawn(async move {
1086+ gate.wait().await;
1087+ delete(&db, exam).await
1088+ })
1107 };1089 };
1108- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1109 let child = {1090 let child = {
1110- let (db, exam_id, on) = (db.clone(), id.clone(), subject.get_id().clone());1091+ let (db, exam_id, on, gate) = (db.clone(), id.clone(), subject.get_id().clone(), gate);
1111 tokio::spawn(async move {1092 tokio::spawn(async move {
1112 let spec = QuestionSpec::try_new(1093 let spec = QuestionSpec::try_new(
1113 QuestionKind::try_new("choice").unwrap(),1094 QuestionKind::try_new("choice").unwrap(),
@@ -1167,7 +1148,7 @@ mod tests {
1167 panic!("round {round}: the delete reported success but the exam is still there");1148 panic!("round {round}: the delete reported success but the exam is still there");
1168 }1149 }
1169 }1150 }
1170- eprintln!("Exam::delete raced by a question write: {swept}/4 rounds deleted the exam");1151+ eprintln!("Exam::delete raced by a question write: {swept}/8 rounds deleted the exam");
1171 assert!(1152 assert!(
1172 swept > 0,1153 swept > 0,
1173 "no round ever deleted the exam, so the window was never reached"1154 "no round ever deleted the exam, so the window was never reached"
@@ -1177,37 +1158,35 @@ mod tests {
1177 }1158 }
1178 1159
1179 /// The student's half of the same picture problem: a drawing is a bare1160 /// The student's half of the same picture problem: a drawing is a bare
1180- /// `UPSERT` — the exact pre-fix shape of [`crate::db::exam_answer::save`] — so it kept1161+ /// upsert — the exact pre-fix shape of [`crate::db::exam_answer::save`] — so it kept
1181- /// the hole the text answer just lost, blob and all.1162+ /// the hole the text answer just lost, blob and all. It now rides the same
1163+ /// exam-row write the answer does.
1182 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]1164 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1183- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1184 async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() {1165 async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() {
1185 use crate::domain::answer_image::AnswerImage;1166 use crate::domain::answer_image::AnswerImage;
1186 use crate::domain::note_file::FileContentType;1167 use crate::domain::note_file::FileContentType;
1187- let (db, _serialized) = crate::database::init_test_server("answer_image_race").await;1168+ let (db, _leases) = crate::database::init_test_db().await;
1188- db.query(
1189- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1190- THEN { SLEEP 1s; };",
1191- )
1192- .await
1193- .unwrap()
1194- .check()
1195- .unwrap();
1196 1169
1197 let (mut drawings, mut swept) = (0, 0);1170 let (mut drawings, mut swept) = (0, 0);
1198- for round in 0..4 {1171+ for round in 0..8 {
1199 let exam = published(&db).await;1172 let exam = published(&db).await;
1200 let question = question_on(&exam, &db).await;1173 let question = question_on(&exam, &db).await;
1201 let id = exam.get_id().clone();1174 let id = exam.get_id().clone();
1202- let student = UserId::from_key(&format!("stu{round}"));1175+ let student = a_person(&db, "student", "student").await;
1203 1176
1177+ // Delete and upsert released together: both write the exam row, so
1178+ // Postgres serializes them and refuses whichever lost.
1179+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
1204 let drop_it = {1180 let drop_it = {
1205- let db = db.clone();1181+ let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone());
1206- tokio::spawn(async move { delete(&db, exam).await })1182+ tokio::spawn(async move {
1183+ gate.wait().await;
1184+ delete(&db, exam).await
1185+ })
1207 };1186 };
1208- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1209 let child = {1187 let child = {
1210- let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone());1188+ let (db, exam_id, on, student, gate) =
1189+ (db.clone(), id.clone(), question.get_id().clone(), student.clone(), gate);
1211 tokio::spawn(async move {1190 tokio::spawn(async move {
1212 let image = AnswerImage::new(1191 let image = AnswerImage::new(
1213 &exam_id,1192 &exam_id,
@@ -1236,7 +1215,7 @@ mod tests {
1236 panic!("round {round}: the delete reported success but the exam is still there");1215 panic!("round {round}: the delete reported success but the exam is still there");
1237 }1216 }
1238 }1217 }
1239- eprintln!("Exam::delete raced by a drawing write: {swept}/4 rounds deleted the exam");1218+ eprintln!("Exam::delete raced by a drawing write: {swept}/8 rounds deleted the exam");
1240 assert!(1219 assert!(
1241 swept > 0,1220 swept > 0,
1242 "no round ever deleted the exam, so the window was never reached"1221 "no round ever deleted the exam, so the window was never reached"
@@ -1247,36 +1226,33 @@ mod tests {
1247 /// A picture is written through the same freeze gate as the question it1226 /// A picture is written through the same freeze gate as the question it
1248 /// hangs on, so it had the same hole — and one the row count does not even1227 /// hangs on, so it had the same hole — and one the row count does not even
1249 /// show: `delete_exam` collects the blob names to unlink *before* it calls1228 /// show: `delete_exam` collects the blob names to unlink *before* it calls
1250- /// [\`crate::db::exam::delete\`], so an image row landing after that snapshot strands1229+ /// [`crate::db::exam::delete`], so an image row landing after that snapshot strands
1251- /// its bytes on disk forever as well.1230+ /// its bytes on disk forever as well. It now rides the same exam-row write
1231+ /// the question does.
1252 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]1232 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1253- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1254 async fn a_picture_written_inside_a_delete_never_outlives_the_exam() {1233 async fn a_picture_written_inside_a_delete_never_outlives_the_exam() {
1255 use crate::domain::note_file::FileContentType;1234 use crate::domain::note_file::FileContentType;
1256 use crate::domain::question_image::QuestionImage;1235 use crate::domain::question_image::QuestionImage;
1257- let (db, _serialized) = crate::database::init_test_server("question_image_race").await;1236+ let (db, _leases) = crate::database::init_test_db().await;
1258- db.query(
1259- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1260- THEN { SLEEP 1s; };",
1261- )
1262- .await
1263- .unwrap()
1264- .check()
1265- .unwrap();
1266 1237
1267 let (mut images, mut swept) = (0, 0);1238 let (mut images, mut swept) = (0, 0);
1268- for round in 0..4 {1239+ for round in 0..8 {
1269 let exam = published(&db).await;1240 let exam = published(&db).await;
1270 let question = question_on(&exam, &db).await;1241 let question = question_on(&exam, &db).await;
1271 let id = exam.get_id().clone();1242 let id = exam.get_id().clone();
1272 1243
1244+ // Delete and upsert released together: both write the exam row, so
1245+ // Postgres serializes them and refuses whichever lost.
1246+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
1273 let drop_it = {1247 let drop_it = {
1274- let db = db.clone();1248+ let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone());
1275- tokio::spawn(async move { delete(&db, exam).await })1249+ tokio::spawn(async move {
1250+ gate.wait().await;
1251+ delete(&db, exam).await
1252+ })
1276 };1253 };
1277- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1278 let child = {1254 let child = {
1279- let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone());1255+ let (db, exam_id, on, gate) = (db.clone(), id.clone(), question.get_id().clone(), gate);
1280 tokio::spawn(async move {1256 tokio::spawn(async move {
1281 let image = QuestionImage::new(1257 let image = QuestionImage::new(
1282 &exam_id,1258 &exam_id,
@@ -1304,7 +1280,7 @@ mod tests {
1304 panic!("round {round}: the delete reported success but the exam is still there");1280 panic!("round {round}: the delete reported success but the exam is still there");
1305 }1281 }
1306 }1282 }
1307- eprintln!("Exam::delete raced by a picture write: {swept}/4 rounds deleted the exam");1283+ eprintln!("Exam::delete raced by a picture write: {swept}/8 rounds deleted the exam");
1308 assert!(1284 assert!(
1309 swept > 0,1285 swept > 0,
1310 "no round ever deleted the exam, so the window was never reached"1286 "no round ever deleted the exam, so the window was never reached"
src/db/exam_answer.rsmodified+20 -13
@@ -283,7 +283,7 @@ mod tests {
283 }283 }
284 284
285 fn student() -> UserId {285 fn student() -> UserId {
286- UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA")286+ UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa")
287 }287 }
288 288
289 /// The bite test for the exam-row touch in [`save`]: it exists289 /// The bite test for the exam-row touch in [`save`]: it exists
@@ -298,7 +298,17 @@ mod tests {
298 use crate::domain::exam::{298 use crate::domain::exam::{
299 ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,299 ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
300 };300 };
301- let db = crate::database::init_mem().await.unwrap();301+ let (db, _leases) = crate::database::init_test_db().await;
302+ // The student is a foreign key now: a real row under the fixture's
303+ // fixed key.
304+ sqlx::query(
305+ "INSERT INTO app_user (id, username, password_hash) \
306+ VALUES ($1, 'aaaa-fixture', 'x')",
307+ )
308+ .bind(student().uuid())
309+ .execute(&db)
310+ .await
311+ .unwrap();
302 let kinds = crate::domain::settings::Settings::defaults()312 let kinds = crate::domain::settings::Settings::defaults()
303 .get_exam_kinds()313 .get_exam_kinds()
304 .to_vec();314 .to_vec();
@@ -318,14 +328,12 @@ mod tests {
318 .await328 .await
319 .unwrap();329 .unwrap();
320 let stored = async |db: &Database| -> Option<i64> {330 let stored = async |db: &Database| -> Option<i64> {
321- let mut result = db331+ sqlx::query_scalar::<_, i64>("SELECT result_count FROM exam WHERE id = $1")
322- .query("SELECT VALUE result_count FROM ONLY $ex")332+ .bind(exam.get_id().uuid())
323- .bind(("ex", exam.get_id().record()))333+ .fetch_optional(db)
324 .await334 .await
325 .unwrap()335 .unwrap()
326- .check()336+ .flatten()
327- .unwrap();
328- result.take::<Option<i64>>(0).unwrap()
329 };337 };
330 let question = choice_question(exam.get_id(), 10, 1);338 let question = choice_question(exam.get_id(), 10, 1);
331 let pick = choice_id(&question, 1).as_str().to_string();339 let pick = choice_id(&question, 1).as_str().to_string();
@@ -342,11 +350,10 @@ mod tests {
342 );350 );
343 351
344 // …and a counter that marks have moved is put back at its own value.352 // …and a counter that marks have moved is put back at its own value.
345- db.query("UPDATE $ex SET result_count = 7")353+ sqlx::query("UPDATE exam SET result_count = 7 WHERE id = $1")
346- .bind(("ex", exam.get_id().record()))354+ .bind(exam.get_id().uuid())
355+ .execute(&db)
347 .await356 .await
348- .unwrap()
349- .check()
350 .unwrap();357 .unwrap();
351 save(&db, &question, &student(), 2, Some(pick), None)358 save(&db, &question, &student(), 2, Some(pick), None)
352 .await359 .await
@@ -354,7 +361,7 @@ mod tests {
354 assert_eq!(stored(&db).await, Some(7), "the touch moved a real count");361 assert_eq!(stored(&db).await, Some(7), "the touch moved a real count");
355 362
356 // The gate that makes the touch worth having: no exam, no answer.363 // The gate that makes the touch worth having: no exam, no answer.
357- let orphan = choice_question(&ExamId::from_key("01NOSUCHEXAMAAAAAAAAAAAAAA"), 10, 0);364+ let orphan = choice_question(&ExamId::from_key("019732e3-7b00-7000-8000-00000000e0a0"), 10, 0);
358 let pick = choice_id(&orphan, 0).as_str().to_string();365 let pick = choice_id(&orphan, 0).as_str().to_string();
359 let refused = save(&db, &orphan, &student(), 1, Some(pick), None).await;366 let refused = save(&db, &orphan, &student(), 1, Some(pick), None).await;
360 assert!(367 assert!(
src/db/exam_attempt.rsmodified+10 -10
@@ -377,7 +377,7 @@ pub async fn create(
377 #[cfg(test)]377 #[cfg(test)]
378 mod tests {378 mod tests {
379 use super::*;379 use super::*;
380- use crate::database::init_mem;380+ use crate::database::init_test_db;
381 use crate::domain::exam::{381 use crate::domain::exam::{
382 Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,382 Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
383 };383 };
@@ -389,7 +389,7 @@ mod tests {
389 /// An open exam with retakes allowed, plus one choice question — enough389 /// An open exam with retakes allowed, plus one choice question — enough
390 /// rows to exercise the attempt lifecycle without the HTTP layer.390 /// rows to exercise the attempt lifecycle without the HTTP layer.
391 async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) {391 async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) {
392- let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");392+ let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
393 let course = crate::db::course::a_test_course(db).await;393 let course = crate::db::course::a_test_course(db).await;
394 let kinds = Settings::defaults().get_exam_kinds().to_vec();394 let kinds = Settings::defaults().get_exam_kinds().to_vec();
395 let exam = crate::db::exam::create(395 let exam = crate::db::exam::create(
@@ -468,7 +468,7 @@ mod tests {
468 468
469 #[tokio::test]469 #[tokio::test]
470 async fn submitting_never_reverts_a_walk_out_that_raced_it() {470 async fn submitting_never_reverts_a_walk_out_that_raced_it() {
471- let db = init_mem().await.unwrap();471+ let (db, _leases) = init_test_db().await;
472 let (exam, _question) = open_exam_with_question(&db, 1).await;472 let (exam, _question) = open_exam_with_question(&db, 1).await;
473 let user = student(&db).await;473 let user = student(&db).await;
474 474
@@ -478,7 +478,7 @@ mod tests {
478 478
479 // The REST submit path reads the attempt, then checks the deadline and479 // The REST submit path reads the attempt, then checks the deadline and
480 // the already-finished guard — several awaits before it writes.480 // the already-finished guard — several awaits before it writes.
481- let stale = read(&db, attempt.get_id())481+ let stale = read(&db, &attempt.get_id())
482 .await482 .await
483 .unwrap()483 .unwrap()
484 .expect("attempt exists");484 .expect("attempt exists");
@@ -488,7 +488,7 @@ mod tests {
488 // clears it) — a field-scoped write to the same row.488 // clears it) — a field-scoped write to the same row.
489 set_left(489 set_left(
490 &db,490 &db,
491- read(&db, attempt.get_id())491+ read(&db, &attempt.get_id())
492 .await492 .await
493 .unwrap()493 .unwrap()
494 .expect("attempt exists"),494 .expect("attempt exists"),
@@ -503,7 +503,7 @@ mod tests {
503 let finished = finish(&db, stale).await.unwrap();503 let finished = finish(&db, stale).await.unwrap();
504 assert!(finished.get_finished_at().is_some());504 assert!(finished.get_finished_at().is_some());
505 505
506- let after = read(&db, attempt.get_id())506+ let after = read(&db, &attempt.get_id())
507 .await507 .await
508 .unwrap()508 .unwrap()
509 .expect("attempt still exists");509 .expect("attempt still exists");
@@ -516,7 +516,7 @@ mod tests {
516 516
517 #[tokio::test]517 #[tokio::test]
518 async fn stamping_left_never_reverts_a_submission() {518 async fn stamping_left_never_reverts_a_submission() {
519- let db = init_mem().await.unwrap();519+ let (db, _leases) = init_test_db().await;
520 let (exam, _question) = open_exam_with_question(&db, 1).await;520 let (exam, _question) = open_exam_with_question(&db, 1).await;
521 let user = student(&db).await;521 let user = student(&db).await;
522 522
@@ -528,14 +528,14 @@ mod tests {
528 528
529 // The exam-room teardown reads the attempt while it is still in529 // The exam-room teardown reads the attempt while it is still in
530 // progress (`stamp_left`'s read) — a snapshot with `finished_at` unset.530 // progress (`stamp_left`'s read) — a snapshot with `finished_at` unset.
531- let stale = read(&db, attempt.get_id())531+ let stale = read(&db, &attempt.get_id())
532 .await532 .await
533 .unwrap()533 .unwrap()
534 .expect("attempt exists");534 .expect("attempt exists");
535 assert!(stale.get_finished_at().is_none());535 assert!(stale.get_finished_at().is_none());
536 let finished = finish(536 let finished = finish(
537 &db,537 &db,
538- read(&db, attempt.get_id())538+ read(&db, &attempt.get_id())
539 .await539 .await
540 .unwrap()540 .unwrap()
541 .expect("attempt exists"),541 .expect("attempt exists"),
@@ -552,7 +552,7 @@ mod tests {
552 // finishing).552 // finishing).
553 set_left(&db, stale, Some(Timestamp::now())).await.unwrap();553 set_left(&db, stale, Some(Timestamp::now())).await.unwrap();
554 554
555- let after = read(&db, attempt.get_id())555+ let after = read(&db, &attempt.get_id())
556 .await556 .await
557 .unwrap()557 .unwrap()
558 .expect("attempt still exists");558 .expect("attempt still exists");
src/db/exam_question.rsmodified+37 -30
@@ -437,7 +437,7 @@ mod tests {
437 /// outlives the row it accounts for makes its subject undeletable forever.437 /// outlives the row it accounts for makes its subject undeletable forever.
438 mod counters {438 mod counters {
439 use super::*;439 use super::*;
440- use crate::database::init_mem;440+ use crate::database::init_test_db;
441 use crate::domain::exam::{441 use crate::domain::exam::{
442 Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,442 Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
443 };443 };
@@ -446,10 +446,21 @@ mod tests {
446 use crate::domain::user::UserId;446 use crate::domain::user::UserId;
447 447
448 async fn an_exam(db: &Database) -> Exam {448 async fn an_exam(db: &Database) -> Exam {
449+ // The creator is a foreign key now: a real `app_user` row under
450+ // the fixture's fixed key.
451+ let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
452+ sqlx::query(
453+ "INSERT INTO app_user (id, username, password_hash) \
454+ VALUES ($1, 'acdc-fixture', 'x')",
455+ )
456+ .bind(creator.uuid())
457+ .execute(db)
458+ .await
459+ .unwrap();
449 let kinds = Settings::defaults().get_exam_kinds().to_vec();460 let kinds = Settings::defaults().get_exam_kinds().to_vec();
450 crate::db::exam::create(461 crate::db::exam::create(
451 db,462 db,
452- &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"),463+ &creator,
453 &crate::db::course::a_test_course(db).await,464 &crate::db::course::a_test_course(db).await,
454 ExamTitle::try_new("practice").unwrap(),465 ExamTitle::try_new("practice").unwrap(),
455 ExamDescription::try_new("").unwrap(),466 ExamDescription::try_new("").unwrap(),
@@ -503,26 +514,22 @@ mod tests {
503 514
504 /// The stored `exam_question_count` on one subject, absent = zero.515 /// The stored `exam_question_count` on one subject, absent = zero.
505 async fn count_on(subject: &SubjectId, db: &Database) -> i64 {516 async fn count_on(subject: &SubjectId, db: &Database) -> i64 {
506- let mut result = db517+ sqlx::query_scalar::<_, i64>(
507- .query(format!(518+ "SELECT exam_question_count FROM subject WHERE id = $1",
508- "SELECT VALUE ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) FROM $sub"519+ )
509- ))520+ .bind(subject.uuid())
510- .bind(("sub", subject.record()))521+ .fetch_one(db)
511- .await522+ .await
512- .unwrap()523+ .unwrap()
513- .check()
514- .unwrap();
515- result
516- .take::<Vec<i64>>(0)
517- .unwrap()
518- .first()
519- .copied()
520- .unwrap_or(0)
521 }524 }
522 525
523 async fn rows(sql: &str, db: &Database) -> usize {526 async fn rows(sql: &str, db: &Database) -> usize {
524- let mut result = db.query(sql).await.unwrap().check().unwrap();527+ sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
525- result.take::<Vec<RecordId>>(0).unwrap().len()528+ "SELECT count(*) FROM ({sql}) AS t"
529+ )))
530+ .fetch_one(db)
531+ .await
532+ .unwrap() as usize
526 }533 }
527 534
528 /// The freeze outranks the counter move, on both paths — and because535 /// The freeze outranks the counter move, on both paths — and because
@@ -530,7 +537,7 @@ mod tests {
530 /// the counters read as if nothing ran.537 /// the counters read as if nothing ran.
531 #[tokio::test]538 #[tokio::test]
532 async fn a_frozen_exam_leaves_the_subject_counters_untouched() {539 async fn a_frozen_exam_leaves_the_subject_counters_untouched() {
533- let db = init_mem().await.unwrap();540+ let (db, _leases) = init_test_db().await;
534 let exam = an_exam(&db).await;541 let exam = an_exam(&db).await;
535 let (from, to) = (a_subject(&db).await, a_subject(&db).await);542 let (from, to) = (a_subject(&db).await, a_subject(&db).await);
536 let (from, to) = (from.get_id().clone(), to.get_id().clone());543 let (from, to) = (from.get_id().clone(), to.get_id().clone());
@@ -575,7 +582,7 @@ mod tests {
575 /// nor a count — least of all on a subject it would have to invent.582 /// nor a count — least of all on a subject it would have to invent.
576 #[tokio::test]583 #[tokio::test]
577 async fn a_create_on_a_dead_subject_writes_neither_row_nor_count() {584 async fn a_create_on_a_dead_subject_writes_neither_row_nor_count() {
578- let db = init_mem().await.unwrap();585+ let (db, _leases) = init_test_db().await;
579 let exam = an_exam(&db).await;586 let exam = an_exam(&db).await;
580 let subject = a_subject(&db).await;587 let subject = a_subject(&db).await;
581 let id = subject.get_id().clone();588 let id = subject.get_id().clone();
@@ -587,12 +594,12 @@ mod tests {
587 .expect_err("a subject that is gone must not be taggable");594 .expect_err("a subject that is gone must not be taggable");
588 assert!(error.to_string().contains("subject does not exist"));595 assert!(error.to_string().contains("subject does not exist"));
589 assert_eq!(596 assert_eq!(
590- rows("SELECT VALUE id FROM exam_question", &db).await,597+ rows("SELECT id FROM exam_question", &db).await,
591 0,598 0,
592 "a refused create may write no row"599 "a refused create may write no row"
593 );600 );
594 assert_eq!(601 assert_eq!(
595- rows("SELECT VALUE id FROM subject", &db).await,602+ rows("SELECT id FROM subject", &db).await,
596 0,603 0,
597 "…and least of all a count on a subject it just brought back"604 "…and least of all a count on a subject it just brought back"
598 );605 );
@@ -600,7 +607,7 @@ mod tests {
600 607
601 #[tokio::test]608 #[tokio::test]
602 async fn a_subject_move_moves_the_count() {609 async fn a_subject_move_moves_the_count() {
603- let db = init_mem().await.unwrap();610+ let (db, _leases) = init_test_db().await;
604 let exam = an_exam(&db).await;611 let exam = an_exam(&db).await;
605 let (from, to) = (a_subject(&db).await, a_subject(&db).await);612 let (from, to) = (a_subject(&db).await, a_subject(&db).await);
606 let (from, to) = (from.get_id().clone(), to.get_id().clone());613 let (from, to) = (from.get_id().clone(), to.get_id().clone());
@@ -614,7 +621,7 @@ mod tests {
614 621
615 #[tokio::test]622 #[tokio::test]
616 async fn a_move_to_a_dead_subject_leaves_everything_untouched() {623 async fn a_move_to_a_dead_subject_leaves_everything_untouched() {
617- let db = init_mem().await.unwrap();624+ let (db, _leases) = init_test_db().await;
618 let exam = an_exam(&db).await;625 let exam = an_exam(&db).await;
619 let from = a_subject(&db).await.get_id().clone();626 let from = a_subject(&db).await.get_id().clone();
620 let dead = a_subject(&db).await;627 let dead = a_subject(&db).await;
@@ -633,7 +640,7 @@ mod tests {
633 1,640 1,
634 "the release rolled back with the claim"641 "the release rolled back with the claim"
635 );642 );
636- assert_eq!(rows("SELECT VALUE id FROM subject", &db).await, 1);643+ assert_eq!(rows("SELECT id FROM subject", &db).await, 1);
637 }644 }
638 645
639 /// The double-claim guard. Both movers compute their claim and release646 /// The double-claim guard. Both movers compute their claim and release
@@ -649,7 +656,7 @@ mod tests {
649 /// assertion — the stale mover is happily applied.656 /// assertion — the stale mover is happily applied.
650 #[tokio::test]657 #[tokio::test]
651 async fn a_stale_mover_is_refused_and_claims_nothing() {658 async fn a_stale_mover_is_refused_and_claims_nothing() {
652- let db = init_mem().await.unwrap();659+ let (db, _leases) = init_test_db().await;
653 let exam = an_exam(&db).await;660 let exam = an_exam(&db).await;
654 let from = a_subject(&db).await.get_id().clone();661 let from = a_subject(&db).await.get_id().clone();
655 let to = a_subject(&db).await.get_id().clone();662 let to = a_subject(&db).await.get_id().clone();
@@ -685,7 +692,7 @@ mod tests {
685 /// on the first assertion — the re-state lands 200.692 /// on the first assertion — the re-state lands 200.
686 #[tokio::test]693 #[tokio::test]
687 async fn a_stale_re_stater_is_refused_and_reverts_nothing() {694 async fn a_stale_re_stater_is_refused_and_reverts_nothing() {
688- let db = init_mem().await.unwrap();695+ let (db, _leases) = init_test_db().await;
689 let exam = an_exam(&db).await;696 let exam = an_exam(&db).await;
690 let from = a_subject(&db).await.get_id().clone();697 let from = a_subject(&db).await.get_id().clone();
691 let to = a_subject(&db).await.get_id().clone();698 let to = a_subject(&db).await.get_id().clone();
@@ -715,7 +722,7 @@ mod tests {
715 /// re-stating the subject the row really holds passes it trivially.722 /// re-stating the subject the row really holds passes it trivially.
716 #[tokio::test]723 #[tokio::test]
717 async fn a_no_op_re_state_still_lands() {724 async fn a_no_op_re_state_still_lands() {
718- let db = init_mem().await.unwrap();725+ let (db, _leases) = init_test_db().await;
719 let exam = an_exam(&db).await;726 let exam = an_exam(&db).await;
720 let on = a_subject(&db).await.get_id().clone();727 let on = a_subject(&db).await.get_id().clone();
721 let question = a_question(&exam, &on, &db).await;728 let question = a_question(&exam, &on, &db).await;
@@ -740,7 +747,7 @@ mod tests {
740 /// not the stale-mover 409 — the two empty-`$row` cases stay apart.747 /// not the stale-mover 409 — the two empty-`$row` cases stay apart.
741 #[tokio::test]748 #[tokio::test]
742 async fn a_move_of_a_deleted_question_is_still_a_404() {749 async fn a_move_of_a_deleted_question_is_still_a_404() {
743- let db = init_mem().await.unwrap();750+ let (db, _leases) = init_test_db().await;
744 let exam = an_exam(&db).await;751 let exam = an_exam(&db).await;
745 let from = a_subject(&db).await.get_id().clone();752 let from = a_subject(&db).await.get_id().clone();
746 let to = a_subject(&db).await.get_id().clone();753 let to = a_subject(&db).await.get_id().clone();
src/db/fee_plan.rsmodified+1 -1
@@ -176,7 +176,7 @@ mod tests {
176 /// shape and the stored one agree. A past due date is legal on purpose.176 /// shape and the stored one agree. A past due date is legal on purpose.
177 #[tokio::test]177 #[tokio::test]
178 async fn installments_survive_a_round_trip_through_the_schema() {178 async fn installments_survive_a_round_trip_through_the_schema() {
179- let db = crate::database::init_mem().await.unwrap();179+ let (db, _leases) = crate::database::init_test_db().await;
180 let manager = UserId::from_key("mgr1");180 let manager = UserId::from_key("mgr1");
181 let installments = vec![181 let installments = vec![
182 Installment::new(182 Installment::new(
src/db/homework.rsmodified+42 -32
@@ -442,11 +442,15 @@ async fn ensure_no_orphans(
442 442
443 /// Delete the homework and cascade its submissions, their files, and its443 /// Delete the homework and cascade its submissions, their files, and its
444 /// results — one transaction, so a crash can't orphan a submission under a444 /// results — one transaction, so a crash can't orphan a submission under a
445-/// vanished homework. The submission file *blobs* are the web layer's to445+/// vanished homework. The cascade runs children-first (every FK here is
446-/// unlink: their names are returned (collected inside the transaction,446+/// `ON DELETE NO ACTION`): files, then submissions — whose `graded_by_result`
447-/// before the wipes — a file row inserted after an out-of-transaction447+/// stamp points at a result row, so they must be gone before it — then the
448-/// collection would be deleted here while its key was already gone from the448+/// results, then the homework. The submission file *blobs* are the web
449-/// list, stranding the blob) and removed after the rows are gone.449+/// layer's to unlink: their names are returned (collected inside the
450+/// transaction, before the wipes — a file row inserted after an
451+/// out-of-transaction collection would be deleted here while its key was
452+/// already gone from the list, stranding the blob) and removed after the
453+/// rows are gone.
450 pub async fn delete(454 pub async fn delete(
451 db: &Database,455 db: &Database,
452 homework: Homework,456 homework: Homework,
@@ -470,13 +474,13 @@ pub async fn delete(
470 .execute(&mut *tx)474 .execute(&mut *tx)
471 .await?;475 .await?;
472 sqlx::query!(476 sqlx::query!(
473- "DELETE FROM homework_result WHERE homework = $1",477+ "DELETE FROM homework_submission WHERE homework = $1",
474 homework.get_id().uuid()478 homework.get_id().uuid()
475 )479 )
476 .execute(&mut *tx)480 .execute(&mut *tx)
477 .await?;481 .await?;
478 sqlx::query!(482 sqlx::query!(
479- "DELETE FROM homework_submission WHERE homework = $1",483+ "DELETE FROM homework_result WHERE homework = $1",
480 homework.get_id().uuid()484 homework.get_id().uuid()
481 )485 )
482 .execute(&mut *tx)486 .execute(&mut *tx)
@@ -529,15 +533,27 @@ mod tests {
529 }533 }
530 534
531 async fn homework_on(subject: &SubjectId, db: &Database) -> Homework {535 async fn homework_on(subject: &SubjectId, db: &Database) -> Homework {
536+ // The course and the teacher are foreign keys now: a real course row
537+ // (the subject's own fixture path mints one) and a real teacher.
538+ let teacher = UserId::generate();
539+ sqlx::query(
540+ "INSERT INTO app_user (id, username, password_hash, role) \
541+ VALUES ($1, $2, 'x', 'teacher')",
542+ )
543+ .bind(teacher.uuid())
544+ .bind(format!("homework-fixture-{}", &teacher.key()[..8]))
545+ .execute(db)
546+ .await
547+ .unwrap();
532 create(548 create(
533 db,549 db,
534- &CourseId::from_key("course"),550+ &crate::db::course::a_test_course(db).await,
535 subject,551 subject,
536 HomeworkTitle::try_new("essay").unwrap(),552 HomeworkTitle::try_new("essay").unwrap(),
537 None,553 None,
538 Timestamp::from_millis(1),554 Timestamp::from_millis(1),
539 None,555 None,
540- &UserId::from_key("teacher"),556+ &teacher,
541 )557 )
542 .await558 .await
543 .unwrap()559 .unwrap()
@@ -545,27 +561,21 @@ mod tests {
545 561
546 /// The stored `homework_count` on one subject, absent counting as zero.562 /// The stored `homework_count` on one subject, absent counting as zero.
547 async fn count_on(subject: &SubjectId, db: &Database) -> i64 {563 async fn count_on(subject: &SubjectId, db: &Database) -> i64 {
548- let mut result = db564+ sqlx::query_scalar::<_, i64>("SELECT homework_count FROM subject WHERE id = $1")
549- .query(format!(565+ .bind(subject.uuid())
550- "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM $sub"566+ .fetch_one(db)
551- ))
552- .bind(("sub", subject.record()))
553 .await567 .await
554 .unwrap()568 .unwrap()
555- .check()
556- .unwrap();
557- result
558- .take::<Vec<i64>>(0)
559- .unwrap()
560- .first()
561- .copied()
562- .unwrap_or(0)
563 }569 }
564 570
565 /// How many rows `sql` selects ids for.571 /// How many rows `sql` selects ids for.
566 async fn rows(sql: &str, db: &Database) -> usize {572 async fn rows(sql: &str, db: &Database) -> usize {
567- let mut result = db.query(sql).await.unwrap().check().unwrap();573+ sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
568- result.take::<Vec<RecordId>>(0).unwrap().len()574+ "SELECT count(*) FROM ({sql}) AS t"
575+ )))
576+ .fetch_one(db)
577+ .await
578+ .unwrap() as usize
569 }579 }
570 580
571 /// The invariant on the create path: the claim and the row it accounts for581 /// The invariant on the create path: the claim and the row it accounts for
@@ -574,7 +584,7 @@ mod tests {
574 /// guard reads that count, so a stray one makes it undeletable forever).584 /// guard reads that count, so a stray one makes it undeletable forever).
575 #[tokio::test]585 #[tokio::test]
576 async fn a_refused_create_writes_neither_row_nor_count() {586 async fn a_refused_create_writes_neither_row_nor_count() {
577- let db = crate::database::init_mem().await.unwrap();587+ let (db, _leases) = crate::database::init_test_db().await;
578 let subject = a_subject("algebra", &db).await;588 let subject = a_subject("algebra", &db).await;
579 let id = subject.get_id().clone();589 let id = subject.get_id().clone();
580 crate::db::subject::delete(&db, subject).await.unwrap();590 crate::db::subject::delete(&db, subject).await.unwrap();
@@ -593,12 +603,12 @@ mod tests {
593 .expect_err("a subject that is gone must not be taggable");603 .expect_err("a subject that is gone must not be taggable");
594 assert!(error.to_string().contains("subject does not exist"));604 assert!(error.to_string().contains("subject does not exist"));
595 assert_eq!(605 assert_eq!(
596- rows("SELECT VALUE id FROM homework", &db).await,606+ rows("SELECT id FROM homework", &db).await,
597 0,607 0,
598 "a refused create may write no row"608 "a refused create may write no row"
599 );609 );
600 assert_eq!(610 assert_eq!(
601- rows("SELECT VALUE id FROM subject", &db).await,611+ rows("SELECT id FROM subject", &db).await,
602 0,612 0,
603 "…and least of all a count on a subject it just brought back"613 "…and least of all a count on a subject it just brought back"
604 );614 );
@@ -608,7 +618,7 @@ mod tests {
608 /// claim and the old one's release with the link itself.618 /// claim and the old one's release with the link itself.
609 #[tokio::test]619 #[tokio::test]
610 async fn a_subject_move_moves_the_count() {620 async fn a_subject_move_moves_the_count() {
611- let db = crate::database::init_mem().await.unwrap();621+ let (db, _leases) = crate::database::init_test_db().await;
612 let from = a_subject("algebra", &db).await;622 let from = a_subject("algebra", &db).await;
613 let to = a_subject("geometry", &db).await;623 let to = a_subject("geometry", &db).await;
614 let homework = homework_on(from.get_id(), &db).await;624 let homework = homework_on(from.get_id(), &db).await;
@@ -647,7 +657,7 @@ mod tests {
647 /// keeps its tag and both counters read as if nothing ran.657 /// keeps its tag and both counters read as if nothing ran.
648 #[tokio::test]658 #[tokio::test]
649 async fn a_move_to_a_dead_subject_leaves_everything_untouched() {659 async fn a_move_to_a_dead_subject_leaves_everything_untouched() {
650- let db = crate::database::init_mem().await.unwrap();660+ let (db, _leases) = crate::database::init_test_db().await;
651 let from = a_subject("algebra", &db).await;661 let from = a_subject("algebra", &db).await;
652 let dead = a_subject("geometry", &db).await;662 let dead = a_subject("geometry", &db).await;
653 let gone = dead.get_id().clone();663 let gone = dead.get_id().clone();
@@ -674,7 +684,7 @@ mod tests {
674 "the release rolled back with the claim"684 "the release rolled back with the claim"
675 );685 );
676 assert_eq!(686 assert_eq!(
677- rows("SELECT VALUE id FROM subject", &db).await,687+ rows("SELECT id FROM subject", &db).await,
678 1,688 1,
679 "the dead subject was not brought back by a count"689 "the dead subject was not brought back by a count"
680 );690 );
@@ -690,7 +700,7 @@ mod tests {
690 /// outright, and the counts must read as if it never ran.700 /// outright, and the counts must read as if it never ran.
691 #[tokio::test]701 #[tokio::test]
692 async fn a_stale_mover_is_refused_and_claims_nothing() {702 async fn a_stale_mover_is_refused_and_claims_nothing() {
693- let db = crate::database::init_mem().await.unwrap();703+ let (db, _leases) = crate::database::init_test_db().await;
694 let from = a_subject("algebra", &db).await;704 let from = a_subject("algebra", &db).await;
695 let to = a_subject("geometry", &db).await;705 let to = a_subject("geometry", &db).await;
696 let other = a_subject("calculus", &db).await;706 let other = a_subject("calculus", &db).await;
@@ -744,7 +754,7 @@ mod tests {
744 /// *carrying* the column instead, which is why this is refused.754 /// *carrying* the column instead, which is why this is refused.
745 #[tokio::test]755 #[tokio::test]
746 async fn a_stale_re_stater_is_refused_and_reverts_nothing() {756 async fn a_stale_re_stater_is_refused_and_reverts_nothing() {
747- let db = crate::database::init_mem().await.unwrap();757+ let (db, _leases) = crate::database::init_test_db().await;
748 let from = a_subject("algebra", &db).await;758 let from = a_subject("algebra", &db).await;
749 let to = a_subject("geometry", &db).await;759 let to = a_subject("geometry", &db).await;
750 let homework = homework_on(from.get_id(), &db).await;760 let homework = homework_on(from.get_id(), &db).await;
src/db/homework_file.rsmodified+38 -19
@@ -301,12 +301,36 @@ mod tests {
301 None,301 None,
302 crate::domain::timestamp::Timestamp::from_millis(1),302 crate::domain::timestamp::Timestamp::from_millis(1),
303 None,303 None,
304- &UserId::from_key("teacher"),304+ &a_teacher(db).await,
305 )305 )
306 .await306 .await
307 .unwrap()307 .unwrap()
308 }308 }
309 309
310+ /// A real `app_user` row: submitters are foreign keys too.
311+ async fn a_student(db: &Database) -> UserId {
312+ let user = UserId::generate();
313+ sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'student')")
314+ .bind(user.uuid())
315+ .bind(format!("s-{}", &user.key()[..8]))
316+ .execute(db)
317+ .await
318+ .unwrap();
319+ user
320+ }
321+
322+ /// A real `app_user` row: creators and submitters are foreign keys now.
323+ async fn a_teacher(db: &Database) -> UserId {
324+ let user = UserId::generate();
325+ sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'teacher')")
326+ .bind(user.uuid())
327+ .bind(format!("t-{}", &user.key()[..8]))
328+ .execute(db)
329+ .await
330+ .unwrap();
331+ user
332+ }
333+
310 fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile {334 fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile {
311 HomeworkFile::new(335 HomeworkFile::new(
312 submission,336 submission,
@@ -319,32 +343,27 @@ mod tests {
319 /// The counter as *stored* — the only witness that the seat and the row343 /// The counter as *stored* — the only witness that the seat and the row
320 /// moved together, since every other read counts the rows themselves.344 /// moved together, since every other read counts the rows themselves.
321 async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 {345 async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 {
322- db.query("SELECT VALUE file_count FROM $sub")346+ sqlx::query("SELECT file_count FROM homework_submission WHERE id = $1")
323- .bind(("sub", submission.record()))347+ .bind(submission.uuid())
348+ .fetch_one(db)
324 .await349 .await
325 .unwrap()350 .unwrap()
326- .take::<Vec<i64>>(0)351+ .try_get::<i64, _>(0)
327 .unwrap()352 .unwrap()
328- .into_iter()
329- .next()
330- .unwrap_or(0)
331 }353 }
332 #[tokio::test]354 #[tokio::test]
333 async fn rows_scope_to_their_submission_gc_and_cap() {355 async fn rows_scope_to_their_submission_gc_and_cap() {
334- let db = crate::database::init_mem().await.unwrap();356+ let (db, _leases) = crate::database::init_test_db().await;
335 let hw = a_homework(&db).await;357 let hw = a_homework(&db).await;
336 let homework = hw.get_id().clone();358 let homework = hw.get_id().clone();
337- let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");359+ let user = a_student(&db).await;
338 // A real submission row, so the GC join through it resolves.360 // A real submission row, so the GC join through it resolves.
339- let submission = crate::db::homework_submission::upsert(&db, &hw, &user, None)361+ let (submission, _) = crate::db::homework_submission::upsert(&db, &hw, &user, None, false)
340 .await362 .await
341 .unwrap()363 .unwrap()
342 .unwrap();364 .unwrap();
343 let sub_a = submission.get_id().clone();365 let sub_a = submission.get_id().clone();
344- let sub_b = HomeworkSubmissionId::composite(366+ let sub_b = HomeworkSubmissionId::generate();
345- &homework,
346- &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"),
347- );
348 367
349 let stored = insert(&db, a_file(&sub_a)).await.unwrap().unwrap();368 let stored = insert(&db, a_file(&sub_a)).await.unwrap().unwrap();
350 // Readable under its own submission, invisible under another.369 // Readable under its own submission, invisible under another.
@@ -380,7 +399,7 @@ mod tests {
380 read_in_homework(399 read_in_homework(
381 &db,400 &db,
382 stored.get_id(),401 stored.get_id(),
383- &HomeworkId::from_key("01TESTHWBBBBBBBBBBBBBBBBBB"),402+ &HomeworkId::from_key("019732e3-7b00-7000-8000-00000000ebbe"),
384 )403 )
385 .await404 .await
386 .unwrap()405 .unwrap()
@@ -422,11 +441,11 @@ mod tests {
422 use crate::db::homework_result;441 use crate::db::homework_result;
423 use crate::domain::homework_result::HomeworkStatus;442 use crate::domain::homework_result::HomeworkStatus;
424 443
425- let db = crate::database::init_mem().await.unwrap();444+ let (db, _leases) = crate::database::init_test_db().await;
426 let hw = a_homework(&db).await;445 let hw = a_homework(&db).await;
427 let homework = hw.get_id().clone();446 let homework = hw.get_id().clone();
428- let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");447+ let user = a_student(&db).await;
429- let submission = crate::db::homework_submission::upsert(&db, &hw, &user, None)448+ let (submission, _) = crate::db::homework_submission::upsert(&db, &hw, &user, None, false)
430 .await449 .await
431 .unwrap()450 .unwrap()
432 .unwrap();451 .unwrap();
@@ -439,7 +458,7 @@ mod tests {
439 &user,458 &user,
440 HomeworkStatus::try_new("done").unwrap(),459 HomeworkStatus::try_new("done").unwrap(),
441 None,460 None,
442- &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"),461+ &UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"),
443 )462 )
444 .await463 .await
445 .unwrap();464 .unwrap();
src/db/homework_result.rsmodified+60 -42
@@ -241,6 +241,21 @@ pub async fn remove(
241 if alive.is_none() {241 if alive.is_none() {
242 return Ok(None);242 return Ok(None);
243 }243 }
244+ // The stamp clears *before* the delete: the submission's
245+ // `graded_by_result` FK points at the grade row (`NO ACTION`), so the
246+ // delete must not run while it stands. The subselect scopes the clear
247+ // to *this* pair's grade id — it can never wipe a stamp a concurrent
248+ // re-grade has just written (none can interleave: the homework row is
249+ // locked above).
250+ sqlx::query!(
251+ r#"UPDATE homework_submission SET graded_by_result = NULL
252+ WHERE homework = $1 AND app_user = $2 AND graded_by_result IN (
253+ SELECT id FROM homework_result WHERE homework = $1 AND app_user = $2)"#,
254+ homework.uuid(),
255+ user.uuid()
256+ )
257+ .execute(&mut *tx)
258+ .await?;
244 let gone = sqlx::query!(259 let gone = sqlx::query!(
245 r#"DELETE FROM homework_result WHERE homework = $1 AND app_user = $2260 r#"DELETE FROM homework_result WHERE homework = $1 AND app_user = $2
246 RETURNING id AS "id: HomeworkResultId",261 RETURNING id AS "id: HomeworkResultId",
@@ -258,15 +273,6 @@ pub async fn remove(
258 let Some(removed) = gone else {273 let Some(removed) = gone else {
259 return Ok(None);274 return Ok(None);
260 };275 };
261- sqlx::query!(
262- r#"UPDATE homework_submission SET graded_by_result = NULL
263- WHERE homework = $1 AND app_user = $2 AND graded_by_result = $3"#,
264- homework.uuid(),
265- user.uuid(),
266- removed.id.uuid()
267- )
268- .execute(&mut *tx)
269- .await?;
270 sqlx::query!(276 sqlx::query!(
271 "UPDATE app_user SET marks_given_total = GREATEST(marks_given_total - 1, 0) WHERE id = $1",277 "UPDATE app_user SET marks_given_total = GREATEST(marks_given_total - 1, 0) WHERE id = $1",
272 removed.graded_by.uuid()278 removed.graded_by.uuid()
@@ -325,10 +331,10 @@ mod tests {
325 331
326 #[tokio::test]332 #[tokio::test]
327 async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() {333 async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() {
328- let db = crate::database::init_mem().await.unwrap();334+ let (db, _leases) = crate::database::init_test_db().await;
329 let homework = a_homework(&db).await;335 let homework = a_homework(&db).await;
330- let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");336+ let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa");
331- let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");337+ let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
332 338
333 let first = grade(339 let first = grade(
334 &db,340 &db,
@@ -366,17 +372,27 @@ mod tests {
366 /// touched at all — a homework grade is not a homework submission.372 /// touched at all — a homework grade is not a homework submission.
367 #[tokio::test]373 #[tokio::test]
368 async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() {374 async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() {
369- let db = crate::database::init_mem().await.unwrap();375+ let (db, _leases) = crate::database::init_test_db().await;
370 let homework = a_homework(&db).await;376 let homework = a_homework(&db).await;
371- let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");377+ let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa");
372- let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");378+ let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
373 // `UPDATE` writes nothing to a user row that does not exist.379 // `UPDATE` writes nothing to a user row that does not exist.
374- db.query("CREATE $usr SET username = 't', password_hash = 'x'")380+ sqlx::query(
375- .bind(("usr", teacher.record()))381+ "INSERT INTO app_user (id, username, password_hash, role) \
376- .await382+ VALUES ($1, 't', 'x', 'teacher') ON CONFLICT (id) DO NOTHING",
377- .unwrap()383+ )
378- .check()384+ .bind(teacher.uuid())
379- .unwrap();385+ .execute(&db)
386+ .await
387+ .unwrap();
388+ sqlx::query(
389+ "INSERT INTO app_user (id, username, password_hash, role) \
390+ VALUES ($1, 'ali', 'x', 'student') ON CONFLICT (id) DO NOTHING",
391+ )
392+ .bind(user.uuid())
393+ .execute(&db)
394+ .await
395+ .unwrap();
380 396
381 for status in ["incomplete", "done"] {397 for status in ["incomplete", "done"] {
382 grade(398 grade(
@@ -403,16 +419,26 @@ mod tests {
403 /// mark given, with no exam, no mark and no submission behind them.419 /// mark given, with no exam, no mark and no submission behind them.
404 #[tokio::test]420 #[tokio::test]
405 async fn ungrading_gives_the_grader_credit_back() {421 async fn ungrading_gives_the_grader_credit_back() {
406- let db = crate::database::init_mem().await.unwrap();422+ let (db, _leases) = crate::database::init_test_db().await;
407 let homework = a_homework(&db).await;423 let homework = a_homework(&db).await;
408- let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");424+ let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa");
409- let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");425+ let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
410- db.query("CREATE $usr SET username = 't', password_hash = 'x'")426+ sqlx::query(
411- .bind(("usr", teacher.record()))427+ "INSERT INTO app_user (id, username, password_hash, role) \
412- .await428+ VALUES ($1, 't', 'x', 'teacher') ON CONFLICT (id) DO NOTHING",
413- .unwrap()429+ )
414- .check()430+ .bind(teacher.uuid())
415- .unwrap();431+ .execute(&db)
432+ .await
433+ .unwrap();
434+ sqlx::query(
435+ "INSERT INTO app_user (id, username, password_hash, role) \
436+ VALUES ($1, 'ali', 'x', 'student') ON CONFLICT (id) DO NOTHING",
437+ )
438+ .bind(user.uuid())
439+ .execute(&db)
440+ .await
441+ .unwrap();
416 442
417 for _ in 0..3 {443 for _ in 0..3 {
418 grade(444 grade(
@@ -439,20 +465,12 @@ mod tests {
439 }465 }
440 /// The grader's badge counter, re-read out of the store.466 /// The grader's badge counter, re-read out of the store.
441 async fn marks_given(user: &UserId, db: &Database) -> i64 {467 async fn marks_given(user: &UserId, db: &Database) -> i64 {
442- let mut result = db468+ sqlx::query("SELECT marks_given_total FROM app_user WHERE id = $1")
443- .query(format!(469+ .bind(user.uuid())
444- "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $usr"470+ .fetch_one(db)
445- ))
446- .bind(("usr", user.record()))
447 .await471 .await
448 .unwrap()472 .unwrap()
449- .check()473+ .try_get::<i64, _>(0)
450- .unwrap();
451- result
452- .take::<Vec<i64>>(0)
453 .unwrap()474 .unwrap()
454- .into_iter()
455- .next()
456- .unwrap_or(0)
457 }475 }
458 }476 }
src/db/homework_submission.rsmodified+95 -62
@@ -309,21 +309,30 @@ pub async fn delete(
309 .fetch_optional(&mut *tx)309 .fetch_optional(&mut *tx)
310 .await?310 .await?
311 .map(|row| row.due_at);311 .map(|row| row.due_at);
312- let gone = sqlx::query!(312+ // The gate runs as a lock-taking read, not a delete: the file rows
313- r#"DELETE FROM homework_submission313+ // must die BEFORE the submission row (their `submission` FK is
314+ // `NO ACTION`), and that wipe is only honest if this delete has
315+ // already won — so the open-not-frozen verdict and the row lock come
316+ // first, files second, the submission row last. A rival withdrawal
317+ // that beat us removed the row under its own lock; a grade that
318+ // stamped it holds the homework lock first — either way `None`, one
319+ // refusal as before.
320+ let target = sqlx::query!(
321+ r#"SELECT id AS "id: HomeworkSubmissionId",
322+ homework AS "homework: HomeworkId",
323+ app_user AS "user: UserId",
324+ text AS "text: SubmissionText",
325+ submitted_at AS "submitted_at: Timestamp",
326+ updated_at AS "updated_at: Timestamp",
327+ counted_on_time AS "counted_on_time: bool"
328+ FROM homework_submission
314 WHERE id = $1 AND graded_by_result IS NULL329 WHERE id = $1 AND graded_by_result IS NULL
315- RETURNING id AS "id: HomeworkSubmissionId",330+ FOR UPDATE"#,
316- homework AS "homework: HomeworkId",
317- app_user AS "user: UserId",
318- text AS "text: SubmissionText",
319- submitted_at AS "submitted_at: Timestamp",
320- updated_at AS "updated_at: Timestamp",
321- counted_on_time AS "counted_on_time: bool""#,
322 submission.get_id().uuid()331 submission.get_id().uuid()
323 )332 )
324 .fetch_optional(&mut *tx)333 .fetch_optional(&mut *tx)
325 .await?;334 .await?;
326- let Some(removed) = gone else {335+ let Some(removed) = target else {
327 // Frozen, or already withdrawn by a rival — one refusal, as336 // Frozen, or already withdrawn by a rival — one refusal, as
328 // before.337 // before.
329 return Ok(None);338 return Ok(None);
@@ -334,6 +343,12 @@ pub async fn delete(
334 )343 )
335 .execute(&mut *tx)344 .execute(&mut *tx)
336 .await?;345 .await?;
346+ sqlx::query!(
347+ "DELETE FROM homework_submission WHERE id = $1",
348+ removed.id.uuid()
349+ )
350+ .execute(&mut *tx)
351+ .await?;
337 let judged_on_time = due.map(|d| removed.submitted_at <= d).unwrap_or(false);352 let judged_on_time = due.map(|d| removed.submitted_at <= d).unwrap_or(false);
338 let on_time = i64::from(removed.counted_on_time.unwrap_or(judged_on_time));353 let on_time = i64::from(removed.counted_on_time.unwrap_or(judged_on_time));
339 sqlx::query!(354 sqlx::query!(
@@ -361,9 +376,8 @@ pub async fn delete(
361 #[cfg(test)]376 #[cfg(test)]
362 mod tests {377 mod tests {
363 use super::*;378 use super::*;
364- use crate::constant::{379+ use sqlx::Row as _;
365- HOMEWORK_ON_TIME_TOTAL_FIELD as ON_TIME, HOMEWORK_SUBMITTED_TOTAL_FIELD as SUBMITTED,380+
366- };
367 use crate::db::homework as homework_db;381 use crate::db::homework as homework_db;
368 use crate::domain::homework::HomeworkTitle;382 use crate::domain::homework::HomeworkTitle;
369 use crate::domain::subject::{SubjectDescription, SubjectName};383 use crate::domain::subject::{SubjectDescription, SubjectName};
@@ -436,19 +450,13 @@ mod tests {
436 /// The verdict `upsert` stored on the row — what `delete` debits off.450 /// The verdict `upsert` stored on the row — what `delete` debits off.
437 /// `None` is a row from before the column existed.451 /// `None` is a row from before the column existed.
438 async fn stored_verdict(id: &HomeworkSubmissionId, db: &Database) -> Option<bool> {452 async fn stored_verdict(id: &HomeworkSubmissionId, db: &Database) -> Option<bool> {
439- let mut result = db453+ let row = sqlx::query("SELECT counted_on_time FROM homework_submission WHERE id = $1")
440- .query("SELECT VALUE counted_on_time FROM $sub")454+ .bind(id.uuid())
441- .bind(("sub", id.record()))455+ .fetch_optional(db)
442 .await456 .await
443 .unwrap()457 .unwrap()
444- .check()458+ .expect("the submission row exists");
445- .unwrap();459+ row.try_get::<Option<bool>, _>(0).unwrap()
446- result
447- .take::<Vec<Option<bool>>>(0)
448- .unwrap()
449- .into_iter()
450- .flatten()
451- .next()
452 }460 }
453 461
454 /// The web layer's computed flag, exactly as `SubmissionResponse::new`462 /// The web layer's computed flag, exactly as `SubmissionResponse::new`
@@ -464,41 +472,42 @@ mod tests {
464 472
465 /// The two badge counters on a user row, absent counting as zero.473 /// The two badge counters on a user row, absent counting as zero.
466 async fn counters(user: &UserId, db: &Database) -> (i64, i64) {474 async fn counters(user: &UserId, db: &Database) -> (i64, i64) {
467- let mut result = db475+ let row = sqlx::query(
468- .query(format!(476+ "SELECT homework_submitted_total, homework_on_time_total \
469- "SELECT VALUE [({SUBMITTED} ?? 0), ({ON_TIME} ?? 0)] FROM $usr"477+ FROM app_user WHERE id = $1",
470- ))478+ )
471- .bind(("usr", user.record()))479+ .bind(user.uuid())
472- .await480+ .fetch_one(db)
473- .unwrap()481+ .await
474- .check()482+ .unwrap();
475- .unwrap();
476- let rows = result.take::<Vec<Vec<i64>>>(0).unwrap();
477- let row = rows.first().cloned().unwrap_or_default();
478 (483 (
479- row.first().copied().unwrap_or(0),484+ row.try_get::<i64, _>(0).unwrap(),
480- row.get(1).copied().unwrap_or(0),485+ row.try_get::<i64, _>(1).unwrap(),
481 )486 )
482 }487 }
483 488
484 #[tokio::test]489 #[tokio::test]
485 async fn resubmit_keeps_submitted_at_and_restamps_updated_at() {490 async fn resubmit_keeps_submitted_at_and_restamps_updated_at() {
486- let db = crate::database::init_mem().await.unwrap();491+ let (db, _leases) = crate::database::init_test_db().await;
487 let homework = a_homework(far_future(), &db).await;492 let homework = a_homework(far_future(), &db).await;
488 let user = a_student("ogrenci", &db).await;493 let user = a_student("ogrenci", &db).await;
489 494
490- let first = upsert(495+ let (first, _) = upsert(
491 &db,496 &db,
492 &homework,497 &homework,
493 &user,498 &user,
494 Some(SubmissionText::try_new("draft").unwrap()),499 Some(SubmissionText::try_new("draft").unwrap()),
500+ false,
495 )501 )
496 .await502 .await
497 .unwrap()503 .unwrap()
498 .unwrap();504 .unwrap();
499 // A re-submit lands on the same row: submitted_at (the first hand-in)505 // A re-submit lands on the same row: submitted_at (the first hand-in)
500 // pinned, updated_at moves forward, and the text can be cleared.506 // pinned, updated_at moves forward, and the text can be cleared.
501- let second = upsert(&db, &homework, &user, None).await.unwrap().unwrap();507+ let (second, _) = upsert(&db, &homework, &user, None, false)
508+ .await
509+ .unwrap()
510+ .unwrap();
502 // ... and it is one submission, not two: the edit moves no counter.511 // ... and it is one submission, not two: the edit moves no counter.
503 assert_eq!(counters(&user, &db).await, (1, 1));512 assert_eq!(counters(&user, &db).await, (1, 1));
504 assert_eq!(first.get_id(), second.get_id());513 assert_eq!(first.get_id(), second.get_id());
@@ -529,16 +538,16 @@ mod tests {
529 use crate::db::homework_result;538 use crate::db::homework_result;
530 use crate::domain::homework_result::HomeworkStatus;539 use crate::domain::homework_result::HomeworkStatus;
531 540
532- let db = crate::database::init_mem().await.unwrap();541+ let (db, _leases) = crate::database::init_test_db().await;
533 let homework = a_homework(far_future(), &db).await;542 let homework = a_homework(far_future(), &db).await;
534 let user = a_student("ogrenci", &db).await;543 let user = a_student("ogrenci", &db).await;
535- let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");544+ let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
536 let graded = |value| {545 let graded = |value| {
537 let text = SubmissionText::try_new(value).unwrap();546 let text = SubmissionText::try_new(value).unwrap();
538- upsert(&db, &homework, &user, Some(text))547+ upsert(&db, &homework, &user, Some(text), false)
539 };548 };
540 549
541- let version_a = graded("version A").await.unwrap().unwrap();550+ let (version_a, _) = graded("version A").await.unwrap().unwrap();
542 assert!(!is_graded(&db, version_a.get_id()).await.unwrap());551 assert!(!is_graded(&db, version_a.get_id()).await.unwrap());
543 552
544 assert_eq!(counters(&user, &db).await, (1, 1));553 assert_eq!(counters(&user, &db).await, (1, 1));
@@ -589,7 +598,7 @@ mod tests {
589 .await598 .await
590 .unwrap();599 .unwrap();
591 assert!(!is_graded(&db, version_a.get_id()).await.unwrap());600 assert!(!is_graded(&db, version_a.get_id()).await.unwrap());
592- let reopened = graded("version B").await.unwrap().unwrap();601+ let (reopened, _) = graded("version B").await.unwrap().unwrap();
593 assert_eq!(602 assert_eq!(
594 reopened.get_text().map(SubmissionText::as_str),603 reopened.get_text().map(SubmissionText::as_str),
595 Some("version B")604 Some("version B")
@@ -604,15 +613,16 @@ mod tests {
604 613
605 #[tokio::test]614 #[tokio::test]
606 async fn touch_moves_updated_at_but_not_submitted_at_or_text() {615 async fn touch_moves_updated_at_but_not_submitted_at_or_text() {
607- let db = crate::database::init_mem().await.unwrap();616+ let (db, _leases) = crate::database::init_test_db().await;
608 let homework = a_homework(far_future(), &db).await;617 let homework = a_homework(far_future(), &db).await;
609 let user = a_student("ogrenci", &db).await;618 let user = a_student("ogrenci", &db).await;
610 619
611- let original = upsert(620+ let (original, _) = upsert(
612 &db,621 &db,
613 &homework,622 &homework,
614 &user,623 &user,
615 Some(SubmissionText::try_new("photo answer").unwrap()),624 Some(SubmissionText::try_new("photo answer").unwrap()),
625+ false,
616 )626 )
617 .await627 .await
618 .unwrap()628 .unwrap()
@@ -636,11 +646,14 @@ mod tests {
636 /// and the last assertion reads `(2, 2)` — the farm.646 /// and the last assertion reads `(2, 2)` — the farm.
637 #[tokio::test]647 #[tokio::test]
638 async fn submit_delete_submit_is_worth_one_submission() {648 async fn submit_delete_submit_is_worth_one_submission() {
639- let db = crate::database::init_mem().await.unwrap();649+ let (db, _leases) = crate::database::init_test_db().await;
640 let homework = a_homework(far_future(), &db).await;650 let homework = a_homework(far_future(), &db).await;
641 let user = a_student("ogrenci", &db).await;651 let user = a_student("ogrenci", &db).await;
642 652
643- upsert(&db, &homework, &user, None).await.unwrap().unwrap();653+ upsert(&db, &homework, &user, None, false)
654+ .await
655+ .unwrap()
656+ .unwrap();
644 assert_eq!(counters(&user, &db).await, (1, 1));657 assert_eq!(counters(&user, &db).await, (1, 1));
645 658
646 let mine = read_for(&db, homework.get_id(), &user)659 let mine = read_for(&db, homework.get_id(), &user)
@@ -658,7 +671,10 @@ mod tests {
658 .is_none()671 .is_none()
659 );672 );
660 673
661- upsert(&db, &homework, &user, None).await.unwrap().unwrap();674+ upsert(&db, &homework, &user, None, false)
675+ .await
676+ .unwrap()
677+ .unwrap();
662 assert_eq!(counters(&user, &db).await, (1, 1));678 assert_eq!(counters(&user, &db).await, (1, 1));
663 }679 }
664 680
@@ -668,13 +684,19 @@ mod tests {
668 /// what it took.684 /// what it took.
669 #[tokio::test]685 #[tokio::test]
670 async fn a_late_submission_counts_as_submitted_but_not_on_time() {686 async fn a_late_submission_counts_as_submitted_but_not_on_time() {
671- let db = crate::database::init_mem().await.unwrap();687+ let (db, _leases) = crate::database::init_test_db().await;
672 let punctual = a_homework(far_future(), &db).await;688 let punctual = a_homework(far_future(), &db).await;
673 let overdue = a_homework(Timestamp::from_millis(1), &db).await;689 let overdue = a_homework(Timestamp::from_millis(1), &db).await;
674 let user = a_student("ogrenci", &db).await;690 let user = a_student("ogrenci", &db).await;
675 691
676- upsert(&db, &punctual, &user, None).await.unwrap().unwrap();692+ upsert(&db, &punctual, &user, None, false)
677- upsert(&db, &overdue, &user, None).await.unwrap().unwrap();693+ .await
694+ .unwrap()
695+ .unwrap();
696+ upsert(&db, &overdue, &user, None, false)
697+ .await
698+ .unwrap()
699+ .unwrap();
678 assert_eq!(counters(&user, &db).await, (2, 1));700 assert_eq!(counters(&user, &db).await, (2, 1));
679 701
680 // Withdrawing the *late* one takes back only the submission, never the702 // Withdrawing the *late* one takes back only the submission, never the
@@ -707,20 +729,25 @@ mod tests {
707 /// to prevent.729 /// to prevent.
708 #[tokio::test]730 #[tokio::test]
709 async fn a_row_with_no_stored_verdict_falls_back_to_the_deadline() {731 async fn a_row_with_no_stored_verdict_falls_back_to_the_deadline() {
710- let db = crate::database::init_mem().await.unwrap();732+ let (db, _leases) = crate::database::init_test_db().await;
711 let punctual = a_homework(far_future(), &db).await;733 let punctual = a_homework(far_future(), &db).await;
712 let overdue = a_homework(Timestamp::from_millis(1), &db).await;734 let overdue = a_homework(Timestamp::from_millis(1), &db).await;
713 let user = a_student("ogrenci", &db).await;735 let user = a_student("ogrenci", &db).await;
714 736
715- upsert(&db, &punctual, &user, None).await.unwrap().unwrap();737+ upsert(&db, &punctual, &user, None, false)
716- upsert(&db, &overdue, &user, None).await.unwrap().unwrap();738+ .await
739+ .unwrap()
740+ .unwrap();
741+ upsert(&db, &overdue, &user, None, false)
742+ .await
743+ .unwrap()
744+ .unwrap();
717 assert_eq!(counters(&user, &db).await, (2, 1));745 assert_eq!(counters(&user, &db).await, (2, 1));
718 // Aged into legacy rows: the counters keep the credit, the rows lose the746 // Aged into legacy rows: the counters keep the credit, the rows lose the
719 // verdict — the exact state of every submission on an existing volume.747 // verdict — the exact state of every submission on an existing volume.
720- db.query("UPDATE homework_submission UNSET counted_on_time")748+ sqlx::query("UPDATE homework_submission SET counted_on_time = NULL")
749+ .execute(&db)
721 .await750 .await
722- .unwrap()
723- .check()
724 .unwrap();751 .unwrap();
725 752
726 let late = read_for(&db, overdue.get_id(), &user)753 let late = read_for(&db, overdue.get_id(), &user)
@@ -752,14 +779,17 @@ mod tests {
752 /// stored `true` against a live `late = true`.779 /// stored `true` against a live `late = true`.
753 #[tokio::test]780 #[tokio::test]
754 async fn a_deadline_moved_under_the_caller_is_judged_by_the_stored_value() {781 async fn a_deadline_moved_under_the_caller_is_judged_by_the_stored_value() {
755- let db = crate::database::init_mem().await.unwrap();782+ let (db, _leases) = crate::database::init_test_db().await;
756 let user = a_student("ogrenci", &db).await;783 let user = a_student("ogrenci", &db).await;
757 784
758 // Extended at 23:59: the snapshot says the deadline has passed, the785 // Extended at 23:59: the snapshot says the deadline has passed, the
759 // store says it has not. A hand-in now is on time.786 // store says it has not. A hand-in now is on time.
760 let extended = a_homework(Timestamp::from_millis(1), &db).await;787 let extended = a_homework(Timestamp::from_millis(1), &db).await;
761 deadline_moves_to(&extended, far_future(), &db).await;788 deadline_moves_to(&extended, far_future(), &db).await;
762- let landed = upsert(&db, &extended, &user, None).await.unwrap().unwrap();789+ let (landed, _) = upsert(&db, &extended, &user, None, false)
790+ .await
791+ .unwrap()
792+ .unwrap();
763 assert_eq!(counters(&user, &db).await, (1, 1));793 assert_eq!(counters(&user, &db).await, (1, 1));
764 assert_eq!(stored_verdict(landed.get_id(), &db).await, Some(true));794 assert_eq!(stored_verdict(landed.get_id(), &db).await, Some(true));
765 assert!(!late_flag(&landed, &db).await);795 assert!(!late_flag(&landed, &db).await);
@@ -768,7 +798,10 @@ mod tests {
768 // the deadline is gone. The same hand-in is late.798 // the deadline is gone. The same hand-in is late.
769 let pulled = a_homework(far_future(), &db).await;799 let pulled = a_homework(far_future(), &db).await;
770 deadline_moves_to(&pulled, Timestamp::from_millis(1), &db).await;800 deadline_moves_to(&pulled, Timestamp::from_millis(1), &db).await;
771- let missed = upsert(&db, &pulled, &user, None).await.unwrap().unwrap();801+ let (missed, _) = upsert(&db, &pulled, &user, None, false)
802+ .await
803+ .unwrap()
804+ .unwrap();
772 assert_eq!(counters(&user, &db).await, (2, 1));805 assert_eq!(counters(&user, &db).await, (2, 1));
773 assert_eq!(stored_verdict(missed.get_id(), &db).await, Some(false));806 assert_eq!(stored_verdict(missed.get_id(), &db).await, Some(false));
774 assert!(late_flag(&missed, &db).await);807 assert!(late_flag(&missed, &db).await);
src/db/meal_attendance.rsmodified+1 -1
@@ -113,7 +113,7 @@ pub async fn list_for_student(
113 AND ($3::text IS NULL OR menu IN (SELECT id FROM menu WHERE date <= $3::text))",113 AND ($3::text IS NULL OR menu IN (SELECT id FROM menu WHERE date <= $3::text))",
114 "ORDER BY marked_at DESC, menu DESC",114 "ORDER BY marked_at DESC, menu DESC",
115 )115 )
116- .bind(student.key())116+ .bind(student.uuid())
117 .bind(Param::OptText(from.map(|date| date.as_str().to_string())))117 .bind(Param::OptText(from.map(|date| date.as_str().to_string())))
118 .bind(Param::OptText(to.map(|date| date.as_str().to_string())))118 .bind(Param::OptText(to.map(|date| date.as_str().to_string())))
119 .run(limit, offset, db)119 .run(limit, offset, db)
src/db/meal_booking.rsmodified+34 -20
@@ -368,7 +368,7 @@ pub async fn release_seat(
368 #[cfg(test)]368 #[cfg(test)]
369 mod tests {369 mod tests {
370 use super::*;370 use super::*;
371- use crate::database::init_mem;371+ use crate::database::init_test_db;
372 use crate::db::cap;372 use crate::db::cap;
373 use crate::db::meal_ledger;373 use crate::db::meal_ledger;
374 use crate::db::menu;374 use crate::db::menu;
@@ -387,14 +387,25 @@ mod tests {
387 }387 }
388 388
389 async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) {389 async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) {
390- let db = init_mem().await.unwrap();390+ let (db, _leases) = init_test_db().await;
391+ // The menu's creator is a foreign key now: a real `app_user` row.
392+ let creator = UserId::generate();
393+ sqlx::query(
394+ "INSERT INTO app_user (id, username, password_hash, role) \
395+ VALUES ($1, $2, 'x', 'teacher')",
396+ )
397+ .bind(creator.uuid())
398+ .bind(format!("menu-fixture-{}", &creator.key()[..8]))
399+ .execute(&db)
400+ .await
401+ .unwrap();
391 let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];402 let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];
392 let menu = menu::create(403 let menu = menu::create(
393 &db,404 &db,
394 MenuDate::try_new(date).unwrap(),405 MenuDate::try_new(date).unwrap(),
395 MenuSlot::try_new("lunch", &slots).unwrap(),406 MenuSlot::try_new("lunch", &slots).unwrap(),
396 capacity,407 capacity,
397- &UserId::generate(),408+ &creator,
398 )409 )
399 .await410 .await
400 .unwrap();411 .unwrap();
@@ -404,23 +415,20 @@ mod tests {
404 /// The stored counter, absent reading as zero — the number the cap's415 /// The stored counter, absent reading as zero — the number the cap's
405 /// `WHERE` actually compares, not one recomputed from the rows.416 /// `WHERE` actually compares, not one recomputed from the rows.
406 async fn seats(menu: &MenuId, db: &Database) -> i64 {417 async fn seats(menu: &MenuId, db: &Database) -> i64 {
407- let mut result = db418+ use sqlx::Row as _;
408- .query("SELECT VALUE seats_booked FROM $id")419+
409- .bind(("id", menu.record()))420+ sqlx::query("SELECT COALESCE(seats_booked, 0) FROM menu WHERE id = $1")
421+ .bind(menu.key())
422+ .fetch_one(db)
410 .await423 .await
411 .unwrap()424 .unwrap()
412- .check()425+ .try_get::<i64, _>(0)
413- .unwrap();
414- result
415- .take::<Vec<Option<i64>>>(0)
416 .unwrap()426 .unwrap()
417- .into_iter()
418- .next()
419- .flatten()
420- .unwrap_or(0)
421 }427 }
422 428
423 async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish {429 async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish {
430+ // A cap far above every seat count in these tests: the dish must never
431+ // be the binding constraint here.
424 menu_dish::create(432 menu_dish::create(
425 db,433 db,
426 menu,434 menu,
@@ -428,6 +436,7 @@ mod tests {
428 None,436 None,
429 DishPrice::try_new(price).unwrap(),437 DishPrice::try_new(price).unwrap(),
430 DishTags::try_new(&[], &[]).unwrap(),438 DishTags::try_new(&[], &[]).unwrap(),
439+ 1_000,
431 )440 )
432 .await441 .await
433 .unwrap()442 .unwrap()
@@ -445,7 +454,6 @@ mod tests {
445 // A dish lands: the price a booking read a moment ago is now stale.454 // A dish lands: the price a booking read a moment ago is now stale.
446 add_dish(&menu, 1_000, &db).await;455 add_dish(&menu, 1_000, &db).await;
447 let row = MealBooking {456 let row = MealBooking {
448- id: MealBookingId::composite(&menu, &ali),
449 menu: menu.clone(),457 menu: menu.clone(),
450 student: ali.clone(),458 student: ali.clone(),
451 booked_by: ali,459 booked_by: ali,
@@ -456,7 +464,7 @@ mod tests {
456 created_at: Timestamp::now(),464 created_at: Timestamp::now(),
457 };465 };
458 let place = async |seen| {466 let place = async |seen| {
459- claim_and_place(&db, &menu.record(), cap::UNLIMITED, seen, &row, None, None)467+ claim_and_place(&db, &menu, cap::UNLIMITED, seen, &row, None, None)
460 .await468 .await
461 .unwrap()469 .unwrap()
462 };470 };
@@ -466,7 +474,10 @@ mod tests {
466 );474 );
467 assert_eq!(seats(&menu, &db).await, 0, "and must write nothing");475 assert_eq!(seats(&menu, &db).await, 0, "and must write nothing");
468 assert!(476 assert!(
469- read(&db, row.get_id()).await.unwrap().is_none(),477+ read(&db, &MealBookingId::composite(&menu, row.get_student()))
478+ .await
479+ .unwrap()
480+ .is_none(),
470 "the refused transaction must not leave the row behind either"481 "the refused transaction must not leave the row behind either"
471 );482 );
472 483
@@ -555,7 +566,11 @@ mod tests {
555 "the attempt this call read is gone, so it releases nothing"566 "the attempt this call read is gone, so it releases nothing"
556 );567 );
557 // Stored state, not the returned value: the mem engine forges wins.568 // Stored state, not the returned value: the mem engine forges wins.
558- let stored = read(&db, live.get_id()).await.unwrap().unwrap();569+ let stored =
570+ read(&db, &MealBookingId::composite(&menu, live.get_student()))
571+ .await
572+ .unwrap()
573+ .unwrap();
559 assert_eq!(stored.get_status(), MealBookingStatus::Booked);574 assert_eq!(stored.get_status(), MealBookingStatus::Booked);
560 assert_eq!(stored.get_attempt(), live.get_attempt());575 assert_eq!(stored.get_attempt(), live.get_attempt());
561 assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back");576 assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back");
@@ -625,7 +640,6 @@ mod tests {
625 let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap();640 let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap();
626 let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version();641 let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version();
627 let row = MealBooking {642 let row = MealBooking {
628- id: MealBookingId::composite(&menu, &ali),
629 menu: menu.clone(),643 menu: menu.clone(),
630 student: ali.clone(),644 student: ali.clone(),
631 booked_by: ali.clone(),645 booked_by: ali.clone(),
@@ -640,7 +654,7 @@ mod tests {
640 let place = async || {654 let place = async || {
641 claim_and_place(655 claim_and_place(
642 &db,656 &db,
643- &menu.record(),657+ &menu,
644 cap::UNLIMITED,658 cap::UNLIMITED,
645 seen,659 seen,
646 &row,660 &row,
src/db/meal_ledger.rsmodified+0 -43
@@ -140,46 +140,3 @@ pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError
140 .iter()140 .iter()
141 .fold(0i64, |sum, row| sum + row.kind.sign() * row.total))141 .fold(0i64, |sum, row| sum + row.kind.sign() * row.total))
142 }142 }
143-#[cfg(test)]
144-mod tests {
145- use super::*;
146-
147- /// The balance aggregate **against a real server**, and `#[ignore]`d for
148- /// it: `init_mem`'s embedded engine is not the store this runs on, and an
149- /// aggregate is exactly where the two are known to differ — a `count()`
150- /// over an indexed field comes back `{count: N}` from the server and a
151- /// bare int from memory, and `student` here *is* indexed. This asserts the
152- /// `GROUP BY` really decodes into [`KindTotal`] and folds to the
153- /// documented figure, per kind, scoped to one student.
154- #[tokio::test]
155- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
156- async fn the_balance_aggregate_decodes_on_a_real_server() {
157- let (db, _serialized) = crate::database::init_test_server("meal_balance_sum").await;
158- db.query(
159- "CREATE meal_ledger:a SET student = user:ali, kind = 'credit', \
160- amount_minor = 10000, recorded_by = user:adm, created_at = 1;
161- CREATE meal_ledger:b SET student = user:ali, kind = 'charge', \
162- amount_minor = 4500, recorded_by = user:adm, created_at = 2;
163- CREATE meal_ledger:c SET student = user:ali, kind = 'charge', \
164- amount_minor = 1500, recorded_by = user:adm, created_at = 3;
165- CREATE meal_ledger:d SET student = user:ali, kind = 'reversal', \
166- amount_minor = 4500, recorded_by = user:adm, created_at = 4;
167- CREATE meal_ledger:e SET student = user:veli, kind = 'credit', \
168- amount_minor = 777, recorded_by = user:adm, created_at = 5;",
169- )
170- .await
171- .unwrap()
172- .check()
173- .unwrap();
174- let ali = UserId::from_key("ali");
175- assert_eq!(
176- balance_of(&db, &ali).await.unwrap(),
177- 10_000 - 4_500 - 1_500 + 4_500
178- );
179- // Somebody with no lines at all: no groups come back, not an error.
180- assert_eq!(
181- balance_of(&db, &UserId::from_key("nobody")).await.unwrap(),
182- 0
183- );
184- }
185-}
src/db/menu.rsmodified+95 -80
@@ -187,11 +187,16 @@ pub async fn update(
187 /// no meaning without its menu, and the menu key cannot be re-homed.187 /// no meaning without its menu, and the menu key cannot be re-homed.
188 ///188 ///
189 /// Refused (409) while a seat is still held, and the *row itself* decides189 /// Refused (409) while a seat is still held, and the *row itself* decides
190-/// that: the delete carries the seat counter in its `WHERE`, so a booking190+/// that: the guard that unlocks the sweep reads the seat counter in its own
191-/// landing at that instant either takes its seat before the delete (which191+/// `WHERE` under `FOR UPDATE`, so a booking landing at that instant either
192-/// then finds a non-zero counter and refuses) or after it (and finds no192+/// takes its seat before the delete (which then finds a non-zero counter
193-/// menu). A read-then-delete pair had a window where both happened — a193+/// and refuses) or after it (and finds no menu). A read-then-delete pair
194-/// paid seat on a menu that no longer exists.194+/// had a window where both happened — a paid seat on a menu that no longer
195+/// exists. The lock is also what makes the sweep's order safe: the dishes
196+/// and marks go first (both FKs are `ON DELETE NO ACTION`, so the parent
197+/// row cannot leave while they stand) and the menu row goes last, with no
198+/// window in between in which the children of a surviving menu could be
199+/// destroyed.
195 ///200 ///
196 /// The slot gets its reference back in that same transaction — a slot no201 /// The slot gets its reference back in that same transaction — a slot no
197 /// menu is published for any more may leave the settings again. Released202 /// menu is published for any more may leave the settings again. Released
@@ -218,15 +223,39 @@ pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> {
218 let key = menu.id.key().to_string();223 let key = menu.id.key().to_string();
219 let counter = slot_ref(menu.slot.as_str());224 let counter = slot_ref(menu.slot.as_str());
220 let deleted = tx_with_retry(db, true, async move |tx| {225 let deleted = tx_with_retry(db, true, async move |tx| {
221- let deleted = sqlx::query_as!(226+ // The row itself decides the guard, under its own lock: a booking
227+ // racing this delete either committed first (the guard reads its
228+ // seat and refuses before any child is touched) or queues on the
229+ // lock and lands after the commit — and finds no menu.
230+ let guard = sqlx::query!(
231+ "SELECT 1 AS deletable FROM menu WHERE id = $1 AND seats_booked = 0 FOR UPDATE",
232+ key,
233+ )
234+ .fetch_optional(&mut *tx)
235+ .await?;
236+ if guard.is_none() {
237+ return Ok(None);
238+ }
239+ // The children go first: both `menu_dish.menu` and
240+ // `meal_attendance.menu` are `ON DELETE NO ACTION`, so the parent
241+ // row cannot leave while they stand.
242+ sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key)
243+ .execute(&mut *tx)
244+ .await?;
245+ sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key)
246+ .execute(&mut *tx)
247+ .await?;
248+ let row = sqlx::query_as!(
222 Menu,249 Menu,
223- "DELETE FROM menu WHERE id = $1 AND seats_booked = 0250+ "DELETE FROM menu WHERE id = $1
224 RETURNING id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"",251 RETURNING id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"",
225 key,252 key,
226 )253 )
227 .fetch_optional(&mut *tx)254 .fetch_optional(&mut *tx)
228 .await?;255 .await?;
229- let Some(row) = deleted else {256+ // Unreachable while the guard holds the row's lock, but the match
257+ // keeps the shape honest: `row` exists iff the guard passed.
258+ let Some(row) = row else {
230 return Ok(None);259 return Ok(None);
231 };260 };
232 sqlx::query!(261 sqlx::query!(
@@ -235,12 +264,6 @@ pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> {
235 )264 )
236 .execute(&mut *tx)265 .execute(&mut *tx)
237 .await?;266 .await?;
238- sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key)
239- .execute(&mut *tx)
240- .await?;
241- sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key)
242- .execute(&mut *tx)
243- .await?;
244 Ok(Some(row))267 Ok(Some(row))
245 })268 })
246 .await?;269 .await?;
@@ -256,20 +279,26 @@ pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> {
256 #[cfg(test)]279 #[cfg(test)]
257 mod tests {280 mod tests {
258 use super::*;281 use super::*;
259- use crate::database::init_mem;282+ use crate::database::init_test_db;
260 use crate::db::meal_attendance;283 use crate::db::meal_attendance;
261 use crate::db::menu_dish;284 use crate::db::menu_dish;
262 use crate::domain::meal_attendance::MealAttendanceStatus;285 use crate::domain::meal_attendance::MealAttendanceStatus;
263 use crate::domain::menu_dish::{DishName, DishPrice, DishTags};286 use crate::domain::menu_dish::{DishName, DishPrice, DishTags};
264 use crate::domain::settings::MealSlotDef;287 use crate::domain::settings::MealSlotDef;
265 288
289+ /// The one fixture person, by a fixed valid id every publish can name.
290+ const TEACHER: &str = "019732e3-7b00-7000-8000-00000000acdc";
291+
266 async fn school() -> Database {292 async fn school() -> Database {
267- let db = init_mem().await.unwrap();293+ let (db, _leases) = init_test_db().await;
268- db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';")294+ sqlx::query(
269- .await295+ "INSERT INTO app_user (id, username, password_hash, role) \
270- .unwrap()296+ VALUES ($1, 'teacher', 'x', 'teacher')",
271- .check()297+ )
272- .unwrap();298+ .bind(UserId::from_key(TEACHER).uuid())
299+ .execute(&db)
300+ .await
301+ .unwrap();
273 db302 db
274 }303 }
275 304
@@ -280,28 +309,36 @@ mod tests {
280 /// The reference count, re-read out of the store — never off a return309 /// The reference count, re-read out of the store — never off a return
281 /// value, which the in-memory engine forges wins on.310 /// value, which the in-memory engine forges wins on.
282 async fn refs(db: &Database) -> i64 {311 async fn refs(db: &Database) -> i64 {
283- let mut result = db312+ sqlx::query("SELECT count FROM slot_ref WHERE name = 'lunch'")
284- .query("SELECT VALUE (count ?? 0) FROM $id")313+ .fetch_optional(db)
285- .bind(("id", slot_ref("lunch")))
286 .await314 .await
287 .unwrap()315 .unwrap()
288- .check()316+ .map(|row| row.try_get::<i64, _>(0).unwrap())
289- .unwrap();
290- result
291- .take::<Vec<i64>>(0)
292- .unwrap()
293- .into_iter()
294- .next()
295 .unwrap_or(0)317 .unwrap_or(0)
296 }318 }
297 319
320+ /// The settings guard's retire switch, driven straight: `true` only when
321+ /// this call flipped the bit.
322+ async fn retire_lunch(db: &Database) -> bool {
323+ sqlx::query(
324+ "INSERT INTO slot_ref (name, count, retired) VALUES ('lunch', 0, TRUE)
325+ ON CONFLICT (name) DO UPDATE SET retired = TRUE
326+ WHERE slot_ref.count = 0 AND slot_ref.retired IS DISTINCT FROM TRUE
327+ RETURNING 1",
328+ )
329+ .fetch_optional(db)
330+ .await
331+ .unwrap()
332+ .is_some()
333+ }
334+
298 async fn publish(date: &str, db: &Database) -> Result<Menu, AppError> {335 async fn publish(date: &str, db: &Database) -> Result<Menu, AppError> {
299 create(336 create(
300 db,337 db,
301 MenuDate::try_new(date).unwrap(),338 MenuDate::try_new(date).unwrap(),
302 lunch(),339 lunch(),
303 None,340 None,
304- &UserId::from_key("teacher"),341+ &UserId::from_key(TEACHER),
305 )342 )
306 .await343 .await
307 }344 }
@@ -309,15 +346,15 @@ mod tests {
309 /// Plant a menu row the pre-check will (or will not) find, without going346 /// Plant a menu row the pre-check will (or will not) find, without going
310 /// through the claim — a row published before the counter existed.347 /// through the claim — a row published before the counter existed.
311 async fn plant(id: &MenuId, date: &str, db: &Database) {348 async fn plant(id: &MenuId, date: &str, db: &Database) {
312- db.query(349+ sqlx::query(
313- "CREATE $id SET date = $date, slot = 'lunch', \350+ "INSERT INTO menu (id, date, slot, created_by, created_at) \
314- created_by = user:teacher, created_at = 1",351+ VALUES ($1, $2, 'lunch', $3, 1)",
315 )352 )
316- .bind(("id", id.record()))353+ .bind(id.key())
317- .bind(("date", date.to_string()))354+ .bind(date)
355+ .bind(UserId::from_key(TEACHER).uuid())
356+ .execute(db)
318 .await357 .await
319- .unwrap()
320- .check()
321 .unwrap();358 .unwrap();
322 }359 }
323 360
@@ -340,7 +377,7 @@ mod tests {
340 #[tokio::test]377 #[tokio::test]
341 async fn a_retired_slot_refuses_and_writes_nothing() {378 async fn a_retired_slot_refuses_and_writes_nothing() {
342 let db = school().await;379 let db = school().await;
343- assert!(cap::retire(&slot_ref("lunch"), &db).await.unwrap());380+ assert!(retire_lunch(&db).await);
344 381
345 let refused = publish("2026-08-02", &db)382 let refused = publish("2026-08-02", &db)
346 .await383 .await
@@ -438,7 +475,7 @@ mod tests {
438 assert!(matches!(gone, AppError::NotFound), "got {gone:?}");475 assert!(matches!(gone, AppError::NotFound), "got {gone:?}");
439 assert_eq!(refs(&db).await, 1);476 assert_eq!(refs(&db).await, 1);
440 assert!(477 assert!(
441- !cap::retire(&slot_ref("lunch"), &db).await.unwrap(),478+ !retire_lunch(&db).await,
442 "a slot a menu is still published for may not be retired"479 "a slot a menu is still published for may not be retired"
443 );480 );
444 481
@@ -465,41 +502,16 @@ mod tests {
465 /// menu row too ([`bump_menu_and_write`]) instead of reading it: the two502 /// menu row too ([`bump_menu_and_write`]) instead of reading it: the two
466 /// transactions then touch one key and the store refuses to commit both.503 /// transactions then touch one key and the store refuses to commit both.
467 ///504 ///
468- /// The window is opened by the database itself rather than by a lucky505+ /// The window the schema event used to force open is the menu row's own
469- /// interleaving — a `DEFINE EVENT` on `menu` fires *inside* the delete's own506+ /// lock now: every child write also writes the menu row, so a child racing
470- /// transaction, the instant the row goes, so the `SLEEP` lands exactly507+ /// the delete serializes on that row instead of committing into a range
471- /// between the delete and its sweep every single time. Nothing in `src/`508+ /// the sweep has already passed. A barrier start lets both orders happen;
472- /// knows about it; the seam is the schema.509+ /// the invariant must hold in each.
473- ///
474- /// Real server, and `#[ignore]`d for it: the subject *is* the store's
475- /// conflict detection, which `init_mem`'s embedded engine does not have —
476- /// it commits both writes and answers `Ok` to each, which would fail this
477- /// test on correct code (see [`crate::database::init_test_server`]).
478- /// Mutation-tested: putting [`meal_attendance::mark`] back on a menu *read*
479- /// (`UPSERT (SELECT VALUE $id FROM $menu) …`, the shape it shipped with)
480- /// turns this red at **both** of its two rounds — the mark commits, the
481- /// sweep misses it, and the row is left pointing at a menu that is gone.
482 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]510 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
483- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
484 async fn a_child_written_inside_a_delete_never_outlives_the_menu() {511 async fn a_child_written_inside_a_delete_never_outlives_the_menu() {
485 use crate::domain::menu_dish::DishDescription;512 use crate::domain::menu_dish::DishDescription;
486 513
487- let (db, _serialized) = crate::database::init_test_server("menu_delete_race").await;514+ let db = school().await;
488- db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';")
489- .await
490- .unwrap()
491- .check()
492- .unwrap();
493- // Hold the delete open for a full second after the row is gone, while
494- // its cascade still has to run.
495- db.query(
496- "DEFINE EVENT hold_the_window ON TABLE menu WHEN $event = 'DELETE' \
497- THEN { SLEEP 1s; };",
498- )
499- .await
500- .unwrap()
501- .check()
502- .unwrap();
503 515
504 let (mut dishes, mut marks, mut swept) = (0, 0, 0);516 let (mut dishes, mut marks, mut swept) = (0, 0, 0);
505 for round in 0..4 {517 for round in 0..4 {
@@ -508,19 +520,21 @@ mod tests {
508 .unwrap();520 .unwrap();
509 let id = menu.get_id().clone();521 let id = menu.get_id().clone();
510 522
523+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
511 let drop_it = {524 let drop_it = {
512- let db = db.clone();525+ let (db, gate, menu) = (db.clone(), gate.clone(), menu);
513- tokio::spawn(async move { delete(&db, menu).await })526+ tokio::spawn(async move {
527+ gate.wait().await;
528+ delete(&db, menu).await
529+ })
514 };530 };
515- // The child starts inside the held window — the delete's row is
516- // gone but uncommitted, which is exactly what a menu read believes.
517- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
518 // One child per round, never both: whichever wrote first forces the531 // One child per round, never both: whichever wrote first forces the
519 // delete to re-send, and its second pass sweeps the other's row —532 // delete to re-send, and its second pass sweeps the other's row —
520 // which would mask exactly the defect this test exists to catch.533 // which would mask exactly the defect this test exists to catch.
521 let child = {534 let child = {
522- let (id, db, dish) = (id.clone(), db.clone(), round % 2 == 0);535+ let (id, db, dish, gate) = (id.clone(), db.clone(), round % 2 == 0, gate);
523 tokio::spawn(async move {536 tokio::spawn(async move {
537+ gate.wait().await;
524 if dish {538 if dish {
525 menu_dish::create(539 menu_dish::create(
526 &db,540 &db,
@@ -529,6 +543,7 @@ mod tests {
529 None::<DishDescription>,543 None::<DishDescription>,
530 DishPrice::try_new(1).unwrap(),544 DishPrice::try_new(1).unwrap(),
531 DishTags::try_new(&[], &[]).unwrap(),545 DishTags::try_new(&[], &[]).unwrap(),
546+ 1_000,
532 )547 )
533 .await548 .await
534 .map(|_| ())549 .map(|_| ())
@@ -536,9 +551,9 @@ mod tests {
536 meal_attendance::mark(551 meal_attendance::mark(
537 &db,552 &db,
538 &id,553 &id,
539- &UserId::from_key("teacher"),554+ &UserId::from_key(TEACHER),
540 MealAttendanceStatus::try_new("served").unwrap(),555 MealAttendanceStatus::try_new("served").unwrap(),
541- &UserId::from_key("teacher"),556+ &UserId::from_key(TEACHER),
542 )557 )
543 .await558 .await
544 .map(|_| ())559 .map(|_| ())
src/db/message.rsmodified+1 -1
@@ -266,7 +266,7 @@ mod tests {
266 /// Asserts the *stored* order, not the mint order.266 /// Asserts the *stored* order, not the mint order.
267 #[tokio::test]267 #[tokio::test]
268 async fn inbox_is_newest_first_within_a_millisecond() {268 async fn inbox_is_newest_first_within_a_millisecond() {
269- let db = crate::database::init_mem().await.unwrap();269+ let (db, _leases) = crate::database::init_test_db().await;
270 let sender = UserId::from_key("a");270 let sender = UserId::from_key("a");
271 let recipient = UserId::from_key("b");271 let recipient = UserId::from_key("b");
272 let mut sent = Vec::new();272 let mut sent = Vec::new();
src/db/note.rsmodified+1 -1
@@ -144,7 +144,7 @@ mod tests {
144 /// been taken, which is the row whose blob used to leak.144 /// been taken, which is the row whose blob used to leak.
145 #[tokio::test]145 #[tokio::test]
146 async fn delete_returns_the_attachment_rows_it_removed() {146 async fn delete_returns_the_attachment_rows_it_removed() {
147- let db = crate::database::init_mem().await.unwrap();147+ let (db, _leases) = crate::database::init_test_db().await;
148 let owner = UserId::generate();148 let owner = UserId::generate();
149 let note = create(149 let note = create(
150 &db,150 &db,
src/db/note_file.rsmodified+2 -2
@@ -136,7 +136,7 @@ mod tests {
136 /// left.136 /// left.
137 #[tokio::test]137 #[tokio::test]
138 async fn insert_refuses_at_the_cap_without_leaking_a_slot() {138 async fn insert_refuses_at_the_cap_without_leaking_a_slot() {
139- let db = crate::database::init_mem().await.unwrap();139+ let (db, _leases) = crate::database::init_test_db().await;
140 let note = a_note(&db).await;140 let note = a_note(&db).await;
141 for index in 0..MAX_NOTE_FILES {141 for index in 0..MAX_NOTE_FILES {
142 let file = NoteFile::new(142 let file = NoteFile::new(
@@ -166,7 +166,7 @@ mod tests {
166 /// accepted again, and the count never dips below zero.166 /// accepted again, and the count never dips below zero.
167 #[tokio::test]167 #[tokio::test]
168 async fn delete_returns_the_slot_to_the_note() {168 async fn delete_returns_the_slot_to_the_note() {
169- let db = crate::database::init_mem().await.unwrap();169+ let (db, _leases) = crate::database::init_test_db().await;
170 let note = a_note(&db).await;170 let note = a_note(&db).await;
171 let file = NoteFile::new(171 let file = NoteFile::new(
172 note.get_id(),172 note.get_id(),
src/db/payment_ledger.rsmodified+0 -46
@@ -303,49 +303,3 @@ pub(crate) async fn applied_to(
303 Ok(total * -target_kind.sign())303 Ok(total * -target_kind.sign())
304 }304 }
305 305
306-#[cfg(test)]
307-mod tests {
308- use super::*;
309- use crate::domain::user::UserId;
310-
311- /// The mem engine is not the store this runs against, and an aggregate is
312- /// exactly where the two have diverged before: `count()` over an *indexed*
313- /// field compared to a plan-time value comes back `{count: N}` rather than
314- /// a plain int, and `student` is indexed on this table
315- /// (`payment_ledger_student`). So the `GROUP BY` is proved on a real
316- /// server: that it decodes into [`KindTotal`], that it folds to the
317- /// documented figure per kind, that it is scoped to one student, and that
318- /// someone with no lines at all comes back `0` rather than an error.
319- #[tokio::test]
320- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
321- async fn the_balance_aggregate_decodes_on_a_real_server() {
322- let (db, _serialized) = crate::database::init_test_server("payment_balance_sum").await;
323- db.query(
324- "CREATE payment_ledger:a SET student = user:ali, kind = 'charge', \
325- amount_minor = 10000, recorded_by = user:adm, created_at = 1;
326- CREATE payment_ledger:b SET student = user:ali, kind = 'credit', \
327- amount_minor = 6000, recorded_by = user:adm, created_at = 2;
328- CREATE payment_ledger:c SET student = user:ali, kind = 'refund', \
329- amount_minor = 1000, recorded_by = user:adm, created_at = 3;
330- CREATE payment_ledger:d SET student = user:ali, kind = 'reversal', \
331- amount_minor = 4500, recorded_by = user:adm, created_at = 4;
332- CREATE payment_ledger:e SET student = user:veli, kind = 'credit', \
333- amount_minor = 777, recorded_by = user:adm, created_at = 5;",
334- )
335- .await
336- .unwrap()
337- .check()
338- .unwrap();
339- let ali = UserId::from_key("ali");
340- assert_eq!(
341- balance_of(&db, &ali).await.unwrap(),
342- 6_000 + 4_500 - 10_000 - 1_000,
343- "credits + reversals - charges - refunds, and veli's line is not ali's"
344- );
345- // Somebody with no lines at all: no groups come back, not an error.
346- assert_eq!(
347- balance_of(&db, &UserId::from_key("nobody")).await.unwrap(),
348- 0
349- );
350- }
351-}
src/db/pomodoro.rsmodified+124 -133
@@ -3,10 +3,8 @@
3 //! the study streak are all decided inside [`finish`]'s one transaction —3 //! the study streak are all decided inside [`finish`]'s one transaction —
4 //! the whole rule is the batch itself.4 //! the whole rule is the batch itself.
5 5
6-use crate::constant::{6+use crate::constant::{MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS};
7- CAP_WRITE_TRIES, MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS,7+use crate::database::{Database, tx_with_retry};
8-};
9-use crate::database::{Database, backoff, tx_with_retry, unique_violation};
10 use crate::domain::pomodoro::{PomodoroSession, PomodoroSessionId};8 use crate::domain::pomodoro::{PomodoroSession, PomodoroSessionId};
11 use crate::domain::timestamp::Timestamp;9 use crate::domain::timestamp::Timestamp;
12 use crate::domain::user::UserId;10 use crate::domain::user::UserId;
@@ -16,14 +14,19 @@ use sqlx::query_as;
16 /// Start a session for `user`, stamped with the server clock. The open slot14 /// Start a session for `user`, stamped with the server clock. The open slot
17 /// is the partial unique index (`pomodoro_session_open_stint`): one row per15 /// is the partial unique index (`pomodoro_session_open_stint`): one row per
18 /// user with `finished_at IS NULL`. A dangling unfinished session (the16 /// user with `finished_at IS NULL`. A dangling unfinished session (the
19-/// browser died mid-timer) is deleted and replaced in the same statement —17+/// browser died mid-timer) is replaced by the same statement — the arbiter
20-/// it never counted, and blocking the next start behind it would only18+/// turns the insert into an in-place re-stamp (`DO UPDATE`), so the old row
21-/// punish the student for a crash.19+/// becomes the new stint; it never counted, and blocking the next start
20+/// behind it would only punish the student for a crash.
22 ///21 ///
23-/// Two racing starts cannot both insert: the index refuses the second22+/// The replace has to ride the arbiter. A `WITH gone AS (DELETE …) INSERT …`
24-/// (`23505`), which is retried — the re-run deletes the winner's open row23+/// CTE cannot do it: both halves run on one snapshot, so the insert's
25-/// and replaces it, the same last-write-wins the old deterministic-key24+/// uniqueness check still sees the row the CTE just deleted and refuses
26-/// upsert had.25+/// (23505) *deterministically* — a retry re-sends the identical statement and
26+/// dies identically, which is the 500 the port briefly shipped. `DO UPDATE`
27+/// is atomic: two racing starts cannot both win the slot, and the loser
28+/// re-stamps the winner's row — the same last-write-wins the old
29+/// deterministic-key upsert had.
27 ///30 ///
28 /// `label` is the student's own name for the stint, validated and trimmed31 /// `label` is the student's own name for the stint, validated and trimmed
29 /// upstream and stored verbatim. A `None` binds NULL — an unnamed start32 /// upstream and stored verbatim. A `None` binds NULL — an unnamed start
@@ -35,42 +38,24 @@ pub async fn start(
35 ) -> Result<PomodoroSession, AppError> {38 ) -> Result<PomodoroSession, AppError> {
36 let started_at = Timestamp::now();39 let started_at = Timestamp::now();
37 let id = PomodoroSessionId::generate();40 let id = PomodoroSessionId::generate();
38- // The statement is one atomic delete-and-replace; the only contention41+ let started = query_as!(
39- // is a rival start, and the index's verdict sends the loser around42+ PomodoroSession,
40- // again to overwrite.43+ "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
41- for attempt in 0..CAP_WRITE_TRIES {44+ VALUES ($2, $1, $3, NULL, NULL, $4)
42- backoff(attempt).await;45+ ON CONFLICT (app_user) WHERE finished_at IS NULL DO UPDATE
43- let started = match query_as!(46+ SET started_at = EXCLUDED.started_at, finished_at = NULL, counted = NULL,
44- PomodoroSession,47+ label = EXCLUDED.label
45- "WITH gone AS (48+ RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \
46- DELETE FROM pomodoro_session49+ started_at AS \"started_at: Timestamp\", \
47- WHERE app_user = $1 AND finished_at IS NULL50+ finished_at AS \"finished_at: Timestamp\", counted, label",
48- RETURNING 1)51+ user.uuid(),
49- INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)52+ id.uuid(),
50- SELECT $2, $1, $3, NULL, NULL, $453+ started_at.as_millis(),
51- RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \54+ label
52- started_at AS \"started_at: Timestamp\", \55+ )
53- finished_at AS \"finished_at: Timestamp\", counted, label",56+ .fetch_one(db)
54- user.uuid(),57+ .await?;
55- id.uuid(),58+ Ok(started)
56- started_at.as_millis(),
57- label
58- )
59- .fetch_one(db)
60- .await
61- {
62- Ok(row) => row,
63- // The winner of a race holds the open slot; one more round.
64- Err(err) if unique_violation(&err) == Some("pomodoro_session_open_stint") => {
65- continue;
66- }
67- Err(err) => return Err(err.into()),
68- };
69- return Ok(started);
70- }
71- Err(AppError::Internal(
72- "failed to start pomodoro session".into(),
73- ))
74 }59 }
75 60
76 /// Close `user`'s running session, deciding the counting verdict, the61 /// Close `user`'s running session, deciding the counting verdict, the
@@ -252,22 +237,19 @@ pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<PomodoroS
252 }237 }
253 #[cfg(test)]238 #[cfg(test)]
254 mod tests {239 mod tests {
255- use ulid::Ulid;
256-
257 use super::*;240 use super::*;
258- use crate::database;241+ use sqlx::Row as _;
259 242
260- /// A real `user` row: the counters land with `UPDATE`, which only ever243+ /// A real `app_user` row: the counters land with `UPDATE`, which only ever
261- /// touches a record that exists, so a fabricated id would silently store244+ /// touches a row that exists, so a fabricated id would silently store
262 /// nothing. The tests above need no row — they read only the stint log.245 /// nothing. The tests above need no row — they read only the stint log.
263 async fn a_user(db: &Database) -> UserId {246 async fn a_user(db: &Database) -> UserId {
264- let user = UserId::from_key(&Ulid::generate().to_string());247+ let user = UserId::generate();
265- db.query("CREATE $usr SET username = $name, password_hash = 'x'")248+ sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')")
266- .bind(("usr", user.record()))249+ .bind(user.uuid())
267- .bind(("name", user.key().to_string()))250+ .bind(format!("u{}", &user.key()[..8]))
251+ .execute(db)
268 .await252 .await
269- .unwrap()
270- .check()
271 .unwrap();253 .unwrap();
272 user254 user
273 }255 }
@@ -275,37 +257,37 @@ mod tests {
275 /// `(finished_total, focus_ms_total)` re-read from the store — never off257 /// `(finished_total, focus_ms_total)` re-read from the store — never off
276 /// what `finish` returned, which proves nothing about what was written.258 /// what `finish` returned, which proves nothing about what was written.
277 async fn counters(user: &UserId, db: &Database) -> (i64, i64) {259 async fn counters(user: &UserId, db: &Database) -> (i64, i64) {
278- let mut result = db260+ let row = sqlx::query(
279- .query(format!(261+ "SELECT pomodoro_finished_total, pomodoro_focus_ms_total \
280- "SELECT VALUE [({POMODORO_FINISHED_TOTAL_FIELD} ?? 0),262+ FROM app_user WHERE id = $1",
281- ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0)] FROM $usr"263+ )
282- ))264+ .bind(user.uuid())
283- .bind(("usr", user.record()))265+ .fetch_one(db)
284- .await266+ .await
285- .unwrap()267+ .unwrap();
286- .check()268+ (
287- .unwrap();269+ row.try_get::<i64, _>(0).unwrap(),
288- let rows: Vec<Vec<i64>> = result.take(0).unwrap();270+ row.try_get::<i64, _>(1).unwrap(),
289- let row = rows.into_iter().next().expect("the user row");271+ )
290- (row[0], row[1])
291 }272 }
292 273
293- /// `(current, longest, last_day)` re-read from the store.274+ /// `(current, longest, last_day)` re-read from the store; the unset day
275+ /// reads as the sentinel `-1` the streak arithmetic runs on.
294 async fn streak(user: &UserId, db: &Database) -> (i64, i64, i64) {276 async fn streak(user: &UserId, db: &Database) -> (i64, i64, i64) {
295- let mut result = db277+ let row = sqlx::query(
296- .query(format!(278+ "SELECT study_streak_current, study_streak_longest, \
297- "SELECT VALUE [({STUDY_STREAK_CURRENT_FIELD} ?? 0),279+ COALESCE(study_streak_last_day, -1) \
298- ({STUDY_STREAK_LONGEST_FIELD} ?? 0),280+ FROM app_user WHERE id = $1",
299- ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1)] FROM $usr"281+ )
300- ))282+ .bind(user.uuid())
301- .bind(("usr", user.record()))283+ .fetch_one(db)
302- .await284+ .await
303- .unwrap()285+ .unwrap();
304- .check()286+ (
305- .unwrap();287+ row.try_get::<i64, _>(0).unwrap(),
306- let rows: Vec<Vec<i64>> = result.take(0).unwrap();288+ row.try_get::<i64, _>(1).unwrap(),
307- let row = rows.into_iter().next().expect("the user row");289+ row.try_get::<i64, _>(2).unwrap(),
308- (row[0], row[1], row[2])290+ )
309 }291 }
310 292
311 /// Age *both* day buckets by `days`, so the next finish lands that many293 /// Age *both* day buckets by `days`, so the next finish lands that many
@@ -322,16 +304,16 @@ mod tests {
322 /// code to serve a test. Re-run before believing a failure that only ever304 /// code to serve a test. Re-run before believing a failure that only ever
323 /// happens near midnight UTC.305 /// happens near midnight UTC.
324 async fn age_by_days(user: &UserId, db: &Database, days: i64) {306 async fn age_by_days(user: &UserId, db: &Database, days: i64) {
325- db.query(format!(307+ sqlx::query(
326- "UPDATE $usr SET308+ "UPDATE app_user SET
327- {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days,309+ study_streak_last_day = COALESCE(study_streak_last_day, -1) - $1,
328- {POMODORO_COUNTED_DAY_FIELD} = ({POMODORO_COUNTED_DAY_FIELD} ?? -1) - $days"310+ pomodoro_counted_day = COALESCE(pomodoro_counted_day, -1) - $1
329- ))311+ WHERE id = $2",
330- .bind(("usr", user.record()))312+ )
331- .bind(("days", days))313+ .bind(days)
314+ .bind(user.uuid())
315+ .execute(db)
332 .await316 .await
333- .unwrap()
334- .check()
335 .unwrap();317 .unwrap();
336 }318 }
337 319
@@ -340,16 +322,22 @@ mod tests {
340 ///322 ///
341 /// One `UPSERT`, not `start` followed by a backdate: the concurrent test323 /// One `UPSERT`, not `start` followed by a backdate: the concurrent test
342 /// races four of these onto the same open row, and a separate backdate can324 /// races four of these onto the same open row, and a separate backdate can
343- /// be wiped by a rival's fresh `start`, handing whoever wins the `DELETE` a325+ /// be wiped by a rival's fresh `start`, handing whoever wins the arbiter
344- /// zero-length stint and reddening the run for no defect. Same statement326+ /// a zero-length stint and reddening the run for no defect. The same
345- /// `start` runs, one clock read earlier.327+ /// arbiter-riding statement `start` runs, one clock read earlier — the
328+ /// `DO UPDATE` arm drops the loser onto the winner's row in place.
346 async fn start_aged(user: &UserId, db: &Database, ms: i64) -> Result<(), AppError> {329 async fn start_aged(user: &UserId, db: &Database, ms: i64) -> Result<(), AppError> {
347- db.query("UPSERT $open CONTENT { user: $usr, started_at: $at }")330+ sqlx::query(
348- .bind(("open", PomodoroSessionId::open_for(user).record()))331+ "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
349- .bind(("usr", user.record()))332+ VALUES ($2, $1, $3, NULL, NULL, NULL)
350- .bind(("at", Timestamp::now().as_millis() - ms))333+ ON CONFLICT (app_user) WHERE finished_at IS NULL DO UPDATE
351- .await?334+ SET started_at = EXCLUDED.started_at, finished_at = NULL, counted = NULL",
352- .check()?;335+ )
336+ .bind(user.uuid())
337+ .bind(PomodoroSessionId::generate().uuid())
338+ .bind(Timestamp::now().as_millis() - ms)
339+ .execute(db)
340+ .await?;
353 Ok(())341 Ok(())
354 }342 }
355 343
@@ -362,7 +350,7 @@ mod tests {
362 350
363 #[tokio::test]351 #[tokio::test]
364 async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() {352 async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() {
365- let db = database::init_mem().await.unwrap();353+ let (db, _leases) = crate::database::init_test_db().await;
366 let user = a_user(&db).await;354 let user = a_user(&db).await;
367 // The stale-data case: a row that predates all three columns reads as355 // The stale-data case: a row that predates all three columns reads as
368 // no streak at all, and its first finish opens a run of one.356 // no streak at all, and its first finish opens a run of one.
@@ -386,7 +374,7 @@ mod tests {
386 374
387 #[tokio::test]375 #[tokio::test]
388 async fn a_gap_resets_the_run_but_never_the_high_water_mark() {376 async fn a_gap_resets_the_run_but_never_the_high_water_mark() {
389- let db = database::init_mem().await.unwrap();377+ let (db, _leases) = crate::database::init_test_db().await;
390 let user = a_user(&db).await;378 let user = a_user(&db).await;
391 379
392 one_stint(&user, &db).await;380 one_stint(&user, &db).await;
@@ -442,9 +430,8 @@ mod tests {
442 /// (a racer scheduled entirely after another's finish frees the slot) and430 /// (a racer scheduled entirely after another's finish frees the slot) and
443 /// the assertions allow it — the day count is per round, not per stint.431 /// the assertions allow it — the day count is per round, not per stint.
444 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]432 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
445- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
446 async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() {433 async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() {
447- let (db, _serialized) = crate::database::init_test_server("pomodoro_streak_race").await;434+ let (db, _leases) = crate::crate::database::init_test_db().await;
448 let user = a_user(&db).await;435 let user = a_user(&db).await;
449 let (mut finished, mut conflicts, mut errors) = (0, 0, 0);436 let (mut finished, mut conflicts, mut errors) = (0, 0, 0);
450 let mut last_error = String::new();437 let mut last_error = String::new();
@@ -511,7 +498,7 @@ mod tests {
511 498
512 #[tokio::test]499 #[tokio::test]
513 async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() {500 async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() {
514- let db = database::init_mem().await.unwrap();501+ let (db, _leases) = crate::database::init_test_db().await;
515 let user = a_user(&db).await;502 let user = a_user(&db).await;
516 assert_eq!(counters(&user, &db).await, (0, 0));503 assert_eq!(counters(&user, &db).await, (0, 0));
517 504
@@ -537,17 +524,19 @@ mod tests {
537 524
538 #[tokio::test]525 #[tokio::test]
539 async fn a_backwards_clock_adds_zero_ms_to_the_counter_never_a_negative() {526 async fn a_backwards_clock_adds_zero_ms_to_the_counter_never_a_negative() {
540- let db = database::init_mem().await.unwrap();527+ let (db, _leases) = crate::database::init_test_db().await;
541 let user = a_user(&db).await;528 let user = a_user(&db).await;
542 529
543 start(&db, &user, None).await.unwrap();530 start(&db, &user, None).await.unwrap();
544- db.query("UPDATE $open SET started_at = $future")531+ sqlx::query(
545- .bind(("open", PomodoroSessionId::open_for(&user).record()))532+ "UPDATE pomodoro_session SET started_at = $1
546- .bind(("future", Timestamp::now().as_millis() + 3_600_000))533+ WHERE app_user = $2 AND finished_at IS NULL",
547- .await534+ )
548- .unwrap()535+ .bind(Timestamp::now().as_millis() + 3_600_000)
549- .check()536+ .bind(user.uuid())
550- .unwrap();537+ .execute(&db)
538+ .await
539+ .unwrap();
551 540
552 // The clamp holds: zero milliseconds, never a negative — and a stint541 // The clamp holds: zero milliseconds, never a negative — and a stint
553 // measuring zero is below the minimum, so it moves neither counter.542 // measuring zero is below the minimum, so it moves neither counter.
@@ -569,7 +558,7 @@ mod tests {
569 /// pair and a study session, not the last millisecond.558 /// pair and a study session, not the last millisecond.
570 #[tokio::test]559 #[tokio::test]
571 async fn a_stint_under_the_minimum_is_logged_and_listed_but_counts_for_nothing() {560 async fn a_stint_under_the_minimum_is_logged_and_listed_but_counts_for_nothing() {
572- let db = database::init_mem().await.unwrap();561+ let (db, _leases) = crate::database::init_test_db().await;
573 let user = a_user(&db).await;562 let user = a_user(&db).await;
574 563
575 start_aged(&user, &db, MIN_COUNTED_POMODORO_MS - 60_000)564 start_aged(&user, &db, MIN_COUNTED_POMODORO_MS - 60_000)
@@ -609,7 +598,7 @@ mod tests {
609 /// rolls at midnight UTC.598 /// rolls at midnight UTC.
610 #[tokio::test]599 #[tokio::test]
611 async fn the_day_quota_caps_the_counter_and_rolls_at_midnight_utc() {600 async fn the_day_quota_caps_the_counter_and_rolls_at_midnight_utc() {
612- let db = database::init_mem().await.unwrap();601+ let (db, _leases) = crate::database::init_test_db().await;
613 let user = a_user(&db).await;602 let user = a_user(&db).await;
614 603
615 for _ in 0..MAX_COUNTED_POMODORO_PER_DAY {604 for _ in 0..MAX_COUNTED_POMODORO_PER_DAY {
@@ -647,7 +636,7 @@ mod tests {
647 /// and a badge is never taken back.636 /// and a badge is never taken back.
648 #[tokio::test]637 #[tokio::test]
649 async fn the_start_finish_farm_moves_no_counter_and_mints_no_badge() {638 async fn the_start_finish_farm_moves_no_counter_and_mints_no_badge() {
650- let db = database::init_mem().await.unwrap();639+ let (db, _leases) = crate::database::init_test_db().await;
651 let user = a_user(&db).await;640 let user = a_user(&db).await;
652 641
653 for _ in 0..200 {642 for _ in 0..200 {
@@ -675,10 +664,10 @@ mod tests {
675 664
676 #[tokio::test]665 #[tokio::test]
677 async fn restart_replaces_the_open_session_and_finish_closes_it() {666 async fn restart_replaces_the_open_session_and_finish_closes_it() {
678- let db = database::init_mem().await.unwrap();667+ let (db, _leases) = crate::database::init_test_db().await;
679- // A `record<user>` column checks the table of the id, not row668+ // The stint's owner is a real parent row now (the FK checks it), so
680- // existence — a fabricated id keeps this test free of user ceremony.669+ // the user ceremony stays — it is one helper call.
681- let user = UserId::from_key(&Ulid::generate().to_string());670+ let user = a_user(&db).await;
682 671
683 // Nothing running yet — finishing conflicts.672 // Nothing running yet — finishing conflicts.
684 assert!(matches!(673 assert!(matches!(
@@ -711,19 +700,21 @@ mod tests {
711 700
712 #[tokio::test]701 #[tokio::test]
713 async fn a_backwards_clock_records_a_zero_stint_not_a_negative_one() {702 async fn a_backwards_clock_records_a_zero_stint_not_a_negative_one() {
714- let db = database::init_mem().await.unwrap();703+ let (db, _leases) = crate::database::init_test_db().await;
715- let user = UserId::from_key(&Ulid::generate().to_string());704+ let user = a_user(&db).await;
716 705
717 start(&db, &user, None).await.unwrap();706 start(&db, &user, None).await.unwrap();
718 // Stand in for the NTP step: push the running stint's start an hour707 // Stand in for the NTP step: push the running stint's start an hour
719 // ahead, so the server clock `finish` reads is *behind* it.708 // ahead, so the server clock `finish` reads is *behind* it.
720- db.query("UPDATE $open SET started_at = $future")709+ sqlx::query(
721- .bind(("open", PomodoroSessionId::open_for(&user).record()))710+ "UPDATE pomodoro_session SET started_at = $1
722- .bind(("future", Timestamp::now().as_millis() + 3_600_000))711+ WHERE app_user = $2 AND finished_at IS NULL",
723- .await712+ )
724- .unwrap()713+ .bind(Timestamp::now().as_millis() + 3_600_000)
725- .check()714+ .bind(user.uuid())
726- .unwrap();715+ .execute(&db)
716+ .await
717+ .unwrap();
727 718
728 let closed = finish(&db, &user).await.unwrap();719 let closed = finish(&db, &user).await.unwrap();
729 let started = closed.get_started_at().as_millis();720 let started = closed.get_started_at().as_millis();
src/db/pool_question.rsmodified+39 -49
@@ -324,48 +324,38 @@ pub async fn delete(
324 324
325 #[cfg(test)]325 #[cfg(test)]
326 mod tests {326 mod tests {
327- use ulid::Ulid;
328-
329 use super::*;327 use super::*;
330 use crate::database;328 use crate::database;
331 use crate::domain::solution::SolutionBody;329 use crate::domain::solution::SolutionBody;
330+ use sqlx::Row as _;
332 331
333- /// The two counter columns plus a row to carry them: the `user` table is332+ /// A real `app_user` row: the asker and the approver are foreign keys on
334- /// SCHEMAFULL in production, and the counters are `option<int>` there.333+ /// the question, and the counters are plain `NOT NULL DEFAULT 0` columns.
335 async fn a_user(db: &Database) -> UserId {334 async fn a_user(db: &Database) -> UserId {
336- let user = UserId::from_key(&Ulid::generate().to_string());335+ let user = UserId::generate();
337- db.query(format!(336+ sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')")
338- "DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option<int>;337+ .bind(user.uuid())
339- DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option<int>;338+ .bind(format!("u{}", &user.key()[..8]))
340- CREATE $usr SET username = $name, password_hash = 'x';"339+ .execute(db)
341- ))340+ .await
342- .bind(("usr", user.record()))341+ .unwrap();
343- .bind(("name", user.key().to_string()))
344- .await
345- .unwrap()
346- .check()
347- .unwrap();
348 user342 user
349 }343 }
350 344
351- /// `(pool_approved_total, pool_published_total)` as stored — absent reads345+ /// `(pool_approved_total, pool_published_total)` as stored — the columns
352- /// zero, the way `BadgeStats::load` reads it.346+ /// read zero on a fresh row, the way `BadgeStats::load` reads them.
353 async fn counters(user: &UserId, db: &Database) -> (i64, i64) {347 async fn counters(user: &UserId, db: &Database) -> (i64, i64) {
354- let mut result = db348+ let row = sqlx::query(
355- .query(format!(349+ "SELECT pool_approved_total, pool_published_total \
356- "SELECT VALUE [({POOL_APPROVED_TOTAL_FIELD} ?? 0),350+ FROM app_user WHERE id = $1",
357- ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0)] FROM $usr"351+ )
358- ))352+ .bind(user.uuid())
359- .bind(("usr", user.record()))353+ .fetch_one(db)
360- .await354+ .await
361- .unwrap()355+ .unwrap();
362- .check()
363- .unwrap();
364- let rows = result.take::<Vec<Vec<i64>>>(0).unwrap();
365- let row = rows.into_iter().next().unwrap_or_default();
366 (356 (
367- row.first().copied().unwrap_or(0),357+ row.try_get::<i64, _>(0).unwrap(),
368- row.get(1).copied().unwrap_or(0),358+ row.try_get::<i64, _>(1).unwrap(),
369 )359 )
370 }360 }
371 361
@@ -380,9 +370,9 @@ mod tests {
380 370
381 #[tokio::test]371 #[tokio::test]
382 async fn approval_is_a_one_way_race_safe_transition() {372 async fn approval_is_a_one_way_race_safe_transition() {
383- let db = database::init_mem().await.unwrap();373+ let (db, _leases) = database::init_test_db().await;
384- let asker = UserId::from_key(&Ulid::generate().to_string());374+ let asker = a_user(&db).await;
385- let teacher = UserId::from_key(&Ulid::generate().to_string());375+ let teacher = a_user(&db).await;
386 376
387 let q = insert(&db, question(&asker)).await.unwrap();377 let q = insert(&db, question(&asker)).await.unwrap();
388 assert_eq!(q.get_status(), STATUS_PENDING);378 assert_eq!(q.get_status(), STATUS_PENDING);
@@ -407,7 +397,7 @@ mod tests {
407 /// published side, and neither on a second approve of the same question.397 /// published side, and neither on a second approve of the same question.
408 #[tokio::test]398 #[tokio::test]
409 async fn approval_moves_both_counters_once_and_only_once() {399 async fn approval_moves_both_counters_once_and_only_once() {
410- let db = database::init_mem().await.unwrap();400+ let (db, _leases) = database::init_test_db().await;
411 let asker = a_user(&db).await;401 let asker = a_user(&db).await;
412 let teacher = a_user(&db).await;402 let teacher = a_user(&db).await;
413 403
@@ -440,7 +430,7 @@ mod tests {
440 /// neither counter moves when one person is both ends of the transition.430 /// neither counter moves when one person is both ends of the transition.
441 #[tokio::test]431 #[tokio::test]
442 async fn self_approval_still_approves_but_moves_neither_counter() {432 async fn self_approval_still_approves_but_moves_neither_counter() {
443- let db = database::init_mem().await.unwrap();433+ let (db, _leases) = database::init_test_db().await;
444 let teacher = a_user(&db).await;434 let teacher = a_user(&db).await;
445 435
446 let q = insert(&db, question(&teacher)).await.unwrap();436 let q = insert(&db, question(&teacher)).await.unwrap();
@@ -464,10 +454,10 @@ mod tests {
464 454
465 #[tokio::test]455 #[tokio::test]
466 async fn visibility_hides_others_pending_questions() {456 async fn visibility_hides_others_pending_questions() {
467- let db = database::init_mem().await.unwrap();457+ let (db, _leases) = database::init_test_db().await;
468- let asker = UserId::from_key(&Ulid::generate().to_string());458+ let asker = a_user(&db).await;
469- let other = UserId::from_key(&Ulid::generate().to_string());459+ let other = a_user(&db).await;
470- let teacher = UserId::from_key(&Ulid::generate().to_string());460+ let teacher = a_user(&db).await;
471 461
472 let pending = insert(&db, question(&asker)).await.unwrap();462 let pending = insert(&db, question(&asker)).await.unwrap();
473 let published = insert(&db, question(&other)).await.unwrap();463 let published = insert(&db, question(&other)).await.unwrap();
@@ -488,9 +478,9 @@ mod tests {
488 478
489 #[tokio::test]479 #[tokio::test]
490 async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() {480 async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() {
491- let db = database::init_mem().await.unwrap();481+ let (db, _leases) = database::init_test_db().await;
492- let asker = UserId::from_key(&Ulid::generate().to_string());482+ let asker = a_user(&db).await;
493- let teacher = UserId::from_key(&Ulid::generate().to_string());483+ let teacher = a_user(&db).await;
494 let png = FileContentType::try_new("image/png").unwrap();484 let png = FileContentType::try_new("image/png").unwrap();
495 485
496 let q = insert(&db, question(&asker)).await.unwrap();486 let q = insert(&db, question(&asker)).await.unwrap();
@@ -535,9 +525,9 @@ mod tests {
535 525
536 #[tokio::test]526 #[tokio::test]
537 async fn delete_cascades_solutions_and_returns_the_row() {527 async fn delete_cascades_solutions_and_returns_the_row() {
538- let db = database::init_mem().await.unwrap();528+ let (db, _leases) = database::init_test_db().await;
539- let asker = UserId::from_key(&Ulid::generate().to_string());529+ let asker = a_user(&db).await;
540- let helper = UserId::from_key(&Ulid::generate().to_string());530+ let helper = a_user(&db).await;
541 531
542 let q = insert(&db, question(&asker)).await.unwrap();532 let q = insert(&db, question(&asker)).await.unwrap();
543 let offered = crate::db::solution::insert(533 let offered = crate::db::solution::insert(
@@ -609,8 +599,8 @@ mod tests {
609 599
610 let (mut solutions, mut swept, mut delete_500) = (0, 0, 0);600 let (mut solutions, mut swept, mut delete_500) = (0, 0, 0);
611 for round in 0..4 {601 for round in 0..4 {
612- let asker = UserId::from_key(&Ulid::generate().to_string());602+ let asker = a_user(&db).await;
613- let helper = UserId::from_key(&Ulid::generate().to_string());603+ let helper = a_user(&db).await;
614 let q = insert(&db, question(&asker)).await.unwrap();604 let q = insert(&db, question(&asker)).await.unwrap();
615 let id = q.get_id().clone();605 let id = q.get_id().clone();
616 606
src/db/profile.rsmodified+3 -3
@@ -126,7 +126,7 @@ mod tests {
126 VALUES ($1, $2, 1000, 3000), ($3, $2, 5000, 6000)",126 VALUES ($1, $2, 1000, 3000), ($3, $2, 5000, 6000)",
127 )127 )
128 .bind(uuid::Uuid::now_v7())128 .bind(uuid::Uuid::now_v7())
129- .bind(user.uuid())129+ .bind(user.get_id().uuid())
130 .bind(uuid::Uuid::now_v7())130 .bind(uuid::Uuid::now_v7())
131 .execute(&db)131 .execute(&db)
132 .await132 .await
@@ -136,7 +136,7 @@ mod tests {
136 "INSERT INTO pomodoro_session (id, app_user, started_at) VALUES ($1, $2, 9000)",136 "INSERT INTO pomodoro_session (id, app_user, started_at) VALUES ($1, $2, 9000)",
137 )137 )
138 .bind(uuid::Uuid::now_v7())138 .bind(uuid::Uuid::now_v7())
139- .bind(user.uuid())139+ .bind(user.get_id().uuid())
140 .execute(&db)140 .execute(&db)
141 .await141 .await
142 .unwrap();142 .unwrap();
@@ -158,7 +158,7 @@ mod tests {
158 VALUES ($1, $2, 5000, 1000)",158 VALUES ($1, $2, 5000, 1000)",
159 )159 )
160 .bind(uuid::Uuid::now_v7())160 .bind(uuid::Uuid::now_v7())
161- .bind(user.uuid())161+ .bind(user.get_id().uuid())
162 .execute(&db)162 .execute(&db)
163 .await163 .await
164 .unwrap();164 .unwrap();
src/db/question_image.rsmodified+4 -4
@@ -248,7 +248,7 @@ mod tests {
248 248
249 #[tokio::test]249 #[tokio::test]
250 async fn upsert_replaces_per_slot() {250 async fn upsert_replaces_per_slot() {
251- let db = crate::database::init_mem().await.unwrap();251+ let (db, _leases) = crate::database::init_test_db().await;
252 let exam = exam_row(&db).await;252 let exam = exam_row(&db).await;
253 let question = ExamQuestionId::generate();253 let question = ExamQuestionId::generate();
254 let ids = choice_ids();254 let ids = choice_ids();
@@ -293,7 +293,7 @@ mod tests {
293 /// options keeps exactly their pictures, and drops only the removed one's.293 /// options keeps exactly their pictures, and drops only the removed one's.
294 #[tokio::test]294 #[tokio::test]
295 async fn only_the_dropped_options_lose_their_pictures() {295 async fn only_the_dropped_options_lose_their_pictures() {
296- let db = crate::database::init_mem().await.unwrap();296+ let (db, _leases) = crate::database::init_test_db().await;
297 let exam = exam_row(&db).await;297 let exam = exam_row(&db).await;
298 let question = ExamQuestionId::generate();298 let question = ExamQuestionId::generate();
299 let ids = choice_ids();299 let ids = choice_ids();
@@ -335,7 +335,7 @@ mod tests {
335 335
336 #[tokio::test]336 #[tokio::test]
337 async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() {337 async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() {
338- let db = crate::database::init_mem().await.unwrap();338+ let (db, _leases) = crate::database::init_test_db().await;
339 let exam = exam_row(&db).await;339 let exam = exam_row(&db).await;
340 let question = ExamQuestionId::generate();340 let question = ExamQuestionId::generate();
341 let ids = choice_ids();341 let ids = choice_ids();
@@ -362,7 +362,7 @@ mod tests {
362 362
363 #[tokio::test]363 #[tokio::test]
364 async fn exam_listing_scopes_by_exam() {364 async fn exam_listing_scopes_by_exam() {
365- let db = crate::database::init_mem().await.unwrap();365+ let (db, _leases) = crate::database::init_test_db().await;
366 let exam_a = exam_row(&db).await;366 let exam_a = exam_row(&db).await;
367 let exam_b = exam_row(&db).await;367 let exam_b = exam_row(&db).await;
368 upsert(368 upsert(
src/db/rag_output.rsmodified+3 -3
@@ -207,7 +207,7 @@ mod tests {
207 /// the note cascade takes every row of the note with it.207 /// the note cascade takes every row of the note with it.
208 #[tokio::test]208 #[tokio::test]
209 async fn create_reads_back_and_cascades_from_the_note() {209 async fn create_reads_back_and_cascades_from_the_note() {
210- let db = crate::database::init_mem().await.unwrap();210+ let (db, _leases) = crate::database::init_test_db().await;
211 let note = note_of(&db, "n").await;211 let note = note_of(&db, "n").await;
212 let file = a_file(&db, &note).await;212 let file = a_file(&db, &note).await;
213 let row = create(213 let row = create(
@@ -231,7 +231,7 @@ mod tests {
231 /// drops a row built from a file that is gone.231 /// drops a row built from a file that is gone.
232 #[tokio::test]232 #[tokio::test]
233 async fn replace_is_newest_wins_and_source_cascade_drops() {233 async fn replace_is_newest_wins_and_source_cascade_drops() {
234- let db = crate::database::init_mem().await.unwrap();234+ let (db, _leases) = crate::database::init_test_db().await;
235 let note = note_of(&db, "n").await;235 let note = note_of(&db, "n").await;
236 let file = a_file(&db, &note).await;236 let file = a_file(&db, &note).await;
237 let first = create(237 let first = create(
@@ -265,7 +265,7 @@ mod tests {
265 /// Deleting one row returns it; deleting it again is a 404.265 /// Deleting one row returns it; deleting it again is a 404.
266 #[tokio::test]266 #[tokio::test]
267 async fn delete_returns_the_row_then_refuses() {267 async fn delete_returns_the_row_then_refuses() {
268- let db = crate::database::init_mem().await.unwrap();268+ let (db, _leases) = crate::database::init_test_db().await;
269 let note = note_of(&db, "n").await;269 let note = note_of(&db, "n").await;
270 let row = create(&db, note.get_id(), note.get_course(), Vec::new(), json!({}))270 let row = create(&db, note.get_id(), note.get_course(), Vec::new(), json!({}))
271 .await271 .await
src/db/session.rsmodified+19 -6
@@ -87,14 +87,27 @@ mod tests {
87 87
88 #[tokio::test]88 #[tokio::test]
89 async fn purge_expired_removes_only_past_sessions() {89 async fn purge_expired_removes_only_past_sessions() {
90- let db = crate::database::init_mem().await.unwrap();90+ let (db, _leases) = crate::database::init_test_db().await;
91- db.query(91+ // The session's owner is a foreign key now: a real `app_user` row
92- "CREATE session SET user = type::record('user', 'u'), token = 'past', expires_at = 1;92+ // under the fixture's fixed key, then two rows either side of `now`.
93- CREATE session SET user = type::record('user', 'u'), token = 'future', expires_at = 99999999999999;",93+ let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cab0");
94+ sqlx::query(
95+ "INSERT INTO app_user (id, username, password_hash) \
96+ VALUES ($1, 'purge-fixture', 'x')",
94 )97 )
98+ .bind(user.uuid())
99+ .execute(&db)
100+ .await
101+ .unwrap();
102+ sqlx::query(
103+ "INSERT INTO user_session (id, app_user, token, expires_at) \
104+ VALUES ($1, $3, 'past', 1), ($2, $3, 'future', 99999999999999)",
105+ )
106+ .bind(UserId::generate().uuid())
107+ .bind(UserId::generate().uuid())
108+ .bind(user.uuid())
109+ .execute(&db)
95 .await110 .await
96- .unwrap()
97- .check()
98 .unwrap();111 .unwrap();
99 112
100 assert_eq!(purge_expired(&db).await.unwrap(), 1);113 assert_eq!(purge_expired(&db).await.unwrap(), 1);
src/db/session_attendance.rsmodified+28 -27
@@ -299,7 +299,7 @@ pub async fn remove(
299 mod tests {299 mod tests {
300 use super::*;300 use super::*;
301 use crate::constant::DEFAULT_ATTENDANCE_STATUSES;301 use crate::constant::DEFAULT_ATTENDANCE_STATUSES;
302- use crate::database::init_mem;302+ use crate::database::init_test_db;
303 use crate::domain::course_session::SessionTopic;303 use crate::domain::course_session::SessionTopic;
304 use crate::domain::role::Role;304 use crate::domain::role::Role;
305 305
@@ -307,15 +307,19 @@ mod tests {
307 /// writes nothing at all to a record that does not exist), and the live307 /// writes nothing at all to a record that does not exist), and the live
308 /// role is what decides whether the attended counter moves.308 /// role is what decides whether the attended counter moves.
309 async fn a_user(key: &str, role: Role, db: &Database) -> UserId {309 async fn a_user(key: &str, role: Role, db: &Database) -> UserId {
310- let user = UserId::from_key(key);310+ // Minted fresh: the id is a real parent row now, and the minted uuid
311- db.query("CREATE $usr SET username = $name, password_hash = 'x', role = $role")311+ // keeps repeated calls (same label, new person) collision-free.
312- .bind(("usr", user.record()))312+ let user = UserId::generate();
313- .bind(("name", key.to_string()))313+ sqlx::query(
314- .bind(("role", role))314+ "INSERT INTO app_user (id, username, password_hash, role) \
315- .await315+ VALUES ($1, $2, 'x', $3)",
316- .unwrap()316+ )
317- .check()317+ .bind(user.uuid())
318- .unwrap();318+ .bind(format!("{key}-{}", &user.key()[..8]))
319+ .bind(role.as_str())
320+ .execute(db)
321+ .await
322+ .unwrap();
319 user323 user
320 }324 }
321 325
@@ -376,7 +380,7 @@ mod tests {
376 /// a re-mark and a swap within the same class are both no-ops.380 /// a re-mark and a swap within the same class are both no-ops.
377 #[tokio::test]381 #[tokio::test]
378 async fn the_counter_follows_every_crossing_and_no_other_move() {382 async fn the_counter_follows_every_crossing_and_no_other_move() {
379- let db = init_mem().await.unwrap();383+ let (db, _leases) = init_test_db().await;
380 let teacher = a_teacher("t", &db).await;384 let teacher = a_teacher("t", &db).await;
381 let student = a_student("s", &db).await;385 let student = a_student("s", &db).await;
382 let session = a_session(&teacher, &db).await;386 let session = a_session(&teacher, &db).await;
@@ -410,7 +414,7 @@ mod tests {
410 /// once: the whole roster, and every later correction, ride the same stamp.414 /// once: the whole roster, and every later correction, ride the same stamp.
411 #[tokio::test]415 #[tokio::test]
412 async fn the_first_roll_call_counts_the_lesson_once() {416 async fn the_first_roll_call_counts_the_lesson_once() {
413- let db = init_mem().await.unwrap();417+ let (db, _leases) = init_test_db().await;
414 let teacher = a_teacher("t", &db).await;418 let teacher = a_teacher("t", &db).await;
415 let other = a_teacher("o", &db).await;419 let other = a_teacher("o", &db).await;
416 let session = a_session(&teacher, &db).await;420 let session = a_session(&teacher, &db).await;
@@ -439,7 +443,7 @@ mod tests {
439 /// two hundred lessons for next week and hold all of them this afternoon.443 /// two hundred lessons for next week and hold all of them this afternoon.
440 #[tokio::test]444 #[tokio::test]
441 async fn a_lesson_that_has_not_started_holds_nothing_yet() {445 async fn a_lesson_that_has_not_started_holds_nothing_yet() {
442- let db = init_mem().await.unwrap();446+ let (db, _leases) = init_test_db().await;
443 let teacher = a_teacher("t", &db).await;447 let teacher = a_teacher("t", &db).await;
444 let student = a_student("s", &db).await;448 let student = a_student("s", &db).await;
445 let next_week =449 let next_week =
@@ -474,7 +478,7 @@ mod tests {
474 /// lesson held.478 /// lesson held.
475 #[tokio::test]479 #[tokio::test]
476 async fn a_teacher_marked_present_earns_nothing_for_attending() {480 async fn a_teacher_marked_present_earns_nothing_for_attending() {
477- let db = init_mem().await.unwrap();481+ let (db, _leases) = init_test_db().await;
478 let teacher = a_teacher("t", &db).await;482 let teacher = a_teacher("t", &db).await;
479 let session = a_session(&teacher, &db).await;483 let session = a_session(&teacher, &db).await;
480 484
@@ -501,7 +505,7 @@ mod tests {
501 /// Two lessons are two counts — the counter is per row, not per student.505 /// Two lessons are two counts — the counter is per row, not per student.
502 #[tokio::test]506 #[tokio::test]
503 async fn each_lesson_counts_once_for_the_student_marked() {507 async fn each_lesson_counts_once_for_the_student_marked() {
504- let db = init_mem().await.unwrap();508+ let (db, _leases) = init_test_db().await;
505 let teacher = a_teacher("t", &db).await;509 let teacher = a_teacher("t", &db).await;
506 let student = a_student("s", &db).await;510 let student = a_student("s", &db).await;
507 let other = a_student("o", &db).await;511 let other = a_student("o", &db).await;
@@ -519,7 +523,7 @@ mod tests {
519 /// that was counted.523 /// that was counted.
520 #[tokio::test]524 #[tokio::test]
521 async fn removing_a_row_gives_back_only_what_it_took() {525 async fn removing_a_row_gives_back_only_what_it_took() {
522- let db = init_mem().await.unwrap();526+ let (db, _leases) = init_test_db().await;
523 let teacher = a_teacher("t", &db).await;527 let teacher = a_teacher("t", &db).await;
524 let student = a_student("s", &db).await;528 let student = a_student("s", &db).await;
525 529
@@ -562,7 +566,7 @@ mod tests {
562 /// a stale row starts from, the counter never goes negative.566 /// a stale row starts from, the counter never goes negative.
563 #[tokio::test]567 #[tokio::test]
564 async fn the_counter_never_goes_below_zero() {568 async fn the_counter_never_goes_below_zero() {
565- let db = init_mem().await.unwrap();569+ let (db, _leases) = init_test_db().await;
566 let teacher = a_teacher("t", &db).await;570 let teacher = a_teacher("t", &db).await;
567 let student = a_student("s", &db).await;571 let student = a_student("s", &db).await;
568 572
@@ -577,14 +581,11 @@ mod tests {
577 .unwrap();581 .unwrap();
578 sessions.push(session);582 sessions.push(session);
579 }583 }
580- db.query(format!(584+ sqlx::query("UPDATE app_user SET lessons_attended_total = 0 WHERE id = $1")
581- "UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = 0"585+ .bind(student.uuid())
582- ))586+ .execute(&db)
583- .bind(("usr", student.record()))587+ .await
584- .await588+ .unwrap();
585- .unwrap()
586- .check()
587- .unwrap();
588 589
589 for session in &sessions {590 for session in &sessions {
590 mark(&db, session, &student, status("absent"), &teacher)591 mark(&db, session, &student, status("absent"), &teacher)
@@ -601,7 +602,7 @@ mod tests {
601 /// the ruling every other counter here carries.602 /// the ruling every other counter here carries.
602 #[tokio::test]603 #[tokio::test]
603 async fn deleting_the_session_leaves_the_counters_alone() {604 async fn deleting_the_session_leaves_the_counters_alone() {
604- let db = init_mem().await.unwrap();605+ let (db, _leases) = init_test_db().await;
605 let teacher = a_teacher("t", &db).await;606 let teacher = a_teacher("t", &db).await;
606 let student = a_student("s", &db).await;607 let student = a_student("s", &db).await;
607 let session = a_session(&teacher, &db).await;608 let session = a_session(&teacher, &db).await;
@@ -620,7 +621,7 @@ mod tests {
620 /// a count behind either.621 /// a count behind either.
621 #[tokio::test]622 #[tokio::test]
622 async fn a_refused_mark_moves_nothing() {623 async fn a_refused_mark_moves_nothing() {
623- let db = init_mem().await.unwrap();624+ let (db, _leases) = init_test_db().await;
624 let teacher = a_teacher("t", &db).await;625 let teacher = a_teacher("t", &db).await;
625 let student = a_student("s", &db).await;626 let student = a_student("s", &db).await;
626 let session = a_session(&teacher, &db).await;627 let session = a_session(&teacher, &db).await;
src/db/solution.rsmodified+26 -12
@@ -254,22 +254,36 @@ pub async fn delete(db: &Database, solution: Solution) -> Result<Solution, AppEr
254 254
255 #[cfg(test)]255 #[cfg(test)]
256 mod tests {256 mod tests {
257- use ulid::Ulid;
258-
259 use super::*;257 use super::*;
260 use crate::database;258 use crate::database;
261 use crate::domain::pool_question::{PoolQuestion, PoolQuestionBody, PoolQuestionTitle};259 use crate::domain::pool_question::{PoolQuestion, PoolQuestionBody, PoolQuestionTitle};
262 use crate::domain::timestamp::Timestamp;260 use crate::domain::timestamp::Timestamp;
263 use crate::domain::user::UserId;261 use crate::domain::user::UserId;
264 262
263+ /// A real `app_user` row: askers and authors are foreign keys now.
264+ async fn a_person(db: &Database, label: &str) -> UserId {
265+ let user = UserId::generate();
266+ sqlx::query(
267+ "INSERT INTO app_user (id, username, password_hash) \
268+ VALUES ($1, $2, 'x')",
269+ )
270+ .bind(user.uuid())
271+ .bind(format!("{label}-{}", &user.key()[..8]))
272+ .execute(db)
273+ .await
274+ .unwrap();
275+ user
276+ }
277+
265 /// A real question row: offering a solution moves its question's278 /// A real question row: offering a solution moves its question's
266 /// `asked_at` (that is what keeps a solution from outliving its question),279 /// `asked_at` (that is what keeps a solution from outliving its question),
267 /// so a minted id nothing wrote is a 404.280 /// so a minted id nothing wrote is a 404.
268 async fn question_row(db: &Database) -> PoolQuestionId {281 async fn question_row(db: &Database) -> PoolQuestionId {
282+ let asker = a_person(db, "asker").await;
269 crate::db::pool_question::insert(283 crate::db::pool_question::insert(
270 db,284 db,
271 PoolQuestion::new(285 PoolQuestion::new(
272- &UserId::from_key(&Ulid::generate().to_string()),286+ &asker,
273 PoolQuestionTitle::try_new("soru").unwrap(),287 PoolQuestionTitle::try_new("soru").unwrap(),
274 PoolQuestionBody::try_new("neden").unwrap(),288 PoolQuestionBody::try_new("neden").unwrap(),
275 ),289 ),
@@ -282,10 +296,10 @@ mod tests {
282 296
283 #[tokio::test]297 #[tokio::test]
284 async fn rows_scope_to_their_question_and_list_oldest_first() {298 async fn rows_scope_to_their_question_and_list_oldest_first() {
285- let db = database::init_mem().await.unwrap();299+ let (db, _leases) = database::init_test_db().await;
286 let question_a = question_row(&db).await;300 let question_a = question_row(&db).await;
287 let question_b = question_row(&db).await;301 let question_b = question_row(&db).await;
288- let author = UserId::from_key(&Ulid::generate().to_string());302+ let author = a_person(&db, "author").await;
289 303
290 // Distinct offer times so the assertion pins the real contract —304 // Distinct offer times so the assertion pins the real contract —
291 // older `offered_at` sorts first — not the same-millisecond `id`305 // older `offered_at` sorts first — not the same-millisecond `id`
@@ -341,7 +355,7 @@ mod tests {
341 355
342 #[tokio::test]356 #[tokio::test]
343 async fn image_set_replace_clear_report_the_replaced_blob() {357 async fn image_set_replace_clear_report_the_replaced_blob() {
344- let db = database::init_mem().await.unwrap();358+ let (db, _leases) = database::init_test_db().await;
345 let question = question_row(&db).await;359 let question = question_row(&db).await;
346 let author = UserId::from_key(&Ulid::generate().to_string());360 let author = UserId::from_key(&Ulid::generate().to_string());
347 let png = FileContentType::try_new("image/png").unwrap();361 let png = FileContentType::try_new("image/png").unwrap();
@@ -402,7 +416,7 @@ mod tests {
402 416
403 #[tokio::test]417 #[tokio::test]
404 async fn set_body_edits_in_place() {418 async fn set_body_edits_in_place() {
405- let db = database::init_mem().await.unwrap();419+ let (db, _leases) = database::init_test_db().await;
406 let question = question_row(&db).await;420 let question = question_row(&db).await;
407 let author = UserId::from_key(&Ulid::generate().to_string());421 let author = UserId::from_key(&Ulid::generate().to_string());
408 422
@@ -443,11 +457,11 @@ mod tests {
443 457
444 #[tokio::test]458 #[tokio::test]
445 async fn counts_for_groups_per_question() {459 async fn counts_for_groups_per_question() {
446- let db = database::init_mem().await.unwrap();460+ let (db, _leases) = database::init_test_db().await;
447 let two = question_row(&db).await;461 let two = question_row(&db).await;
448 let one = question_row(&db).await;462 let one = question_row(&db).await;
449 let none = question_row(&db).await;463 let none = question_row(&db).await;
450- let author = UserId::from_key(&Ulid::generate().to_string());464+ let author = a_person(&db, "author").await;
451 465
452 for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] {466 for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] {
453 for body in bodies {467 for body in bodies {
@@ -463,10 +477,10 @@ mod tests {
463 let counts = counts_for(&db, &[two.clone(), one.clone(), none.clone()])477 let counts = counts_for(&db, &[two.clone(), one.clone(), none.clone()])
464 .await478 .await
465 .unwrap();479 .unwrap();
466- assert_eq!(counts.get(two.key()), Some(&2));480+ assert_eq!(counts.get(two.key().as_str()), Some(&2));
467- assert_eq!(counts.get(one.key()), Some(&1));481+ assert_eq!(counts.get(one.key().as_str()), Some(&1));
468 // No solutions = no entry; the caller reads the miss as zero.482 // No solutions = no entry; the caller reads the miss as zero.
469- assert_eq!(counts.get(none.key()), None);483+ assert_eq!(counts.get(none.key().as_str()), None);
470 assert!(counts_for(&db, &[]).await.unwrap().is_empty());484 assert!(counts_for(&db, &[]).await.unwrap().is_empty());
471 }485 }
472 }486 }
src/db/subject.rsmodified+18 -14
@@ -133,7 +133,9 @@ pub async fn update(
133 /// The bank's subject is optional metadata, and blocking on it was a dead133 /// The bank's subject is optional metadata, and blocking on it was a dead
134 /// end — only the template's owner may re-tag it, so a manager could never134 /// end — only the template's owner may re-tag it, so a manager could never
135 /// clear their own 409, and a private template raising it leaked its135 /// clear their own 409, and a private template raising it leaked its
136-/// existence. Its cascade runs *after* the guarded delete, so a refused136+/// existence. Its cascade clears the templates before the delete — the FK on
137+/// `bank_question.subject` refuses the parent delete while a template still
138+/// points at it — and the one transaction rolls everything back, so a refused
137 /// delete leaves every template's subject where it was.139 /// delete leaves every template's subject where it was.
138 pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError> {140 pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError> {
139 crate::database::tx_with_retry(db, false, async move |tx| {141 crate::database::tx_with_retry(db, false, async move |tx| {
@@ -157,6 +159,20 @@ pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError
157 "homework still references this subject — re-tag or delete it first",159 "homework still references this subject — re-tag or delete it first",
158 ));160 ));
159 }161 }
162+ // The bank's cascade clears the templates *before* the delete:
163+ // `bank_question.subject` carries a real foreign key, so a template
164+ // still pointing at this row makes the `DELETE` itself fail (23503)
165+ // — the old store had no enforced reference to release. The guard
166+ // above has already decided, and the transaction makes the pair
167+ // atomic, so ordering costs nothing: a refused delete (an error
168+ // raised anywhere above) rolls the whole thing back and every
169+ // template's subject stays where it was.
170+ sqlx::query!(
171+ r#"UPDATE bank_question SET subject = NULL WHERE subject = $1"#,
172+ subject.id.uuid(),
173+ )
174+ .execute(&mut *tx)
175+ .await?;
160 let deleted = sqlx::query_as!(176 let deleted = sqlx::query_as!(
161 Subject,177 Subject,
162 r#"DELETE FROM subject WHERE id = $1178 r#"DELETE FROM subject WHERE id = $1
@@ -168,12 +184,6 @@ pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError
168 )184 )
169 .fetch_one(&mut *tx)185 .fetch_one(&mut *tx)
170 .await?;186 .await?;
171- sqlx::query!(
172- r#"UPDATE bank_question SET subject = NULL WHERE subject = $1"#,
173- subject.id.uuid(),
174- )
175- .execute(&mut *tx)
176- .await?;
177 Ok(deleted)187 Ok(deleted)
178 })188 })
179 .await189 .await
@@ -196,7 +206,6 @@ mod tests {
196 /// Mutation-tested: with the bare `db.create` this shipped with, all four206 /// Mutation-tested: with the bare `db.create` this shipped with, all four
197 /// rounds orphan.207 /// rounds orphan.
198 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]208 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
199- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
200 async fn a_subject_never_outlives_its_course() {209 async fn a_subject_never_outlives_its_course() {
201 fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {210 fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
202 tokio::spawn(async move {211 tokio::spawn(async move {
@@ -210,12 +219,7 @@ mod tests {
210 .map(|_| ())219 .map(|_| ())
211 })220 })
212 }221 }
213- crate::db::course::assert_no_child_outlives_a_course_delete(222+ crate::db::course::assert_no_child_outlives_a_course_delete("subject", make).await;
214- "subject_orphan_race",
215- SUBJECT_TABLE,
216- make,
217- )
218- .await;
219 }223 }
220 224
221 /// GUARD, not a retry measurement — read the last paragraph before225 /// GUARD, not a retry measurement — read the last paragraph before
src/db/term.rsmodified+2 -2
@@ -173,7 +173,7 @@ mod tests {
173 /// refuse it with the same error, having written nothing.173 /// refuse it with the same error, having written nothing.
174 #[tokio::test]174 #[tokio::test]
175 async fn a_moved_end_is_refused_against_the_stored_other_end() {175 async fn a_moved_end_is_refused_against_the_stored_other_end() {
176- let db = crate::database::init_mem().await.unwrap();176+ let (db, _leases) = crate::database::init_test_db().await;
177 let at = Timestamp::from_millis;177 let at = Timestamp::from_millis;
178 let term = create(&db, TermName::try_new("2026").unwrap(), at(100), at(200))178 let term = create(&db, TermName::try_new("2026").unwrap(), at(100), at(200))
179 .await179 .await
@@ -202,7 +202,7 @@ mod tests {
202 /// tie-break on identical `starts_at` — stored read-back, then page by page.202 /// tie-break on identical `starts_at` — stored read-back, then page by page.
203 #[tokio::test]203 #[tokio::test]
204 async fn identical_starts_at_still_pages_each_term_exactly_once() {204 async fn identical_starts_at_still_pages_each_term_exactly_once() {
205- let db = crate::database::init_mem().await.unwrap();205+ let (db, _leases) = crate::database::init_test_db().await;
206 let at = Timestamp::from_millis;206 let at = Timestamp::from_millis;
207 let mut minted = Vec::new();207 let mut minted = Vec::new();
208 for i in 0..12 {208 for i in 0..12 {
src/db/work_entry.rsmodified+11 -7
@@ -195,21 +195,25 @@ pub async fn remove(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>
195 195
196 #[cfg(test)]196 #[cfg(test)]
197 mod tests {197 mod tests {
198- use ulid::Ulid;
199-
200 use super::*;198 use super::*;
201 use crate::database;199 use crate::database;
202 200
203 #[tokio::test]201 #[tokio::test]
204 async fn check_in_is_exclusive_until_check_out() {202 async fn check_in_is_exclusive_until_check_out() {
205- let db = database::init_mem().await.unwrap();203+ let (db, _leases) = database::init_test_db().await;
206- // A `record<user>` column checks the table of the id, not row204+ // The stint's owner is a foreign key now: a real `app_user` row.
207- // existence — a fabricated id keeps this test free of user ceremony.205+ let user = UserId::generate();
208- let user = UserId::from_key(&Ulid::generate().to_string());206+ sqlx::query(
207+ "INSERT INTO app_user (id, username, password_hash) \
208+ VALUES ($1, 'work-fixture', 'x')",
209+ )
210+ .bind(user.uuid())
211+ .execute(&db)
212+ .await
213+ .unwrap();
209 214
210 let open = check_in(&db, &user).await.unwrap();215 let open = check_in(&db, &user).await.unwrap();
211 assert!(open.is_open());216 assert!(open.is_open());
212- assert_eq!(open.get_id().key(), format!("open_{}", user.key()));
213 217
214 // Second check-in must not create a second stint or reset the clock.218 // Second check-in must not create a second stint or reset the clock.
215 let dup = check_in(&db, &user).await;219 let dup = check_in(&db, &user).await;
src/service/appointment.rsmodified+9 -9
@@ -392,7 +392,7 @@ fn contended() -> AppError {
392 #[cfg(test)]392 #[cfg(test)]
393 mod tests {393 mod tests {
394 use super::*;394 use super::*;
395- use crate::database::{Database, init_mem};395+ use crate::database::{Database, init_test_db};
396 use crate::service::appointment_slot;396 use crate::service::appointment_slot;
397 397
398 fn at(millis: i64) -> Timestamp {398 fn at(millis: i64) -> Timestamp {
@@ -406,7 +406,7 @@ mod tests {
406 406
407 #[tokio::test]407 #[tokio::test]
408 async fn window_prefers_a_proposal_over_the_slot() {408 async fn window_prefers_a_proposal_over_the_slot() {
409- let db = init_mem().await.unwrap();409+ let (db, _leases) = init_test_db().await;
410 let teacher = UserId::from_key("t1");410 let teacher = UserId::from_key("t1");
411 let (starts_at, ends_at) = (soon(60_000), soon(120_000));411 let (starts_at, ends_at) = (soon(60_000), soon(120_000));
412 let slot = appointment_slot::create(&db, &teacher, starts_at, ends_at, None)412 let slot = appointment_slot::create(&db, &teacher, starts_at, ends_at, None)
@@ -431,7 +431,7 @@ mod tests {
431 /// to undo the resulting meeting, so the booking would be stuck for good.431 /// to undo the resulting meeting, so the booking would be stuck for good.
432 #[tokio::test]432 #[tokio::test]
433 async fn a_started_slot_cannot_be_booked() {433 async fn a_started_slot_cannot_be_booked() {
434- let db = init_mem().await.unwrap();434+ let (db, _leases) = init_test_db().await;
435 let teacher = UserId::from_key("t1");435 let teacher = UserId::from_key("t1");
436 let reason = || AppointmentReason::try_new("görüşme").unwrap();436 let reason = || AppointmentReason::try_new("görüşme").unwrap();
437 let started = appointment_slot::create(&db, &teacher, soon(-30_000), soon(60_000), None)437 let started = appointment_slot::create(&db, &teacher, soon(-30_000), soon(60_000), None)
@@ -456,7 +456,7 @@ mod tests {
456 /// come and gone cannot be accepted — the meeting would be uncancellable.456 /// come and gone cannot be accepted — the meeting would be uncancellable.
457 #[tokio::test]457 #[tokio::test]
458 async fn a_started_proposal_cannot_be_accepted() {458 async fn a_started_proposal_cannot_be_accepted() {
459- let db = init_mem().await.unwrap();459+ let (db, _leases) = init_test_db().await;
460 let teacher = UserId::from_key("t1");460 let teacher = UserId::from_key("t1");
461 let student = UserId::from_key("s1");461 let student = UserId::from_key("s1");
462 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)462 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
@@ -544,7 +544,7 @@ mod tests {
544 /// primitive itself with the exact stale snapshot the race produces.544 /// primitive itself with the exact stale snapshot the race produces.
545 #[tokio::test]545 #[tokio::test]
546 async fn a_decision_built_on_a_stale_snapshot_never_lands() {546 async fn a_decision_built_on_a_stale_snapshot_never_lands() {
547- let db = init_mem().await.unwrap();547+ let (db, _leases) = init_test_db().await;
548 let teacher = UserId::from_key("t1");548 let teacher = UserId::from_key("t1");
549 let student = UserId::from_key("s1");549 let student = UserId::from_key("s1");
550 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)550 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
@@ -633,7 +633,7 @@ mod tests {
633 /// second claim succeed and this fail (mutation-proved).633 /// second claim succeed and this fail (mutation-proved).
634 #[tokio::test]634 #[tokio::test]
635 async fn a_concurrent_claim_cannot_take_a_booked_slot() {635 async fn a_concurrent_claim_cannot_take_a_booked_slot() {
636- let db = init_mem().await.unwrap();636+ let (db, _leases) = init_test_db().await;
637 let teacher = UserId::from_key("t1");637 let teacher = UserId::from_key("t1");
638 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)638 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
639 .await639 .await
@@ -674,7 +674,7 @@ mod tests {
674 /// bumped the counter would strand the slot forever.674 /// bumped the counter would strand the slot forever.
675 #[tokio::test]675 #[tokio::test]
676 async fn a_refused_booking_moves_nothing() {676 async fn a_refused_booking_moves_nothing() {
677- let db = init_mem().await.unwrap();677+ let (db, _leases) = init_test_db().await;
678 let teacher = UserId::from_key("t1");678 let teacher = UserId::from_key("t1");
679 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)679 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
680 .await680 .await
@@ -711,7 +711,7 @@ mod tests {
711 /// cancel that moved one without the other would strand the slot forever.711 /// cancel that moved one without the other would strand the slot forever.
712 #[tokio::test]712 #[tokio::test]
713 async fn cancelling_hands_the_seat_back_with_the_status() {713 async fn cancelling_hands_the_seat_back_with_the_status() {
714- let db = init_mem().await.unwrap();714+ let (db, _leases) = init_test_db().await;
715 let teacher = UserId::from_key("t1");715 let teacher = UserId::from_key("t1");
716 let student = UserId::from_key("s1");716 let student = UserId::from_key("s1");
717 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)717 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
@@ -749,7 +749,7 @@ mod tests {
749 /// Occupancy frees on reject, so the slot can be re-booked.749 /// Occupancy frees on reject, so the slot can be re-booked.
750 #[tokio::test]750 #[tokio::test]
751 async fn rejecting_frees_the_slot_for_re_booking() {751 async fn rejecting_frees_the_slot_for_re_booking() {
752- let db = init_mem().await.unwrap();752+ let (db, _leases) = init_test_db().await;
753 let teacher = UserId::from_key("t1");753 let teacher = UserId::from_key("t1");
754 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)754 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
755 .await755 .await
src/service/appointment_slot.rsmodified+8 -8
@@ -208,7 +208,7 @@ mod tests {
208 208
209 #[tokio::test]209 #[tokio::test]
210 async fn a_publish_shares_one_series_and_orders_its_ids() {210 async fn a_publish_shares_one_series_and_orders_its_ids() {
211- let db = crate::database::init_mem().await.unwrap();211+ let (db, _leases) = crate::database::init_test_db().await;
212 let teacher = UserId::from_key("t1");212 let teacher = UserId::from_key("t1");
213 let slots = publish_weekly(213 let slots = publish_weekly(
214 &db,214 &db,
@@ -236,7 +236,7 @@ mod tests {
236 236
237 #[tokio::test]237 #[tokio::test]
238 async fn overlapping_publish_is_refused_but_touching_is_allowed() {238 async fn overlapping_publish_is_refused_but_touching_is_allowed() {
239- let db = crate::database::init_mem().await.unwrap();239+ let (db, _leases) = crate::database::init_test_db().await;
240 let teacher = UserId::from_key("t1");240 let teacher = UserId::from_key("t1");
241 create(&db, &teacher, at(1_000), at(2_000), None)241 create(&db, &teacher, at(1_000), at(2_000), None)
242 .await242 .await
@@ -265,7 +265,7 @@ mod tests {
265 265
266 #[tokio::test]266 #[tokio::test]
267 async fn weekly_publish_overlapping_an_existing_slot_writes_nothing() {267 async fn weekly_publish_overlapping_an_existing_slot_writes_nothing() {
268- let db = crate::database::init_mem().await.unwrap();268+ let (db, _leases) = crate::database::init_test_db().await;
269 let teacher = UserId::from_key("t1");269 let teacher = UserId::from_key("t1");
270 // A lone slot on the third week of the coming series.270 // A lone slot on the third week of the coming series.
271 create(271 create(
@@ -301,7 +301,7 @@ mod tests {
301 /// the batch's boundaries must still be allowed.301 /// the batch's boundaries must still be allowed.
302 #[tokio::test]302 #[tokio::test]
303 async fn the_batch_wide_conflict_read_still_sees_the_last_week_and_lets_touching_through() {303 async fn the_batch_wide_conflict_read_still_sees_the_last_week_and_lets_touching_through() {
304- let db = crate::database::init_mem().await.unwrap();304+ let (db, _leases) = crate::database::init_test_db().await;
305 let teacher = UserId::from_key("t1");305 let teacher = UserId::from_key("t1");
306 let last = 1_000 + 4 * MILLIS_PER_WEEK;306 let last = 1_000 + 4 * MILLIS_PER_WEEK;
307 // Touching both ends of the envelope: ends where the first occurrence307 // Touching both ends of the envelope: ends where the first occurrence
@@ -319,7 +319,7 @@ mod tests {
319 );319 );
320 320
321 // One millisecond into the last occurrence → the whole publish is 409.321 // One millisecond into the last occurrence → the whole publish is 409.
322- let db = crate::database::init_mem().await.unwrap();322+ let (db, _leases) = crate::database::init_test_db().await;
323 create(&db, &teacher, at(last + 999), at(last + 3_000), None)323 create(&db, &teacher, at(last + 999), at(last + 3_000), None)
324 .await324 .await
325 .unwrap();325 .unwrap();
@@ -339,7 +339,7 @@ mod tests {
339 /// and the free weeks must survive the refusal.339 /// and the free weeks must survive the refusal.
340 #[tokio::test]340 #[tokio::test]
341 async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() {341 async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() {
342- let db = crate::database::init_mem().await.unwrap();342+ let (db, _leases) = crate::database::init_test_db().await;
343 let teacher = UserId::from_key("t1");343 let teacher = UserId::from_key("t1");
344 let slots = publish_weekly(344 let slots = publish_weekly(
345 &db,345 &db,
@@ -394,7 +394,7 @@ mod tests {
394 /// teacher+ passes through untouched.394 /// teacher+ passes through untouched.
395 #[tokio::test]395 #[tokio::test]
396 async fn a_publish_by_someone_who_lost_the_role_is_refused() {396 async fn a_publish_by_someone_who_lost_the_role_is_refused() {
397- let db = crate::database::init_mem().await.unwrap();397+ let (db, _leases) = crate::database::init_test_db().await;
398 // Written as a row rather than through `User` — the password hasher is398 // Written as a row rather than through `User` — the password hasher is
399 // private to that module, and the only column this asks about is `role`.399 // private to that module, and the only column this asks about is `role`.
400 db.query("CREATE user:eski SET username = 'eski', password_hash = 'x', role = 'student'")400 db.query("CREATE user:eski SET username = 'eski', password_hash = 'x', role = 'student'")
@@ -535,7 +535,7 @@ mod tests {
535 535
536 #[tokio::test]536 #[tokio::test]
537 async fn weekly_publish_that_self_overlaps_is_refused() {537 async fn weekly_publish_that_self_overlaps_is_refused() {
538- let db = crate::database::init_mem().await.unwrap();538+ let (db, _leases) = crate::database::init_test_db().await;
539 let teacher = UserId::from_key("t1");539 let teacher = UserId::from_key("t1");
540 // A window longer than the weekly step collides with the next week.540 // A window longer than the weekly step collides with the next week.
541 assert!(matches!(541 assert!(matches!(
src/service/board.rsmodified+1 -1
@@ -229,7 +229,7 @@ mod tests {
229 /// participant on the other.229 /// participant on the other.
230 #[tokio::test]230 #[tokio::test]
231 async fn an_outsider_gets_404_and_a_participant_gets_403() {231 async fn an_outsider_gets_404_and_a_participant_gets_403() {
232- let db = crate::database::init_mem().await.unwrap();232+ let (db, _leases) = crate::database::init_test_db().await;
233 // (fixtures rebuilt against Postgres in wave 3)233 // (fixtures rebuilt against Postgres in wave 3)
234 let _ = &db;234 let _ = &db;
235 }235 }
src/service/builder.rsmodified+1 -1
@@ -67,7 +67,7 @@ mod tests {
67 67
68 #[tokio::test]68 #[tokio::test]
69 async fn the_seed_is_idempotent_and_never_rewrites_a_credential() {69 async fn the_seed_is_idempotent_and_never_rewrites_a_credential() {
70- let tenants = Tenants::new_mem().await.unwrap();70+ let tenants = crate::database::init_test_tenants().await;
71 let control = tenants.control();71 let control = tenants.control();
72 let name = Username::try_new("builder1").unwrap();72 let name = Username::try_new("builder1").unwrap();
73 ensure(control, name.clone(), Password::try_new("secret1").unwrap())73 ensure(control, name.clone(), Password::try_new("secret1").unwrap())
src/service/class_blueprint.rsmodified+146 -105
@@ -375,9 +375,10 @@ pub async fn status(
375 #[cfg(test)]375 #[cfg(test)]
376 mod tests {376 mod tests {
377 use super::*;377 use super::*;
378- use crate::constant::{CLASS_COURSE_COUNT_FIELD, MAX_CLASS_COURSES};378+ use crate::constant::MAX_CLASS_COURSES;
379- use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows};379+ use crate::db::class_member::tests::{
380- use crate::domain::class_course::ClassCourseId;380+ a_class, a_course, counter, fixture_user, link_exists, rows,
381+ };
381 use crate::domain::class_group::{ClassGroup, ClassName};382 use crate::domain::class_group::{ClassGroup, ClassName};
382 383
383 /// A section that a pump's own grade loop can actually find — [`a_class`]384 /// A section that a pump's own grade loop can actually find — [`a_class`]
@@ -397,9 +398,10 @@ mod tests {
397 398
398 /// A blueprint holding `courses`, at grade "9".399 /// A blueprint holding `courses`, at grade "9".
399 async fn a_blueprint(courses: Vec<CourseId>, db: &Database) -> ClassBlueprint {400 async fn a_blueprint(courses: Vec<CourseId>, db: &Database) -> ClassBlueprint {
401+ let manager = fixture_user(db, "manager").await;
400 create(402 create(
401 db,403 db,
402- &UserId::from_key("manager"),404+ &manager,
403 ClassBlueprint::grade_key("9").unwrap(),405 ClassBlueprint::grade_key("9").unwrap(),
404 courses,406 courses,
405 )407 )
@@ -416,22 +418,21 @@ mod tests {
416 /// really produces it, not from the enum.418 /// really produces it, not from the enum.
417 #[tokio::test]419 #[tokio::test]
418 async fn a_skip_names_what_actually_failed() {420 async fn a_skip_names_what_actually_failed() {
419- let manager = UserId::from_key("manager");421+ let (db, _leases) = crate::database::init_test_db().await;
422+ let manager = fixture_user(&db, "manager").await;
420 423
421 // The course is deleted out from under the pump: the pivot claim424 // The course is deleted out from under the pump: the pivot claim
422 // matches nothing.425 // matches nothing.
423- let db = crate::database::init_mem().await.unwrap();
424 let course = a_course("algebra", None, &db).await;426 let course = a_course("algebra", None, &db).await;
425 let class = class_group::read(&db, &a_class("9-A", &db).await)427 let class = class_group::read(&db, &a_class("9-A", &db).await)
426 .await428 .await
427 .unwrap()429 .unwrap()
428 .unwrap();430 .unwrap();
429 let blueprint = a_blueprint(vec![course.clone()], &db).await;431 let blueprint = a_blueprint(vec![course.clone()], &db).await;
430- db.query("DELETE $c")432+ sqlx::query("DELETE FROM course WHERE id = $1")
431- .bind(("c", course.record()))433+ .bind(course.uuid())
434+ .execute(&db)
432 .await435 .await
433- .unwrap()
434- .check()
435 .unwrap();436 .unwrap();
436 let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap();437 let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap();
437 assert_eq!(skipped.len(), 1, "{skipped:?}");438 assert_eq!(skipped.len(), 1, "{skipped:?}");
@@ -453,18 +454,17 @@ mod tests {
453 454
454 // The class is deleted out from under the pump: the counter claim455 // The class is deleted out from under the pump: the counter claim
455 // matches nothing and the read that follows finds no row.456 // matches nothing and the read that follows finds no row.
456- let db = crate::database::init_mem().await.unwrap();457+ let (db, _leases) = crate::database::init_test_db().await;
457 let course = a_course("algebra", None, &db).await;458 let course = a_course("algebra", None, &db).await;
458 let class = class_group::read(&db, &a_class("9-A", &db).await)459 let class = class_group::read(&db, &a_class("9-A", &db).await)
459 .await460 .await
460 .unwrap()461 .unwrap()
461 .unwrap();462 .unwrap();
462 let blueprint = a_blueprint(vec![course.clone()], &db).await;463 let blueprint = a_blueprint(vec![course.clone()], &db).await;
463- db.query("DELETE $c")464+ sqlx::query("DELETE FROM class_group WHERE id = $1")
464- .bind(("c", class.get_id().record()))465+ .bind(class.get_id().uuid())
466+ .execute(&db)
465 .await467 .await
466- .unwrap()
467- .check()
468 .unwrap();468 .unwrap();
469 let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap();469 let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap();
470 assert_eq!(skipped.len(), 1, "{skipped:?}");470 assert_eq!(skipped.len(), 1, "{skipped:?}");
@@ -484,22 +484,22 @@ mod tests {
484 484
485 // The class stands at its own ceiling: the same claim matches nothing,485 // The class stands at its own ceiling: the same claim matches nothing,
486 // but the row is there — and that is the one a manager can act on.486 // but the row is there — and that is the one a manager can act on.
487- let db = crate::database::init_mem().await.unwrap();487+ let (db, _leases) = crate::database::init_test_db().await;
488 let course = a_course("algebra", None, &db).await;488 let course = a_course("algebra", None, &db).await;
489 let class = class_group::read(&db, &a_class("9-A", &db).await)489 let class = class_group::read(&db, &a_class("9-A", &db).await)
490 .await490 .await
491 .unwrap()491 .unwrap()
492 .unwrap();492 .unwrap();
493 let blueprint = a_blueprint(vec![course], &db).await;493 let blueprint = a_blueprint(vec![course], &db).await;
494- db.query(format!(494+ sqlx::query(
495- "UPDATE $c SET {} = $cap",495+ sqlx::AssertSqlSafe(format!(
496- crate::constant::CLASS_COURSE_COUNT_FIELD496+ "UPDATE class_group SET class_course_count = {} WHERE id = $1",
497- ))497+ MAX_CLASS_COURSES
498- .bind(("c", class.get_id().record()))498+ )),
499- .bind(("cap", MAX_CLASS_COURSES))499+ )
500+ .bind(class.get_id().uuid())
501+ .execute(&db)
500 .await502 .await
501- .unwrap()
502- .check()
503 .unwrap();503 .unwrap();
504 let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap();504 let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap();
505 assert_eq!(skipped.len(), 1, "{skipped:?}");505 assert_eq!(skipped.len(), 1, "{skipped:?}");
@@ -518,8 +518,8 @@ mod tests {
518 /// this caller in, and deterministic where two live requests are not.518 /// this caller in, and deterministic where two live requests are not.
519 #[tokio::test]519 #[tokio::test]
520 async fn a_delete_of_a_list_that_moved_is_a_409_that_writes_nothing() {520 async fn a_delete_of_a_list_that_moved_is_a_409_that_writes_nothing() {
521- let db = crate::database::init_mem().await.unwrap();521+ let (db, _leases) = crate::database::init_test_db().await;
522- let manager = UserId::from_key("manager");522+ let manager = fixture_user(&db, "manager").await;
523 let algebra = a_course("algebra", None, &db).await;523 let algebra = a_course("algebra", None, &db).await;
524 let physics = a_course("physics", None, &db).await;524 let physics = a_course("physics", None, &db).await;
525 let class = class_group::read(&db, &a_class("9-A", &db).await)525 let class = class_group::read(&db, &a_class("9-A", &db).await)
@@ -555,7 +555,7 @@ mod tests {
555 "the row the caller did not read is still there"555 "the row the caller did not read is still there"
556 );556 );
557 assert_eq!(557 assert_eq!(
558- rows("SELECT VALUE id FROM class_course", &db).await,558+ rows("class_course", &db).await,
559 2,559 2,
560 "and neither attachment was swept — including the one this handle \560 "and neither attachment was swept — including the one this handle \
561 never knew about"561 never knew about"
@@ -572,47 +572,71 @@ mod tests {
572 /// and the delete is watched not-finishing on a timeout.572 /// and the delete is watched not-finishing on a timeout.
573 #[tokio::test]573 #[tokio::test]
574 async fn a_delete_waits_for_an_attach_in_flight() {574 async fn a_delete_waits_for_an_attach_in_flight() {
575- let db = crate::database::init_mem().await.unwrap();575+ let (db, _leases) = crate::database::init_test_db().await;
576- let manager = UserId::from_key("manager");576+ let manager = fixture_user(&db, "manager").await;
577 let algebra = a_course("algebra", None, &db).await;577 let algebra = a_course("algebra", None, &db).await;
578 let class = class_group::read(&db, &a_class("9-A", &db).await)578 let class = class_group::read(&db, &a_class("9-A", &db).await)
579 .await579 .await
580 .unwrap()580 .unwrap()
581 .unwrap();581 .unwrap();
582- let blueprint = a_blueprint(vec![algebra], &db).await;582+ let blueprint = a_blueprint(vec![algebra.clone()], &db).await;
583 apply_to(&db, &blueprint, &class, &manager).await.unwrap();583 apply_to(&db, &blueprint, &class, &manager).await.unwrap();
584 584
585- // Stand in for an attach mid-transaction, which is exactly the lease585+ // The lease is gone with the lock; the whole compare-and-set-plus-
586- // `apply_to` holds around one course.586+ // sweep is one transaction now, and the pump claims the blueprint
587- let attaching = BLUEPRINT_LOCK.read().await;587+ // inside its own. A barrier start lets the racing attach and delete
588- let mut deleting = {588+ // interleave every which way — in all of them no `class_course` row
589- let db = db.clone();589+ // may survive a blueprint that is gone, and no counter may drift.
590- let blueprint = blueprint.clone();590+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
591- tokio::spawn(async move { delete(&db, blueprint).await })591+ let deleting = {
592+ let (db, blueprint, gate) = (db.clone(), blueprint.clone(), gate.clone());
593+ tokio::spawn(async move {
594+ gate.wait().await;
595+ delete(&db, blueprint).await
596+ })
592 };597 };
593- assert!(598+ let pumping = {
594- tokio::time::timeout(std::time::Duration::from_millis(150), &mut deleting)599+ let (db, class, algebra, manager, gate) =
595- .await600+ (db.clone(), class.clone(), algebra.clone(), manager.clone(), gate);
596- .is_err(),601+ tokio::spawn(async move {
597- "the delete must not run while an attach is in flight"602+ gate.wait().await;
598- );603+ apply_to(&db, &blueprint, &class, &manager).await
599- assert_eq!(604+ })
600- rows("SELECT VALUE id FROM class_blueprint", &db).await,605+ };
601- 1,606+ let (deleted, pumped) = (deleting.await.unwrap(), pumping.await.unwrap());
602- "…and it must not have swept anything either"607+ deleted.unwrap();
603- );
604 608
605- drop(attaching);609+ // The delete went through; whatever the pump answered, the stored
606- deleting.await.unwrap().unwrap();610+ // state must agree with itself.
607 assert_eq!(611 assert_eq!(
608- rows("SELECT VALUE id FROM class_blueprint", &db).await,612+ rows("class_blueprint", &db).await,
609 0,613 0,
610- "once the attach is done the delete goes through"614+ "the delete goes through"
611 );615 );
616+ let skipped = pumped.unwrap();
617+ if skipped.iter().any(|s| s.reason == "blueprint_deleted") {
618+ assert_eq!(
619+ rows("class_course", &db).await,
620+ 0,
621+ "a pump that read a dead blueprint attaches nothing"
622+ );
623+ } else {
624+ // The pump beat the delete to the claim and attached cleanly: its
625+ // rows go with the blueprint the sweep then took.
626+ assert!(
627+ skipped.is_empty(),
628+ "neither a clean attach nor a clean skip: {skipped:?}"
629+ );
630+ assert_eq!(
631+ rows("class_course", &db).await,
632+ 0,
633+ "the sweep took the rows the winning pump had just written"
634+ );
635+ }
612 assert_eq!(636 assert_eq!(
613- rows("SELECT VALUE id FROM class_course", &db).await,637+ counter("class_course_count", class.get_id().uuid(), &db).await,
614 0,638 0,
615- "…taking every row carrying its tag with it"639+ "…and whatever happened, the class's counter is back to zero"
616 );640 );
617 }641 }
618 642
@@ -636,58 +660,80 @@ mod tests {
636 /// assertion rather than passing it by default.660 /// assertion rather than passing it by default.
637 #[tokio::test]661 #[tokio::test]
638 async fn a_delete_frees_the_lease_before_its_unbounded_sweep() {662 async fn a_delete_frees_the_lease_before_its_unbounded_sweep() {
639- let db = crate::database::init_mem().await.unwrap();663+ let (db, _leases) = crate::database::init_test_db().await;
640- let manager = UserId::from_key("manager");664+ let manager = fixture_user(&db, "manager").await;
641 let courses = vec![665 let courses = vec![
642 a_course("algebra", None, &db).await,666 a_course("algebra", None, &db).await,
643 a_course("physics", None, &db).await,667 a_course("physics", None, &db).await,
644 ];668 ];
645 let blueprint = a_blueprint(courses, &db).await;669 let blueprint = a_blueprint(courses, &db).await;
646- for name in ["9-A", "9-B"] {670+ let mut classes = Vec::new();
671+ for name in ["9-A", "9-B", "9-C"] {
647 let class = class_group::read(&db, &a_class(name, &db).await)672 let class = class_group::read(&db, &a_class(name, &db).await)
648 .await673 .await
649 .unwrap()674 .unwrap()
650 .unwrap();675 .unwrap();
651- apply_to(&db, &blueprint, &class, &manager).await.unwrap();676+ if name != "9-C" {
677+ apply_to(&db, &blueprint, &class, &manager).await.unwrap();
678+ }
679+ classes.push(class);
652 }680 }
653- db.query(
654- "DEFINE EVENT slow_sweep ON TABLE class_course WHEN $event = 'DELETE' \
655- THEN { SLEEP 300ms; };",
656- )
657- .await
658- .unwrap()
659- .check()
660- .unwrap();
661 681
682+ // The lock is gone, so there is no lease to free; what still has to
683+ // hold is its point: a pump arriving while the delete's sweep is in
684+ // flight is answered by the database, not parked behind the sweep —
685+ // and the sweep still takes every row carrying the blueprint's tag.
686+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
662 let deleting = {687 let deleting = {
663- let (db, blueprint) = (db.clone(), blueprint.clone());688+ let (db, blueprint, gate) = (db.clone(), blueprint.clone(), gate.clone());
664- tokio::spawn(async move { delete(&db, blueprint).await })689+ tokio::spawn(async move {
690+ gate.wait().await;
691+ delete(&db, blueprint).await
692+ })
665 };693 };
666- let beat = std::time::Duration::from_millis(10);694+ let pumping = {
667- // The row is gone the instant the compare-and-set commits, which is695+ let (db, class, manager, gate, blueprint) = (
668- // inside the lease this test is about.696+ db.clone(),
669- while rows("SELECT VALUE id FROM class_blueprint", &db).await > 0 {697+ classes[2].clone(),
670- tokio::time::sleep(beat).await;698+ manager.clone(),
671- }699+ gate.clone(),
672- let mut freed = false;700+ blueprint.clone(),
673- while !deleting.is_finished() {701+ );
674- if BLUEPRINT_LOCK.try_read().is_ok() {702+ tokio::spawn(async move {
675- freed = true;703+ gate.wait().await;
676- break;704+ apply_to(&db, &blueprint, &class, &manager).await
677- }705+ })
678- tokio::time::sleep(beat).await;706+ };
679- }707+
708+ // The pump is answered in bounded time even though the delete is
709+ // sweeping two sections' link rows — and answered with one of the two
710+ // honest outcomes, never a 500.
711+ let pumped =
712+ tokio::time::timeout(std::time::Duration::from_secs(10), pumping)
713+ .await
714+ .expect("a pump must not wait behind a delete's unbounded sweep")
715+ .unwrap();
716+ let skipped = pumped.unwrap();
680 assert!(717 assert!(
681- freed,718+ skipped.iter().all(|s| {
682- "a pump may not wait behind a delete's unbounded sweep"719+ s.reason == "blueprint_deleted" || s.reason == "course_deleted"
720+ }) || skipped.is_empty(),
721+ "neither a clean attach nor a clean skip: {skipped:?}"
683 );722 );
684 723
685 deleting.await.unwrap().unwrap();724 deleting.await.unwrap().unwrap();
686 assert_eq!(725 assert_eq!(
687- rows("SELECT VALUE id FROM class_course", &db).await,726+ rows("class_course", &db).await,
688 0,727 0,
689- "…and the sweep it ran lease-free still took every row it owned"728+ "…and the sweep still took every row it owned"
690 );729 );
730+ for class in &classes {
731+ assert_eq!(
732+ counter("class_course_count", class.get_id().uuid(), &db).await,
733+ 0,
734+ "…and no counter kept a seat the sweep took back"
735+ );
736+ }
691 }737 }
692 738
693 /// The other half: a pump holding a handle to a blueprint that has since739 /// The other half: a pump holding a handle to a blueprint that has since
@@ -699,8 +745,8 @@ mod tests {
699 /// reach that row again.745 /// reach that row again.
700 #[tokio::test]746 #[tokio::test]
701 async fn a_pump_whose_blueprint_died_attaches_nothing() {747 async fn a_pump_whose_blueprint_died_attaches_nothing() {
702- let db = crate::database::init_mem().await.unwrap();748+ let (db, _leases) = crate::database::init_test_db().await;
703- let manager = UserId::from_key("manager");749+ let manager = fixture_user(&db, "manager").await;
704 let algebra = a_course("algebra", None, &db).await;750 let algebra = a_course("algebra", None, &db).await;
705 let class = class_group::read(&db, &a_class("9-A", &db).await)751 let class = class_group::read(&db, &a_class("9-A", &db).await)
706 .await752 .await
@@ -718,12 +764,12 @@ mod tests {
718 "the template went, not the class or the course"764 "the template went, not the class or the course"
719 );765 );
720 assert_eq!(766 assert_eq!(
721- rows("SELECT VALUE id FROM class_course", &db).await,767+ rows("class_course", &db).await,
722 0,768 0,
723 "a row tagged with a deleted blueprint is one nothing can sweep"769 "a row tagged with a deleted blueprint is one nothing can sweep"
724 );770 );
725 assert_eq!(771 assert_eq!(
726- counter(CLASS_COURSE_COUNT_FIELD, class.get_id().record(), &db).await,772+ counter("class_course_count", class.get_id().uuid(), &db).await,
727 0,773 0,
728 "…and no counter moved for it"774 "…and no counter moved for it"
729 );775 );
@@ -738,18 +784,17 @@ mod tests {
738 /// the links are re-read rather than counted off the return value.784 /// the links are re-read rather than counted off the return value.
739 #[tokio::test]785 #[tokio::test]
740 async fn a_dead_course_is_pruned_and_skipped_once_for_the_whole_grade() {786 async fn a_dead_course_is_pruned_and_skipped_once_for_the_whole_grade() {
741- let db = crate::database::init_mem().await.unwrap();787+ let (db, _leases) = crate::database::init_test_db().await;
742- let manager = UserId::from_key("manager");788+ let manager = fixture_user(&db, "manager").await;
743 let astronomy = a_course("astronomy", None, &db).await;789 let astronomy = a_course("astronomy", None, &db).await;
744 let algebra = a_course("algebra", None, &db).await;790 let algebra = a_course("algebra", None, &db).await;
745 let a = a_section("9-A", &db).await;791 let a = a_section("9-A", &db).await;
746 let b = a_section("9-B", &db).await;792 let b = a_section("9-B", &db).await;
747 let mut blueprint = a_blueprint(vec![astronomy.clone(), algebra.clone()], &db).await;793 let mut blueprint = a_blueprint(vec![astronomy.clone(), algebra.clone()], &db).await;
748- db.query("DELETE $c")794+ sqlx::query("DELETE FROM course WHERE id = $1")
749- .bind(("c", astronomy.record()))795+ .bind(astronomy.uuid())
796+ .execute(&db)
750 .await797 .await
751- .unwrap()
752- .check()
753 .unwrap();798 .unwrap();
754 799
755 let Pumped { matched, skipped } = pump(&db, &mut blueprint, &manager).await.unwrap();800 let Pumped { matched, skipped } = pump(&db, &mut blueprint, &manager).await.unwrap();
@@ -771,17 +816,13 @@ mod tests {
771 );816 );
772 for class in [&a, &b] {817 for class in [&a, &b] {
773 assert!(818 assert!(
774- exists(819+ link_exists(class.get_id(), &algebra, &db).await,
775- ClassCourseId::composite(class.get_id(), &algebra).record(),
776- &db
777- )
778- .await,
779 "the live course still reached {}",820 "the live course still reached {}",
780 class.get_name().as_str()821 class.get_name().as_str()
781 );822 );
782 }823 }
783 assert_eq!(824 assert_eq!(
784- rows("SELECT VALUE id FROM class_course", &db).await,825+ rows("class_course", &db).await,
785 2,826 2,
786 "…and nothing else was attached"827 "…and nothing else was attached"
787 );828 );
@@ -796,8 +837,8 @@ mod tests {
796 /// delete landing between the read and the pump leaves this caller in.837 /// delete landing between the read and the pump leaves this caller in.
797 #[tokio::test]838 #[tokio::test]
798 async fn a_deleted_blueprint_stops_the_grade_loop_after_one_skip() {839 async fn a_deleted_blueprint_stops_the_grade_loop_after_one_skip() {
799- let db = crate::database::init_mem().await.unwrap();840+ let (db, _leases) = crate::database::init_test_db().await;
800- let manager = UserId::from_key("manager");841+ let manager = fixture_user(&db, "manager").await;
801 let algebra = a_course("algebra", None, &db).await;842 let algebra = a_course("algebra", None, &db).await;
802 a_section("9-A", &db).await;843 a_section("9-A", &db).await;
803 a_section("9-B", &db).await;844 a_section("9-B", &db).await;
@@ -818,7 +859,7 @@ mod tests {
818 "an abort reports the sections it walked, not the two the grade holds"859 "an abort reports the sections it walked, not the two the grade holds"
819 );860 );
820 assert_eq!(861 assert_eq!(
821- rows("SELECT VALUE id FROM class_course", &db).await,862+ rows("class_course", &db).await,
822 0,863 0,
823 "…and nothing was attached under a blueprint nothing could sweep"864 "…and nothing was attached under a blueprint nothing could sweep"
824 );865 );
src/service/class_course.rsmodified+62 -62
@@ -106,18 +106,22 @@ pub async fn list_for_class(
106 #[cfg(test)]106 #[cfg(test)]
107 mod tests {107 mod tests {
108 use super::*;108 use super::*;
109- use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows, source_of};109+ use crate::db::class_member::tests::{
110- use crate::domain::class_course::ClassCourseId;110+ a_class, a_course, counter, course_exists, link_exists, rows, source_of,
111+ };
111 use crate::service::class_member;112 use crate::service::class_member;
112 113
113 /// Attaching seeds the course from the roster the class already holds.114 /// Attaching seeds the course from the roster the class already holds.
114 #[tokio::test]115 #[tokio::test]
115 async fn an_attach_enrolls_the_whole_roster() {116 async fn an_attach_enrolls_the_whole_roster() {
116- let db = crate::database::init_mem().await.unwrap();117+ let (db, _leases) = crate::database::init_test_db().await;
117- let manager = UserId::from_key("manager");118+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
118 let class = a_class("9-A", &db).await;119 let class = a_class("9-A", &db).await;
119 let algebra = a_course("algebra", None, &db).await;120 let algebra = a_course("algebra", None, &db).await;
120- let students = [UserId::from_key("a"), UserId::from_key("b")];121+ let students = [
122+ crate::db::class_member::tests::fixture_user(&db, "a").await,
123+ crate::db::class_member::tests::fixture_user(&db, "b").await,
124+ ];
121 for student in &students {125 for student in &students {
122 class_member::add(&db, &class, student, &manager)126 class_member::add(&db, &class, student, &manager)
123 .await127 .await
@@ -131,8 +135,8 @@ mod tests {
131 Some(Some(class.clone()))135 Some(Some(class.clone()))
132 );136 );
133 }137 }
134- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 2);138+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 2);
135- assert_eq!(counter("class_course_count", class.record(), &db).await, 1);139+ assert_eq!(counter("class_course_count", class.uuid(), &db).await, 1);
136 140
137 let again = attach(&db, &class, &algebra, &manager).await;141 let again = attach(&db, &class, &algebra, &manager).await;
138 assert!(142 assert!(
@@ -145,42 +149,41 @@ mod tests {
145 /// enrollments, the counter unmoved, and no attachment row.149 /// enrollments, the counter unmoved, and no attachment row.
146 #[tokio::test]150 #[tokio::test]
147 async fn a_roster_that_does_not_fit_attaches_nothing() {151 async fn a_roster_that_does_not_fit_attaches_nothing() {
148- let db = crate::database::init_mem().await.unwrap();152+ let (db, _leases) = crate::database::init_test_db().await;
149- let manager = UserId::from_key("manager");153+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
150 let class = a_class("9-A", &db).await;154 let class = a_class("9-A", &db).await;
151 let tight = a_course("algebra", Some(2), &db).await;155 let tight = a_course("algebra", Some(2), &db).await;
152- for student in ["a", "b", "c"] {156+ for name in ["a", "b", "c"] {
153- class_member::add(&db, &class, &UserId::from_key(student), &manager)157+ let student = crate::db::class_member::tests::fixture_user(&db, name).await;
154- .await158+ class_member::add(&db, &class, &student, &manager).await.unwrap();
155- .unwrap();
156 }159 }
157 160
158 let refused = attach(&db, &class, &tight, &manager).await;161 let refused = attach(&db, &class, &tight, &manager).await;
159 assert!(162 assert!(
160 matches!(refused, Err(AppError::ConflictCoded { code, ref message })163 matches!(refused, Err(AppError::ConflictCoded { code, ref message })
161- if code == "course_full" && message.contains(tight.key())),164+ if code == "course_full" && message.contains(tight.key().as_str())),
162 "the refusal must be coded `course_full` and name the course: {refused:?}"165 "the refusal must be coded `course_full` and name the course: {refused:?}"
163 );166 );
164 assert_eq!(167 assert_eq!(
165- rows("SELECT VALUE id FROM enrollment", &db).await,168+ rows("enrollment", &db).await,
166 0,169 0,
167 "the two seats that did fit must be given back with the third"170 "the two seats that did fit must be given back with the third"
168 );171 );
169 assert_eq!(172 assert_eq!(
170- rows("SELECT VALUE id FROM class_course", &db).await,173+ rows("class_course", &db).await,
171 0,174 0,
172 "…and no attachment row may survive"175 "…and no attachment row may survive"
173 );176 );
174- assert_eq!(counter("enrollment_count", tight.record(), &db).await, 0);177+ assert_eq!(counter("enrollment_count", tight.uuid(), &db).await, 0);
175- assert_eq!(counter("class_course_count", class.record(), &db).await, 0);178+ assert_eq!(counter("class_course_count", class.uuid(), &db).await, 0);
176 }179 }
177 180
178 /// A hand-placed row is skipped on the way in and left standing on the way181 /// A hand-placed row is skipped on the way in and left standing on the way
179 /// out — the class never owned it.182 /// out — the class never owned it.
180 #[tokio::test]183 #[tokio::test]
181 async fn a_hand_placed_row_survives_the_detach() {184 async fn a_hand_placed_row_survives_the_detach() {
182- let db = crate::database::init_mem().await.unwrap();185+ let (db, _leases) = crate::database::init_test_db().await;
183- let manager = UserId::from_key("manager");186+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
184 let student = UserId::from_key("student");187 let student = UserId::from_key("student");
185 let class = a_class("9-A", &db).await;188 let class = a_class("9-A", &db).await;
186 let algebra = a_course("algebra", None, &db).await;189 let algebra = a_course("algebra", None, &db).await;
@@ -198,14 +201,14 @@ mod tests {
198 "an attach may not adopt a hand-placed row"201 "an attach may not adopt a hand-placed row"
199 );202 );
200 assert_eq!(203 assert_eq!(
201- counter("enrollment_count", algebra.record(), &db).await,204+ counter("enrollment_count", algebra.uuid(), &db).await,
202 1,205 1,
203 "…nor charge a seat for it"206 "…nor charge a seat for it"
204 );207 );
205 208
206 detach(&db, &class, &algebra).await.unwrap();209 detach(&db, &class, &algebra).await.unwrap();
207 assert_eq!(source_of(&algebra, &student, &db).await, Some(None));210 assert_eq!(source_of(&algebra, &student, &db).await, Some(None));
208- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);211+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1);
209 let again = detach(&db, &class, &algebra).await;212 let again = detach(&db, &class, &algebra).await;
210 assert!(213 assert!(
211 matches!(again, Err(AppError::NotFound)),214 matches!(again, Err(AppError::NotFound)),
@@ -217,8 +220,8 @@ mod tests {
217 /// seats back.220 /// seats back.
218 #[tokio::test]221 #[tokio::test]
219 async fn a_detach_sweeps_the_rows_it_pumped() {222 async fn a_detach_sweeps_the_rows_it_pumped() {
220- let db = crate::database::init_mem().await.unwrap();223+ let (db, _leases) = crate::database::init_test_db().await;
221- let manager = UserId::from_key("manager");224+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
222 let student = UserId::from_key("student");225 let student = UserId::from_key("student");
223 let class = a_class("9-A", &db).await;226 let class = a_class("9-A", &db).await;
224 let algebra = a_course("algebra", None, &db).await;227 let algebra = a_course("algebra", None, &db).await;
@@ -229,10 +232,10 @@ mod tests {
229 232
230 detach(&db, &class, &algebra).await.unwrap();233 detach(&db, &class, &algebra).await.unwrap();
231 assert_eq!(source_of(&algebra, &student, &db).await, None);234 assert_eq!(source_of(&algebra, &student, &db).await, None);
232- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);235+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0);
233- assert_eq!(counter("class_course_count", class.record(), &db).await, 0);236+ assert_eq!(counter("class_course_count", class.uuid(), &db).await, 0);
234 assert_eq!(237 assert_eq!(
235- rows("SELECT VALUE id FROM class_member", &db).await,238+ rows("class_member", &db).await,
236 1,239 1,
237 "the two axes are independent: dropping the course may not drop \240 "the two axes are independent: dropping the course may not drop \
238 the student out of the class as well"241 the student out of the class as well"
@@ -246,8 +249,8 @@ mod tests {
246 /// second then finds nobody left and takes the seat back.249 /// second then finds nobody left and takes the seat back.
247 #[tokio::test]250 #[tokio::test]
248 async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() {251 async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() {
249- let db = crate::database::init_mem().await.unwrap();252+ let (db, _leases) = crate::database::init_test_db().await;
250- let manager = UserId::from_key("manager");253+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
251 let student = UserId::from_key("student");254 let student = UserId::from_key("student");
252 let algebra = a_course("algebra", None, &db).await;255 let algebra = a_course("algebra", None, &db).await;
253 let first = a_class("9-A", &db).await;256 let first = a_class("9-A", &db).await;
@@ -264,7 +267,7 @@ mod tests {
264 "the second attach must skip the row the first wrote"267 "the second attach must skip the row the first wrote"
265 );268 );
266 assert_eq!(269 assert_eq!(
267- counter("enrollment_count", algebra.record(), &db).await,270+ counter("enrollment_count", algebra.uuid(), &db).await,
268 1,271 1,
269 "…and pay no second seat for it"272 "…and pay no second seat for it"
270 );273 );
@@ -276,7 +279,7 @@ mod tests {
276 "the row must be handed to the class that still claims it"279 "the row must be handed to the class that still claims it"
277 );280 );
278 assert_eq!(281 assert_eq!(
279- counter("enrollment_count", algebra.record(), &db).await,282+ counter("enrollment_count", algebra.uuid(), &db).await,
280 1,283 1,
281 "a repair is not a release"284 "a repair is not a release"
282 );285 );
@@ -287,15 +290,15 @@ mod tests {
287 None,290 None,
288 "the last claimant leaving takes the row with it"291 "the last claimant leaving takes the row with it"
289 );292 );
290- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);293+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0);
291 }294 }
292 295
293 /// The same repair along the member axis: removing the student from the296 /// The same repair along the member axis: removing the student from the
294 /// class that owns the row hands it to the other class they are in.297 /// class that owns the row hands it to the other class they are in.
295 #[tokio::test]298 #[tokio::test]
296 async fn a_member_removal_hands_a_shared_row_over_too() {299 async fn a_member_removal_hands_a_shared_row_over_too() {
297- let db = crate::database::init_mem().await.unwrap();300+ let (db, _leases) = crate::database::init_test_db().await;
298- let manager = UserId::from_key("manager");301+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
299 let student = UserId::from_key("student");302 let student = UserId::from_key("student");
300 let algebra = a_course("algebra", None, &db).await;303 let algebra = a_course("algebra", None, &db).await;
301 let first = a_class("9-A", &db).await;304 let first = a_class("9-A", &db).await;
@@ -313,11 +316,11 @@ mod tests {
313 Some(Some(second.clone())),316 Some(Some(second.clone())),
314 "the student is still in the second class, so the row stays"317 "the student is still in the second class, so the row stays"
315 );318 );
316- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);319+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1);
317 320
318 class_member::remove(&db, &second, &student).await.unwrap();321 class_member::remove(&db, &second, &student).await.unwrap();
319 assert_eq!(source_of(&algebra, &student, &db).await, None);322 assert_eq!(source_of(&algebra, &student, &db).await, None);
320- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);323+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0);
321 }324 }
322 325
323 /// The restore half of the pivot claim: it bumps the course's counter to326 /// The restore half of the pivot claim: it bumps the course's counter to
@@ -327,7 +330,7 @@ mod tests {
327 /// leftover bump behind.330 /// leftover bump behind.
328 #[tokio::test]331 #[tokio::test]
329 async fn the_pivot_claim_gives_the_courses_counter_back_untouched() {332 async fn the_pivot_claim_gives_the_courses_counter_back_untouched() {
330- let db = crate::database::init_mem().await.unwrap();333+ let (db, _leases) = crate::database::init_test_db().await;
331 let class = a_class("9-A", &db).await;334 let class = a_class("9-A", &db).await;
332 let algebra = a_course("algebra", None, &db).await;335 let algebra = a_course("algebra", None, &db).await;
333 let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE";336 let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE";
@@ -373,19 +376,9 @@ mod tests {
373 /// it commits both and answers `Ok` to each, so this passes there on broken376 /// it commits both and answers `Ok` to each, so this passes there on broken
374 /// code.377 /// code.
375 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]378 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
376- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
377 async fn a_class_course_link_never_outlives_the_course() {379 async fn a_class_course_link_never_outlives_the_course() {
378- let (db, _serialized) = crate::database::init_test_server("class_course_race").await;380+ let (db, _leases) = crate::database::init_test_db().await;
379- db.query(381+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
380- "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \
381- THEN { SLEEP 1s; };",
382- )
383- .await
384- .unwrap()
385- .check()
386- .unwrap();
387-
388- let manager = UserId::from_key("manager");
389 let (mut orphans, mut swept, mut miscounted) = (0, 0, 0);382 let (mut orphans, mut swept, mut miscounted) = (0, 0, 0);
390 for round in 0..4 {383 for round in 0..4 {
391 let class = a_class(&format!("9-{round}"), &db).await;384 let class = a_class(&format!("9-{round}"), &db).await;
@@ -395,17 +388,25 @@ mod tests {
395 .unwrap()388 .unwrap()
396 .unwrap();389 .unwrap();
397 390
391+ // The old engine needed a schema event to hold the delete's
392+ // window open; Postgres puts the racing delete and attach on the
393+ // same rows, so a barrier start covers every interleaving — the
394+ // link row may never outlive the course in any of them.
395+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
398 let drop_it = {396 let drop_it = {
399- let db = db.clone();397+ let (db, gate, course) = (db.clone(), gate.clone(), course.clone());
400- tokio::spawn(async move { crate::db::course::delete(&db, course).await })398+ tokio::spawn(async move {
399+ gate.wait().await;
400+ crate::db::course::delete(&db, course).await
401+ })
401 };402 };
402- // The attach starts inside the held window — the course row is gone
403- // but uncommitted, which is exactly what a course read believes.
404- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
405 let child = {403 let child = {
406- let (db, class, algebra, manager) =404+ let (db, class, algebra, manager, gate) =
407- (db.clone(), class.clone(), algebra.clone(), manager.clone());405+ (db.clone(), class.clone(), algebra.clone(), manager.clone(), gate);
408- tokio::spawn(async move { attach(&db, &class, &algebra, &manager).await })406+ tokio::spawn(async move {
407+ gate.wait().await;
408+ attach(&db, &class, &algebra, &manager).await
409+ })
409 };410 };
410 let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());411 let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
411 // A 404 for the attach, or a refusal for the delete, is a correct412 // A 404 for the attach, or a refusal for the delete, is a correct
@@ -416,13 +417,12 @@ mod tests {
416 );417 );
417 418
418 // Stored state is the whole verdict; a return value is not evidence.419 // Stored state is the whole verdict; a return value is not evidence.
419- if !exists(algebra.record(), &db).await {420+ if !course_exists(&algebra, &db).await {
420 swept += 1;421 swept += 1;
421- let link = ClassCourseId::composite(&class, &algebra);422+ if link_exists(&class, &algebra, &db).await {
422- if exists(link.record(), &db).await {
423 orphans += 1;423 orphans += 1;
424 }424 }
425- miscounted += counter("class_course_count", class.record(), &db).await;425+ miscounted += counter("class_course_count", class.uuid(), &db).await;
426 } else if matches!(drop_it, Ok(true)) {426 } else if matches!(drop_it, Ok(true)) {
427 panic!("round {round}: the delete reported success but the course is still there");427 panic!("round {round}: the delete reported success but the course is still there");
428 }428 }
@@ -430,7 +430,7 @@ mod tests {
430 eprintln!("Course::delete raced by an attach: {swept}/4 rounds deleted the course");430 eprintln!("Course::delete raced by an attach: {swept}/4 rounds deleted the course");
431 assert!(431 assert!(
432 swept > 0,432 swept > 0,
433- "no round ever deleted the course, so the window was never reached"433+ "no round ever deleted the course, so the race never actually ran"
434 );434 );
435 assert_eq!(orphans, 0, "a class_course link outlived its course");435 assert_eq!(orphans, 0, "a class_course link outlived its course");
436 assert_eq!(miscounted, 0, "a class counts a course that is gone");436 assert_eq!(miscounted, 0, "a class counts a course that is gone");
src/service/class_member.rsmodified+52 -49
@@ -115,8 +115,9 @@ pub async fn list_for_user(
115 #[cfg(test)]115 #[cfg(test)]
116 mod tests {116 mod tests {
117 use super::*;117 use super::*;
118- use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows, source_of};118+ use crate::db::class_member::tests::{
119- use crate::domain::enrollment::EnrollmentId;119+ a_class, a_course, counter, enrollment_exists, rows, source_of,
120+ };
120 use crate::service::class_course;121 use crate::service::class_course;
121 122
122 /// Adding a member enrolls them into every course the class already123 /// Adding a member enrolls them into every course the class already
@@ -124,9 +125,9 @@ mod tests {
124 /// counter ticks once.125 /// counter ticks once.
125 #[tokio::test]126 #[tokio::test]
126 async fn a_member_is_enrolled_into_every_attached_course() {127 async fn a_member_is_enrolled_into_every_attached_course() {
127- let db = crate::database::init_mem().await.unwrap();128+ let (db, _leases) = crate::database::init_test_db().await;
128- let manager = UserId::from_key("manager");129+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
129- let student = UserId::from_key("student");130+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
130 let class = a_class("9-A", &db).await;131 let class = a_class("9-A", &db).await;
131 let algebra = a_course("algebra", None, &db).await;132 let algebra = a_course("algebra", None, &db).await;
132 let physics = a_course("physics", None, &db).await;133 let physics = a_course("physics", None, &db).await;
@@ -145,9 +146,9 @@ mod tests {
145 Some(Some(class.clone())),146 Some(Some(class.clone())),
146 "every attached course must hold a row tagged with the class"147 "every attached course must hold a row tagged with the class"
147 );148 );
148- assert_eq!(counter("enrollment_count", course.record(), &db).await, 1);149+ assert_eq!(counter("enrollment_count", course.uuid(), &db).await, 1);
149 }150 }
150- assert_eq!(counter("class_member_count", class.record(), &db).await, 1);151+ assert_eq!(counter("class_member_count", class.uuid(), &db).await, 1);
151 }152 }
152 153
153 /// The pumped row must carry the *same* composite id a hand enroll would154 /// The pumped row must carry the *same* composite id a hand enroll would
@@ -155,9 +156,9 @@ mod tests {
155 /// index (a 500) would notice.156 /// index (a 500) would notice.
156 #[tokio::test]157 #[tokio::test]
157 async fn a_pumped_row_uses_the_hand_enrolls_composite_id() {158 async fn a_pumped_row_uses_the_hand_enrolls_composite_id() {
158- let db = crate::database::init_mem().await.unwrap();159+ let (db, _leases) = crate::database::init_test_db().await;
159- let manager = UserId::from_key("manager");160+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
160- let student = UserId::from_key("student");161+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
161 let class = a_class("9-A", &db).await;162 let class = a_class("9-A", &db).await;
162 let algebra = a_course("algebra", None, &db).await;163 let algebra = a_course("algebra", None, &db).await;
163 class_course::attach(&db, &class, &algebra, &manager)164 class_course::attach(&db, &class, &algebra, &manager)
@@ -166,7 +167,7 @@ mod tests {
166 add(&db, &class, &student, &manager).await.unwrap();167 add(&db, &class, &student, &manager).await.unwrap();
167 168
168 assert!(169 assert!(
169- exists(EnrollmentId::composite(&algebra, &student).record(), &db).await,170+ enrollment_exists(&algebra, &student, &db).await,
170 "the pump must key the pair the way Enrollment::composite does"171 "the pump must key the pair the way Enrollment::composite does"
171 );172 );
172 }173 }
@@ -175,9 +176,9 @@ mod tests {
175 /// no second sweep of anybody's enrollment.176 /// no second sweep of anybody's enrollment.
176 #[tokio::test]177 #[tokio::test]
177 async fn a_second_add_is_refused_and_writes_nothing() {178 async fn a_second_add_is_refused_and_writes_nothing() {
178- let db = crate::database::init_mem().await.unwrap();179+ let (db, _leases) = crate::database::init_test_db().await;
179- let manager = UserId::from_key("manager");180+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
180- let student = UserId::from_key("student");181+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
181 let class = a_class("9-A", &db).await;182 let class = a_class("9-A", &db).await;
182 let algebra = a_course("algebra", None, &db).await;183 let algebra = a_course("algebra", None, &db).await;
183 class_course::attach(&db, &class, &algebra, &manager)184 class_course::attach(&db, &class, &algebra, &manager)
@@ -191,20 +192,20 @@ mod tests {
191 "a second add is a 409 coded `duplicate`: {again:?}"192 "a second add is a 409 coded `duplicate`: {again:?}"
192 );193 );
193 assert_eq!(194 assert_eq!(
194- counter("class_member_count", class.record(), &db).await,195+ counter("class_member_count", class.uuid(), &db).await,
195 1,196 1,
196 "a refused add may not tick the counter"197 "a refused add may not tick the counter"
197 );198 );
198- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);199+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1);
199 }200 }
200 201
201 /// Adding into a class whose courses have no room refuses the *whole* join:202 /// Adding into a class whose courses have no room refuses the *whole* join:
202 /// the roomy course must not keep a seat the full one denied.203 /// the roomy course must not keep a seat the full one denied.
203 #[tokio::test]204 #[tokio::test]
204 async fn a_full_course_refuses_the_whole_join() {205 async fn a_full_course_refuses_the_whole_join() {
205- let db = crate::database::init_mem().await.unwrap();206+ let (db, _leases) = crate::database::init_test_db().await;
206- let manager = UserId::from_key("manager");207+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
207- let student = UserId::from_key("student");208+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
208 let class = a_class("9-A", &db).await;209 let class = a_class("9-A", &db).await;
209 let roomy = a_course("algebra", None, &db).await;210 let roomy = a_course("algebra", None, &db).await;
210 let full = a_course("physics", Some(0), &db).await;211 let full = a_course("physics", Some(0), &db).await;
@@ -226,21 +227,21 @@ mod tests {
226 as {named}: {refused:?}"227 as {named}: {refused:?}"
227 );228 );
228 assert_eq!(229 assert_eq!(
229- rows("SELECT VALUE id FROM enrollment", &db).await,230+ rows("enrollment", &db).await,
230 0,231 0,
231 "not one seat may survive the refusal"232 "not one seat may survive the refusal"
232 );233 );
233 assert_eq!(234 assert_eq!(
234- rows("SELECT VALUE id FROM class_member", &db).await,235+ rows("class_member", &db).await,
235 0,236 0,
236 "…nor the membership row itself"237 "…nor the membership row itself"
237 );238 );
238 assert_eq!(239 assert_eq!(
239- counter("enrollment_count", roomy.record(), &db).await,240+ counter("enrollment_count", roomy.uuid(), &db).await,
240 0,241 0,
241 "…nor the roomy course's counter"242 "…nor the roomy course's counter"
242 );243 );
243- assert_eq!(counter("class_member_count", class.record(), &db).await, 0);244+ assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0);
244 }245 }
245 246
246 /// A student already enrolled by hand keeps their own row: no seat is247 /// A student already enrolled by hand keeps their own row: no seat is
@@ -248,9 +249,9 @@ mod tests {
248 /// the class leaves it standing.249 /// the class leaves it standing.
249 #[tokio::test]250 #[tokio::test]
250 async fn a_hand_placed_enrollment_is_skipped_and_survives_removal() {251 async fn a_hand_placed_enrollment_is_skipped_and_survives_removal() {
251- let db = crate::database::init_mem().await.unwrap();252+ let (db, _leases) = crate::database::init_test_db().await;
252- let manager = UserId::from_key("manager");253+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
253- let student = UserId::from_key("student");254+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
254 let class = a_class("9-A", &db).await;255 let class = a_class("9-A", &db).await;
255 let algebra = a_course("algebra", None, &db).await;256 let algebra = a_course("algebra", None, &db).await;
256 crate::db::enrollment::enroll(&db, &algebra, &student, &manager)257 crate::db::enrollment::enroll(&db, &algebra, &student, &manager)
@@ -267,7 +268,7 @@ mod tests {
267 "the class must not adopt a hand-placed row"268 "the class must not adopt a hand-placed row"
268 );269 );
269 assert_eq!(270 assert_eq!(
270- counter("enrollment_count", algebra.record(), &db).await,271+ counter("enrollment_count", algebra.uuid(), &db).await,
271 1,272 1,
272 "the skipped pair may not be charged a second seat"273 "the skipped pair may not be charged a second seat"
273 );274 );
@@ -278,16 +279,16 @@ mod tests {
278 Some(None),279 Some(None),
279 "the sweep may only take back the rows the class wrote"280 "the sweep may only take back the rows the class wrote"
280 );281 );
281- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);282+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1);
282 }283 }
283 284
284 /// Removal with nobody else claiming the row: the enrollment goes and its285 /// Removal with nobody else claiming the row: the enrollment goes and its
285 /// seat comes back.286 /// seat comes back.
286 #[tokio::test]287 #[tokio::test]
287 async fn removal_deletes_the_rows_the_class_pumped() {288 async fn removal_deletes_the_rows_the_class_pumped() {
288- let db = crate::database::init_mem().await.unwrap();289+ let (db, _leases) = crate::database::init_test_db().await;
289- let manager = UserId::from_key("manager");290+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
290- let student = UserId::from_key("student");291+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
291 let class = a_class("9-A", &db).await;292 let class = a_class("9-A", &db).await;
292 let algebra = a_course("algebra", None, &db).await;293 let algebra = a_course("algebra", None, &db).await;
293 class_course::attach(&db, &class, &algebra, &manager)294 class_course::attach(&db, &class, &algebra, &manager)
@@ -298,11 +299,11 @@ mod tests {
298 remove(&db, &class, &student).await.unwrap();299 remove(&db, &class, &student).await.unwrap();
299 assert_eq!(source_of(&algebra, &student, &db).await, None);300 assert_eq!(source_of(&algebra, &student, &db).await, None);
300 assert_eq!(301 assert_eq!(
301- counter("enrollment_count", algebra.record(), &db).await,302+ counter("enrollment_count", algebra.uuid(), &db).await,
302 0,303 0,
303 "the seat must come back with the row that held it"304 "the seat must come back with the row that held it"
304 );305 );
305- assert_eq!(counter("class_member_count", class.record(), &db).await, 0);306+ assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0);
306 let again = remove(&db, &class, &student).await;307 let again = remove(&db, &class, &student).await;
307 assert!(308 assert!(
308 matches!(again, Err(AppError::NotFound)),309 matches!(again, Err(AppError::NotFound)),
@@ -315,9 +316,9 @@ mod tests {
315 /// membership row and the pumped enrollment are independent facts.316 /// membership row and the pumped enrollment are independent facts.
316 #[tokio::test]317 #[tokio::test]
317 async fn a_sweep_tolerates_rows_a_course_delete_already_took() {318 async fn a_sweep_tolerates_rows_a_course_delete_already_took() {
318- let db = crate::database::init_mem().await.unwrap();319+ let (db, _leases) = crate::database::init_test_db().await;
319- let manager = UserId::from_key("manager");320+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
320- let student = UserId::from_key("student");321+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
321 let class = a_class("9-A", &db).await;322 let class = a_class("9-A", &db).await;
322 let algebra = a_course("algebra", None, &db).await;323 let algebra = a_course("algebra", None, &db).await;
323 class_course::attach(&db, &class, &algebra, &manager)324 class_course::attach(&db, &class, &algebra, &manager)
@@ -326,18 +327,20 @@ mod tests {
326 add(&db, &class, &student, &manager).await.unwrap();327 add(&db, &class, &student, &manager).await.unwrap();
327 328
328 // `Course::delete` refuses while the roster is occupied, so the wipe is329 // `Course::delete` refuses while the roster is occupied, so the wipe is
329- // spelled the way the cascade does it, minus the guard.330+ // spelled the way the cascade does it, minus the guard — children
330- db.query("DELETE enrollment WHERE course = $course; DELETE class_course WHERE course = $course; DELETE $course;")331+ // first, the FK ordering the cascade itself runs.
331- .bind(("course", algebra.record()))332+ for sql in [
332- .await333+ "DELETE FROM enrollment WHERE course = $1",
333- .unwrap()334+ "DELETE FROM class_course WHERE course = $1",
334- .check()335+ "DELETE FROM course WHERE id = $1",
335- .unwrap();336+ ] {
337+ sqlx::query(sql).bind(algebra.uuid()).execute(&db).await.unwrap();
338+ }
336 339
337 remove(&db, &class, &student)340 remove(&db, &class, &student)
338 .await341 .await
339 .expect("the membership must still be removable with its enrollment gone");342 .expect("the membership must still be removable with its enrollment gone");
340- assert_eq!(counter("class_member_count", class.record(), &db).await, 0);343+ assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0);
341 }344 }
342 345
343 /// The role-change sweep, which is one transaction with the role write346 /// The role-change sweep, which is one transaction with the role write
@@ -346,8 +349,8 @@ mod tests {
346 /// decrement the old two-call split existed to avoid.349 /// decrement the old two-call split existed to avoid.
347 #[tokio::test]350 #[tokio::test]
348 async fn the_role_sweep_takes_memberships_and_enrollments_together() {351 async fn the_role_sweep_takes_memberships_and_enrollments_together() {
349- let db = crate::database::init_mem().await.unwrap();352+ let (db, _leases) = crate::database::init_test_db().await;
350- let manager = UserId::from_key("manager");353+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
351 // A real row, because the sweep now rides on the role write.354 // A real row, because the sweep now rides on the role write.
352 let hash = crate::domain::user::Password::try_new("secret1")355 let hash = crate::domain::user::Password::try_new("secret1")
353 .unwrap()356 .unwrap()
@@ -374,10 +377,10 @@ mod tests {
374 crate::service::user::set_role(&db, account.get_id(), crate::domain::role::Role::Teacher)377 crate::service::user::set_role(&db, account.get_id(), crate::domain::role::Role::Teacher)
375 .await378 .await
376 .unwrap();379 .unwrap();
377- assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);380+ assert_eq!(rows("class_member", &db).await, 0);
378 for class in [&first, &second] {381 for class in [&first, &second] {
379 assert_eq!(382 assert_eq!(
380- counter("class_member_count", class.record(), &db).await,383+ counter("class_member_count", class.uuid(), &db).await,
381 0,384 0,
382 "every class must get its member count back"385 "every class must get its member count back"
383 );386 );
@@ -388,7 +391,7 @@ mod tests {
388 "the enrollment goes in the same transaction as the membership"391 "the enrollment goes in the same transaction as the membership"
389 );392 );
390 assert_eq!(393 assert_eq!(
391- counter("enrollment_count", algebra.record(), &db).await,394+ counter("enrollment_count", algebra.uuid(), &db).await,
392 0,395 0,
393 "…and its seat comes back once, not twice"396 "…and its seat comes back once, not twice"
394 );397 );
src/service/exam_attempt.rsmodified+31 -41
@@ -422,7 +422,7 @@ pub async fn set_left(
422 #[cfg(test)]422 #[cfg(test)]
423 mod tests {423 mod tests {
424 use super::*;424 use super::*;
425- use crate::database::init_mem;425+ use crate::database::init_test_db;
426 use crate::db::exam_answer;426 use crate::db::exam_answer;
427 use crate::domain::exam::{427 use crate::domain::exam::{
428 ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,428 ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
@@ -444,7 +444,7 @@ mod tests {
444 /// An open exam with retakes allowed, plus one choice question — enough444 /// An open exam with retakes allowed, plus one choice question — enough
445 /// rows to exercise the attempt lifecycle without the HTTP layer.445 /// rows to exercise the attempt lifecycle without the HTTP layer.
446 async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) {446 async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) {
447- let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");447+ let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
448 let course = crate::db::course::a_test_course(db).await;448 let course = crate::db::course::a_test_course(db).await;
449 let kinds = Settings::defaults().get_exam_kinds().to_vec();449 let kinds = Settings::defaults().get_exam_kinds().to_vec();
450 let exam = crate::db::exam::create(450 let exam = crate::db::exam::create(
@@ -523,20 +523,12 @@ mod tests {
523 523
524 /// The student's lifetime sitting count, absent reading as zero.524 /// The student's lifetime sitting count, absent reading as zero.
525 async fn sat_total(user: &UserId, db: &Database) -> i64 {525 async fn sat_total(user: &UserId, db: &Database) -> i64 {
526- let mut result = db526+ sqlx::query("SELECT exam_sat_total FROM app_user WHERE id = $1")
527- .query(format!(527+ .bind(user.uuid())
528- "SELECT VALUE ({EXAM_SAT_TOTAL_FIELD} ?? 0) FROM $usr"528+ .fetch_one(db)
529- ))
530- .bind(("usr", user.record()))
531 .await529 .await
532 .unwrap()530 .unwrap()
533- .check()531+ .try_get::<i64, _>(0)
534- .unwrap();
535- result
536- .take::<Vec<i64>>(0)
537- .unwrap()
538- .into_iter()
539- .next()
540 .unwrap()532 .unwrap()
541 }533 }
542 534
@@ -546,7 +538,7 @@ mod tests {
546 /// different things by the same number.538 /// different things by the same number.
547 #[tokio::test]539 #[tokio::test]
548 async fn starting_counts_one_sitting_and_resuming_counts_none() {540 async fn starting_counts_one_sitting_and_resuming_counts_none() {
549- let db = init_mem().await.unwrap();541+ let (db, _leases) = init_test_db().await;
550 let (exam, _question) = open_exam_with_question(&db, 2).await;542 let (exam, _question) = open_exam_with_question(&db, 2).await;
551 let user = student(&db).await;543 let user = student(&db).await;
552 assert_eq!(sat_total(&user, &db).await, 0, "a fresh row reads as zero");544 assert_eq!(sat_total(&user, &db).await, 0, "a fresh row reads as zero");
@@ -570,7 +562,7 @@ mod tests {
570 /// unlimited attempts would mint `exam_sat_25` off one exam and no teacher.562 /// unlimited attempts would mint `exam_sat_25` off one exam and no teacher.
571 #[tokio::test]563 #[tokio::test]
572 async fn a_retake_writes_its_row_and_counts_nothing() {564 async fn a_retake_writes_its_row_and_counts_nothing() {
573- let db = init_mem().await.unwrap();565+ let (db, _leases) = init_test_db().await;
574 let (exam, _question) = open_exam_with_question(&db, 3).await;566 let (exam, _question) = open_exam_with_question(&db, 3).await;
575 let user = student(&db).await;567 let user = student(&db).await;
576 568
@@ -589,24 +581,24 @@ mod tests {
589 /// with it: a sitting is never counted twice.581 /// with it: a sitting is never counted twice.
590 #[tokio::test]582 #[tokio::test]
591 async fn a_lost_start_race_never_counts_the_sitting_twice() {583 async fn a_lost_start_race_never_counts_the_sitting_twice() {
592- let db = init_mem().await.unwrap();584+ let (db, _leases) = init_test_db().await;
593 let (exam, _question) = open_exam_with_question(&db, 1).await;585 let (exam, _question) = open_exam_with_question(&db, 1).await;
594 let user = student(&db).await;586 let user = student(&db).await;
595 587
596 let (winner, _) = start(&db, &exam, &user).await.unwrap();588 let (winner, _) = start(&db, &exam, &user).await.unwrap();
597 assert_eq!(sat_total(&user, &db).await, 1);589 assert_eq!(sat_total(&user, &db).await, 1);
598 590
599- let claimed = cap::claim_and_create(591+ // The loser of the start race re-runs the same create: the composite
600- &user.record(),592+ // id answers Duplicate, the create is answered as a resume (the same
601- EXAM_SAT_TOTAL_FIELD,593+ // sitting, nothing new), and the counter increment the loser had
602- cap::UNLIMITED,594+ // claimed rolled back with its refused transaction.
603- &winner.id.record(),595+ let (resumed, created) = start(&db, &exam, &user).await.unwrap();
604- &winner,596+ assert!(!created, "the rival start must not have created anything");
605- &db,597+ assert_eq!(
606- )598+ resumed.get_seq(),
607- .await599+ winner.get_seq(),
608- .unwrap();600+ "the resume answers the winner's sitting, not a new one"
609- assert!(matches!(claimed, cap::Claimed::Duplicate));601+ );
610 assert_eq!(602 assert_eq!(
611 sat_total(&user, &db).await,603 sat_total(&user, &db).await,
612 1,604 1,
@@ -616,7 +608,7 @@ mod tests {
616 608
617 #[tokio::test]609 #[tokio::test]
618 async fn a_retake_preserves_the_prior_sittings_sheet() {610 async fn a_retake_preserves_the_prior_sittings_sheet() {
619- let db = init_mem().await.unwrap();611+ let (db, _leases) = init_test_db().await;
620 let (exam, question) = open_exam_with_question(&db, 2).await;612 let (exam, question) = open_exam_with_question(&db, 2).await;
621 let user = student(&db).await;613 let user = student(&db).await;
622 614
@@ -654,7 +646,7 @@ mod tests {
654 646
655 #[tokio::test]647 #[tokio::test]
656 async fn a_lost_retake_race_cannot_touch_the_winners_sheet() {648 async fn a_lost_retake_race_cannot_touch_the_winners_sheet() {
657- let db = init_mem().await.unwrap();649+ let (db, _leases) = init_test_db().await;
658 let (exam, question) = open_exam_with_question(&db, 3).await;650 let (exam, question) = open_exam_with_question(&db, 3).await;
659 let user = student(&db).await;651 let user = student(&db).await;
660 652
@@ -678,17 +670,15 @@ mod tests {
678 // A stale double-start races on the same seq and loses to the670 // A stale double-start races on the same seq and loses to the
679 // composite id: the duplicate create is rejected, and with no wipe in671 // composite id: the duplicate create is rejected, and with no wipe in
680 // the path the winner's fresh answer is untouched either way.672 // the path the winner's fresh answer is untouched either way.
681- let loser = ExamAttempt {673+ let lost = sqlx::query(
682- id: ExamAttemptId::composite(exam.get_id(), &user, 2),674+ "INSERT INTO exam_attempt (exam, app_user, seq, started_at) \
683- exam: exam.get_id().clone(),675+ VALUES ($1, $2, 2, $3)",
684- user: user.clone(),676+ )
685- seq: 2,677+ .bind(exam.get_id().uuid())
686- started_at: Timestamp::now(),678+ .bind(user.uuid())
687- finished_at: None,679+ .bind(Timestamp::now().as_millis())
688- left_at: None,680+ .execute(&db)
689- };681+ .await;
690- let lost: Result<Option<ExamAttempt>, surrealdb::Error> =
691- db.create(loser.id.record()).content(loser).await;
692 assert!(lost.is_err(), "the duplicate-seq create must be rejected");682 assert!(lost.is_err(), "the duplicate-seq create must be rejected");
693 let answers = exam_answer::list_for_exam_user(&db, exam.get_id(), &user, 2)683 let answers = exam_answer::list_for_exam_user(&db, exam.get_id(), &user, 2)
694 .await684 .await
src/service/fee_plan_assignment.rsmodified+2 -2
@@ -211,7 +211,7 @@ pub async fn list_for_student(
211 #[cfg(test)]211 #[cfg(test)]
212 mod tests {212 mod tests {
213 use super::*;213 use super::*;
214- use crate::database::init_mem;214+ use crate::database::init_test_db;
215 use crate::domain::fee_plan::{FeePlanName, Installment};215 use crate::domain::fee_plan::{FeePlanName, Installment};
216 use crate::domain::payment_ledger::LedgerAmount;216 use crate::domain::payment_ledger::LedgerAmount;
217 217
@@ -231,7 +231,7 @@ mod tests {
231 /// must not double a family's debt.231 /// must not double a family's debt.
232 #[tokio::test]232 #[tokio::test]
233 async fn assigning_bills_every_installment_and_a_replay_bills_nothing() {233 async fn assigning_bills_every_installment_and_a_replay_bills_nothing() {
234- let db = init_mem().await.unwrap();234+ let (db, _leases) = init_test_db().await;
235 let manager = UserId::from_key("mgr1");235 let manager = UserId::from_key("mgr1");
236 let student = UserId::from_key("stu1");236 let student = UserId::from_key("stu1");
237 let plan = a_plan(237 let plan = a_plan(
src/service/meal_booking.rsmodified+24 -16
@@ -289,7 +289,7 @@ fn refundable_after_lost_flip(seen: &MealBooking, live: &MealBooking) -> Result<
289 #[cfg(test)]289 #[cfg(test)]
290 mod tests {290 mod tests {
291 use super::*;291 use super::*;
292- use crate::database::init_mem;292+ use crate::database::init_test_db;
293 use crate::db::menu_dish;293 use crate::db::menu_dish;
294 use crate::domain::meal_booking::MealBookingStatus;294 use crate::domain::meal_booking::MealBookingStatus;
295 use crate::domain::meal_ledger::LedgerAmount;295 use crate::domain::meal_ledger::LedgerAmount;
@@ -305,14 +305,25 @@ mod tests {
305 }305 }
306 306
307 async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) {307 async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) {
308- let db = init_mem().await.unwrap();308+ let (db, _leases) = init_test_db().await;
309+ // The menu's creator is a foreign key now: a real `app_user` row.
310+ let creator = UserId::generate();
311+ sqlx::query(
312+ "INSERT INTO app_user (id, username, password_hash, role) \
313+ VALUES ($1, $2, 'x', 'teacher')",
314+ )
315+ .bind(creator.uuid())
316+ .bind(format!("menu-fixture-{}", &creator.key()[..8]))
317+ .execute(&db)
318+ .await
319+ .unwrap();
309 let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];320 let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];
310 let menu = menu::create(321 let menu = menu::create(
311 &db,322 &db,
312 MenuDate::try_new(date).unwrap(),323 MenuDate::try_new(date).unwrap(),
313 MenuSlot::try_new("lunch", &slots).unwrap(),324 MenuSlot::try_new("lunch", &slots).unwrap(),
314 capacity,325 capacity,
315- &UserId::generate(),326+ &creator,
316 )327 )
317 .await328 .await
318 .unwrap();329 .unwrap();
@@ -322,23 +333,20 @@ mod tests {
322 /// The stored counter, absent reading as zero — the number the cap's333 /// The stored counter, absent reading as zero — the number the cap's
323 /// `WHERE` actually compares, not one recomputed from the rows.334 /// `WHERE` actually compares, not one recomputed from the rows.
324 async fn seats(menu: &MenuId, db: &Database) -> i64 {335 async fn seats(menu: &MenuId, db: &Database) -> i64 {
325- let mut result = db336+ use sqlx::Row as _;
326- .query("SELECT VALUE seats_booked FROM $id")337+
327- .bind(("id", menu.record()))338+ sqlx::query("SELECT COALESCE(seats_booked, 0) FROM menu WHERE id = $1")
339+ .bind(menu.key())
340+ .fetch_one(db)
328 .await341 .await
329 .unwrap()342 .unwrap()
330- .check()343+ .try_get::<i64, _>(0)
331- .unwrap();
332- result
333- .take::<Vec<Option<i64>>>(0)
334 .unwrap()344 .unwrap()
335- .into_iter()
336- .next()
337- .flatten()
338- .unwrap_or(0)
339 }345 }
340 346
341 async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish {347 async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish {
348+ // A cap far above every seat count in these tests: the dish must never
349+ // be the binding constraint here.
342 menu_dish::create(350 menu_dish::create(
343 db,351 db,
344 menu,352 menu,
@@ -346,6 +354,7 @@ mod tests {
346 None,354 None,
347 DishPrice::try_new(price).unwrap(),355 DishPrice::try_new(price).unwrap(),
348 DishTags::try_new(&[], &[]).unwrap(),356 DishTags::try_new(&[], &[]).unwrap(),
357+ 1_000,
349 )358 )
350 .await359 .await
351 .unwrap()360 .unwrap()
@@ -541,7 +550,6 @@ mod tests {
541 let fresh = menu::read(&db, &menu).await.unwrap().unwrap();550 let fresh = menu::read(&db, &menu).await.unwrap().unwrap();
542 let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap();551 let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap();
543 let row = MealBooking {552 let row = MealBooking {
544- id: MealBookingId::composite(&menu, &ali),
545 menu: menu.clone(),553 menu: menu.clone(),
546 student: ali.clone(),554 student: ali.clone(),
547 booked_by: ali.clone(),555 booked_by: ali.clone(),
@@ -554,7 +562,7 @@ mod tests {
554 let charge = MealLedger::charge_for(&row, &ali);562 let charge = MealLedger::charge_for(&row, &ali);
555 let booked = match meal_booking::claim_and_place(563 let booked = match meal_booking::claim_and_place(
556 &db,564 &db,
557- &menu.record(),565+ &menu,
558 cap::UNLIMITED,566 cap::UNLIMITED,
559 fresh.get_version(),567 fresh.get_version(),
560 &row,568 &row,
src/service/payment_ledger.rsmodified+4 -4
@@ -365,7 +365,7 @@ mod tests {
365 PaymentRequestKey::try_new("abc_r").is_err(),365 PaymentRequestKey::try_new("abc_r").is_err(),
366 "the key that spelled a reversal's id must not parse"366 "the key that spelled a reversal's id must not parse"
367 );367 );
368- let db = crate::database::init_mem().await.unwrap();368+ let (db, _leases) = crate::database::init_test_db().await;
369 let (charge, _, manager) = one_charge(100, &db).await;369 let (charge, _, manager) = one_charge(100, &db).await;
370 let key = PaymentRequestKey::try_new("abc-r").unwrap();370 let key = PaymentRequestKey::try_new("abc-r").unwrap();
371 let credit_line = credit(371 let credit_line = credit(
@@ -424,7 +424,7 @@ mod tests {
424 /// a family unable to settle a bill the school itself refunded.424 /// a family unable to settle a bill the school itself refunded.
425 #[tokio::test]425 #[tokio::test]
426 async fn a_refund_frees_the_room_it_took_under_the_charge() {426 async fn a_refund_frees_the_room_it_took_under_the_charge() {
427- let db = crate::database::init_mem().await.unwrap();427+ let (db, _leases) = crate::database::init_test_db().await;
428 let (charge, student, manager) = one_charge(100, &db).await;428 let (charge, student, manager) = one_charge(100, &db).await;
429 let pay = |amount| {429 let pay = |amount| {
430 credit(430 credit(
@@ -475,7 +475,7 @@ mod tests {
475 /// out, so the room that refund freed is taken back.475 /// out, so the room that refund freed is taken back.
476 #[tokio::test]476 #[tokio::test]
477 async fn a_reversed_refund_takes_its_room_back() {477 async fn a_reversed_refund_takes_its_room_back() {
478- let db = crate::database::init_mem().await.unwrap();478+ let (db, _leases) = crate::database::init_test_db().await;
479 let (charge, _, manager) = one_charge(100, &db).await;479 let (charge, _, manager) = one_charge(100, &db).await;
480 let credit_line = credit(480 let credit_line = credit(
481 &db,481 &db,
@@ -528,7 +528,7 @@ mod tests {
528 use crate::db::fee_plan;528 use crate::db::fee_plan;
529 use crate::domain::fee_plan::{FeePlanName, Installment};529 use crate::domain::fee_plan::{FeePlanName, Installment};
530 530
531- let db = crate::database::init_mem().await.unwrap();531+ let (db, _leases) = crate::database::init_test_db().await;
532 let manager = UserId::from_key("mgr1");532 let manager = UserId::from_key("mgr1");
533 let student = UserId::from_key("stu1");533 let student = UserId::from_key("stu1");
534 let plan = fee_plan::create(534 let plan = fee_plan::create(
src/service/settings.rsmodified+121 -73
@@ -351,20 +351,30 @@ fn missing(before: &[String], after: &[String]) -> Vec<String> {
351 #[cfg(test)]351 #[cfg(test)]
352 mod tests {352 mod tests {
353 use super::*;353 use super::*;
354- use crate::database::init_mem;354+ use crate::database::init_test_db;
355 use crate::db::settings::save;355 use crate::db::settings::save;
356 356
357 /// The `retired` bit as the store holds it, `None` when no counter row was357 /// The `retired` bit as the store holds it, `None` when no counter row was
358 /// ever written — read back, never inferred from a return value.358 /// ever written — read back, never inferred from a return value.
359- async fn bit(db: &Database, counter: RecordId) -> Option<bool> {359+ async fn ref_bit(db: &Database, table: &str, name: &str) -> Option<bool> {
360- let mut result = db360+ let row = sqlx::query(&format!(
361- .query("SELECT VALUE retired FROM $id")361+ "SELECT retired FROM {table} WHERE name = $1"
362- .bind(("id", counter))362+ ))
363- .await363+ .bind(name)
364- .unwrap()364+ .fetch_optional(db)
365- .check()365+ .await
366- .unwrap();366+ .unwrap();
367- result.take::<Vec<bool>>(0).unwrap().first().copied()367+ row.map(|row| row.try_get::<bool, _>(0).unwrap())
368+ }
369+
370+ /// [`ref_bit`] against the exam-kind counters.
371+ async fn kind_bit(db: &Database, name: &str) -> Option<bool> {
372+ ref_bit(db, "kind_ref", name).await
373+ }
374+
375+ /// [`ref_bit`] against the meal-slot counters.
376+ async fn slot_bit(db: &Database, name: &str) -> Option<bool> {
377+ ref_bit(db, "slot_ref", name).await
368 }378 }
369 379
370 /// Two managers drop the same exam kind at once; one of them loses the380 /// Two managers drop the same exam kind at once; one of them loses the
@@ -377,29 +387,27 @@ mod tests {
377 /// records no undo, so `restore` has nothing to take back.387 /// records no undo, so `restore` has nothing to take back.
378 #[tokio::test]388 #[tokio::test]
379 async fn the_loser_of_a_settings_race_cannot_un_retire_the_winner_s_kind() {389 async fn the_loser_of_a_settings_race_cannot_un_retire_the_winner_s_kind() {
380- let db = init_mem().await.unwrap();390+ let (db, _leases) = init_test_db().await;
381- let counter = kind_ref("midterm");391+ // Two managers send the same removal, each having decided it against
382-392+ // the same original list. The winner's attempt retires the kind and
383- // The winner's PATCH retires the kind.393+ // saves; the loser's save loses the compare-and-set, aborts — taking
384- assert!(matches!(394+ // every write of its attempt back with it — and retries against the
385- cap::retire_name(&counter, &db).await.unwrap(),395+ // fresh list, where the same PATCH is a no-op that flips nothing.
386- cap::Switched::Flipped396+ // (The old engine needed a hand-rolled undo list for this; the
387- ));397+ // transaction's own rollback is the undo now.)
388-398+ let without_midterm = SettingsPatch {
389- // The loser's PATCH decides the same removal against the same snapshot,399+ exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),
390- // then its save is refused.400+ ..a_patch()
391- let mut undo = Vec::new();401+ };
392- if let cap::Switched::Flipped = cap::retire_name(&counter, &db).await.unwrap() {402+ apply(&db, &without_midterm).await.unwrap(); // the winner
393- undo.push(Undo::Retired(counter.clone()));403+ apply(&db, &without_midterm).await.unwrap(); // the loser, retried
394- }
395- assert!(undo.is_empty(), "a no-op retirement records no undo");
396- restore(&undo, &db).await.unwrap();
397 404
398 assert_eq!(405 assert_eq!(
399- bit(&db, counter).await,406+ kind_bit(&db, "midterm").await,
400 Some(true),407 Some(true),
401 "the winner's retirement must outlive the loser's rollback"408 "the winner's retirement must outlive the loser's rollback"
402 );409 );
410+ assert!(!stored(&db).await.0.contains(&"midterm".to_string()));
403 }411 }
404 412
405 /// The mirror hole: a re-*added* name is put back in service before the413 /// The mirror hole: a re-*added* name is put back in service before the
@@ -407,20 +415,37 @@ mod tests {
407 /// name is off the stored list with a counter that grades happily.415 /// name is off the stored list with a counter that grades happily.
408 #[tokio::test]416 #[tokio::test]
409 async fn a_rollback_re_retires_a_name_this_attempt_put_back_in_service() {417 async fn a_rollback_re_retires_a_name_this_attempt_put_back_in_service() {
410- let db = init_mem().await.unwrap();418+ let (db, _leases) = init_test_db().await;
411- let counter = slot_ref("lunch");419+ // The stored list drops lunch; the slot counter carries the retirement.
412- cap::retire_name(&counter, &db).await.unwrap();420+ let without = SettingsPatch {
413-421+ meal_slots: Some(slots(&["breakfast", "snack"])),
414- // The attempt re-adds the slot, then its save is refused.422+ ..a_patch()
415- let mut undo = Vec::new();423+ };
416- if let cap::Switched::Flipped = cap::unretire_name(&counter, &db).await.unwrap() {424+ apply(&db, &without).await.unwrap();
417- undo.push(Undo::Unretired(counter.clone()));425+ assert_eq!(slot_bit(&db, "lunch").await, Some(true));
418- }426+
419- assert_eq!(undo.len(), 1, "a real un-retirement is undoable");427+ // An attempt re-adds the slot but judged the write against the row
420- restore(&undo, &db).await.unwrap();428+ // *before* a rival's unrelated edit landed: its guarded save writes
429+ // zero rows, and — inside [`apply`] — the abort would take the
430+ // attempt's un-retirement straight back with it. Driven here at the
431+ // save the way the loser experiences it: refused, so nothing lands.
432+ let stale_snapshot = load(&db).await.unwrap();
433+ let elsewhere = SettingsPatch {
434+ max_file_bytes: Some(2048),
435+ ..a_patch()
436+ };
437+ apply(&db, &elsewhere).await.unwrap();
438+
439+ let mut params = Settings::defaults().params();
440+ params.meal_slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];
441+ let re_added = Settings::try_new(params).unwrap();
442+ let landed = crate::db::settings::save_if_unchanged(&db, re_added, &stale_snapshot)
443+ .await
444+ .unwrap();
445+ assert!(landed.is_none(), "the stale save must be refused");
421 446
422 assert_eq!(447 assert_eq!(
423- bit(&db, counter).await,448+ slot_bit(&db, "lunch").await,
424 Some(true),449 Some(true),
425 "a re-add that never landed must leave the slot retired"450 "a re-add that never landed must leave the slot retired"
426 );451 );
@@ -432,22 +457,33 @@ mod tests {
432 /// overwrite of a live reference.457 /// overwrite of a live reference.
433 #[tokio::test]458 #[tokio::test]
434 async fn a_rollback_leaves_a_name_that_gained_a_reference_in_service() {459 async fn a_rollback_leaves_a_name_that_gained_a_reference_in_service() {
435- let db = init_mem().await.unwrap();460+ let (db, _leases) = init_test_db().await;
436- let counter = slot_ref("lunch");461+ // Lunch goes away and comes back, and while it is in service a menu is
437- cap::retire_name(&counter, &db).await.unwrap();462+ // published against it — the live reference the counter counts.
438- cap::unretire_name(&counter, &db).await.unwrap();463+ let without = SettingsPatch {
439- db.query("UPDATE $id SET count = 1")464+ meal_slots: Some(slots(&["breakfast", "snack"])),
440- .bind(("id", counter.clone()))465+ ..a_patch()
441- .await466+ };
442- .unwrap()467+ apply(&db, &without).await.unwrap();
443- .check()468+ let with = SettingsPatch {
444- .unwrap();469+ meal_slots: Some(slots(&["breakfast", "lunch", "snack"])),
445-470+ ..a_patch()
446- restore(&[Undo::Unretired(counter.clone())], &db)471+ };
472+ apply(&db, &with).await.unwrap();
473+ sqlx::query("UPDATE slot_ref SET count = 1 WHERE name = 'lunch'")
474+ .execute(&db)
447 .await475 .await
448 .unwrap();476 .unwrap();
449 477
450- assert_eq!(bit(&db, counter).await, Some(false));478+ // The attempt that takes lunch away again now meets the reference: the
479+ // removal is refused — honestly, with the published-menu 409, not by
480+ // silently overwriting a live reference — and the slot stays usable.
481+ let refused = apply(&db, &without).await;
482+ assert!(
483+ matches!(refused, Err(AppError::ConflictOwned(ref msg)) if msg.contains("'lunch'")),
484+ "a referenced slot's removal must be refused: {refused:?}"
485+ );
486+ assert_eq!(slot_bit(&db, "lunch").await, Some(false));
451 }487 }
452 488
453 // --- the whole edit, driven the way two managers drive it -------------489 // --- the whole edit, driven the way two managers drive it -------------
@@ -513,7 +549,7 @@ mod tests {
513 /// legitimately removed — off the list and gradable.549 /// legitimately removed — off the list and gradable.
514 #[tokio::test]550 #[tokio::test]
515 async fn two_edits_dropping_the_same_kind_leave_it_retired() {551 async fn two_edits_dropping_the_same_kind_leave_it_retired() {
516- let db = init_mem().await.unwrap();552+ let (db, _leases) = init_test_db().await;
517 let without = SettingsPatch {553 let without = SettingsPatch {
518 exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),554 exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),
519 ..a_patch()555 ..a_patch()
@@ -529,7 +565,7 @@ mod tests {
529 "dropped from the list"565 "dropped from the list"
530 );566 );
531 assert_eq!(567 assert_eq!(
532- bit(&db, kind_ref("midterm")).await,568+ kind_bit(&db, "midterm").await,
533 Some(true),569 Some(true),
534 "a kind the stored list no longer offers must not grade"570 "a kind the stored list no longer offers must not grade"
535 );571 );
@@ -548,29 +584,41 @@ mod tests {
548 /// the other edit does may be visible until the pair completes.584 /// the other edit does may be visible until the pair completes.
549 #[tokio::test]585 #[tokio::test]
550 async fn a_rival_edit_cannot_run_between_a_retirement_and_its_save() {586 async fn a_rival_edit_cannot_run_between_a_retirement_and_its_save() {
551- let db = init_mem().await.unwrap();587+ let (db, _leases) = init_test_db().await;
552 let without = SettingsPatch {588 let without = SettingsPatch {
553 exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),589 exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),
554 ..a_patch()590 ..a_patch()
555 };591 };
556 592
557- let held = SETTINGS_LOCK.lock().await;593+ // The retire-then-save pair is one transaction, so a rival reading the
594+ // store while the edit runs can see the pair wholly unlanded or wholly
595+ // landed — never the retirement without the list commit that was the
596+ // old lock's whole job to prevent. Poll the edit from the outside and
597+ // assert that at every instant.
558 let rival = tokio::spawn({598 let rival = tokio::spawn({
559 let db = db.clone();599 let db = db.clone();
560 async move { apply(&db, &without).await.map(|_| ()) }600 async move { apply(&db, &without).await.map(|_| ()) }
561 });601 });
562- tokio::time::sleep(std::time::Duration::from_millis(200)).await;602+ while !rival.is_finished() {
563-603+ let (kinds, _) = stored(&db).await;
564- assert_eq!(604+ let retired = kind_bit(&db, "midterm").await;
565- bit(&db, kind_ref("midterm")).await,605+ if retired == Some(true) {
566- None,606+ assert!(
567- "a rival's pair must not have started, let alone half-landed"607+ !kinds.contains(&"midterm".to_string()),
568- );608+ "a retirement became visible before its list commit"
569- assert!(stored(&db).await.0.contains(&"midterm".to_string()));609+ );
610+ }
611+ if retired == Some(false) {
612+ assert!(
613+ kinds.contains(&"midterm".to_string()),
614+ "an un-retirement became visible before its list commit"
615+ );
616+ }
617+ tokio::task::yield_now().await;
618+ }
570 619
571- drop(held);
572 rival.await.unwrap().unwrap();620 rival.await.unwrap().unwrap();
573- assert_eq!(bit(&db, kind_ref("midterm")).await, Some(true));621+ assert_eq!(kind_bit(&db, "midterm").await, Some(true));
574 assert!(!stored(&db).await.0.contains(&"midterm".to_string()));622 assert!(!stored(&db).await.0.contains(&"midterm".to_string()));
575 }623 }
576 624
@@ -579,7 +627,7 @@ mod tests {
579 /// a listed kind that refuses every grade.627 /// a listed kind that refuses every grade.
580 #[tokio::test]628 #[tokio::test]
581 async fn two_edits_re_adding_the_same_kind_leave_it_in_service() {629 async fn two_edits_re_adding_the_same_kind_leave_it_in_service() {
582- let db = init_mem().await.unwrap();630+ let (db, _leases) = init_test_db().await;
583 let without = SettingsPatch {631 let without = SettingsPatch {
584 exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),632 exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),
585 ..a_patch()633 ..a_patch()
@@ -599,7 +647,7 @@ mod tests {
599 let (kinds, _) = stored(&db).await;647 let (kinds, _) = stored(&db).await;
600 assert!(kinds.contains(&"midterm".to_string()), "back on the list");648 assert!(kinds.contains(&"midterm".to_string()), "back on the list");
601 assert_eq!(649 assert_eq!(
602- bit(&db, kind_ref("midterm")).await,650+ kind_bit(&db, "midterm").await,
603 Some(false),651 Some(false),
604 "a kind the stored list offers must grade"652 "a kind the stored list offers must grade"
605 );653 );
@@ -608,7 +656,7 @@ mod tests {
608 /// The same pair over meal slots, which retire on their own counters.656 /// The same pair over meal slots, which retire on their own counters.
609 #[tokio::test]657 #[tokio::test]
610 async fn two_edits_dropping_the_same_slot_leave_it_retired() {658 async fn two_edits_dropping_the_same_slot_leave_it_retired() {
611- let db = init_mem().await.unwrap();659+ let (db, _leases) = init_test_db().await;
612 let without = SettingsPatch {660 let without = SettingsPatch {
613 meal_slots: Some(slots(&["breakfast", "snack"])),661 meal_slots: Some(slots(&["breakfast", "snack"])),
614 ..a_patch()662 ..a_patch()
@@ -620,7 +668,7 @@ mod tests {
620 668
621 let (_, stored_slots) = stored(&db).await;669 let (_, stored_slots) = stored(&db).await;
622 assert!(!stored_slots.contains(&"lunch".to_string()));670 assert!(!stored_slots.contains(&"lunch".to_string()));
623- assert_eq!(bit(&db, slot_ref("lunch")).await, Some(true));671+ assert_eq!(slot_bit(&db, "lunch").await, Some(true));
624 }672 }
625 673
626 // --- the stale slot name that wedged the whole list -------------------674 // --- the stale slot name that wedged the whole list -------------------
@@ -641,7 +689,7 @@ mod tests {
641 /// stored name is submittable; a new one with the same characters is not.689 /// stored name is submittable; a new one with the same characters is not.
642 #[tokio::test]690 #[tokio::test]
643 async fn a_stored_slot_name_stays_submittable_but_a_new_one_does_not() {691 async fn a_stored_slot_name_stays_submittable_but_a_new_one_does_not() {
644- let db = init_mem().await.unwrap();692+ let (db, _leases) = init_test_db().await;
645 a_school_with_a_stale_slot(&db).await;693 a_school_with_a_stale_slot(&db).await;
646 694
647 let edit = SettingsPatch {695 let edit = SettingsPatch {
@@ -666,7 +714,7 @@ mod tests {
666 /// over unvalidated — the behaviour the wedge report leaned on.714 /// over unvalidated — the behaviour the wedge report leaned on.
667 #[tokio::test]715 #[tokio::test]
668 async fn an_unrelated_edit_carries_a_stale_slot_name_over() {716 async fn an_unrelated_edit_carries_a_stale_slot_name_over() {
669- let db = init_mem().await.unwrap();717+ let (db, _leases) = init_test_db().await;
670 a_school_with_a_stale_slot(&db).await;718 a_school_with_a_stale_slot(&db).await;
671 719
672 let elsewhere = SettingsPatch {720 let elsewhere = SettingsPatch {
src/service/user.rsmodified+4 -4
@@ -210,7 +210,7 @@ pub async fn set_preferences(
210 #[cfg(test)]210 #[cfg(test)]
211 mod tests {211 mod tests {
212 use super::*;212 use super::*;
213- use crate::database::{Database, init_mem};213+ use crate::database::{Database, init_test_db};
214 use crate::domain::user::Password;214 use crate::domain::user::Password;
215 215
216 async fn a_user(username: &str, db: &Database) -> User {216 async fn a_user(username: &str, db: &Database) -> User {
@@ -236,7 +236,7 @@ mod tests {
236 async fn the_cascade_returns_the_boards_it_stripped() {236 async fn the_cascade_returns_the_boards_it_stripped() {
237 use crate::domain::board::BoardTitle;237 use crate::domain::board::BoardTitle;
238 238
239- let db = init_mem().await.unwrap();239+ let (db, _leases) = init_test_db().await;
240 let creator = a_user("ogretmen", &db).await;240 let creator = a_user("ogretmen", &db).await;
241 let guest = a_user("ogrenci", &db).await;241 let guest = a_user("ogrenci", &db).await;
242 let board = crate::db::board::create(242 let board = crate::db::board::create(
@@ -276,7 +276,7 @@ mod tests {
276 use crate::domain::board::BoardTitle;276 use crate::domain::board::BoardTitle;
277 use crate::domain::board_stroke::BOARD_CLOSED;277 use crate::domain::board_stroke::BOARD_CLOSED;
278 278
279- let db = init_mem().await.unwrap();279+ let (db, _leases) = init_test_db().await;
280 let creator = a_user("ogretmen", &db).await;280 let creator = a_user("ogretmen", &db).await;
281 let guest = a_user("ogrenci", &db).await;281 let guest = a_user("ogrenci", &db).await;
282 let board = crate::db::board::create(282 let board = crate::db::board::create(
@@ -352,7 +352,7 @@ mod tests {
352 use crate::domain::timestamp::Timestamp;352 use crate::domain::timestamp::Timestamp;
353 use crate::service::appointment;353 use crate::service::appointment;
354 354
355- let db = init_mem().await.unwrap();355+ let (db, _leases) = init_test_db().await;
356 let staff = |name: &'static str, db: Database| async move {356 let staff = |name: &'static str, db: Database| async move {
357 let teacher = a_user(name, &db).await;357 let teacher = a_user(name, &db).await;
358 set_role(&db, teacher.get_id(), Role::Teacher)358 set_role(&db, teacher.get_id(), Role::Teacher)
src/web/appointments.rsmodified+5 -5
@@ -58,7 +58,7 @@ struct PublishSlots {
58 #[derive(Deserialize, ToSchema)]58 #[derive(Deserialize, ToSchema)]
59 struct BookAppointment {59 struct BookAppointment {
60 /// The slot to take, from `GET /appointments/slots`.60 /// The slot to take, from `GET /appointments/slots`.
61- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]61+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
62 slot: String,62 slot: String,
63 /// Why you want the meeting — required, the teacher decides on it.63 /// Why you want the meeting — required, the teacher decides on it.
64 #[schema(max_length = 1000, example = "Ders notlarını konuşmak istiyorum")]64 #[schema(max_length = 1000, example = "Ders notlarını konuşmak istiyorum")]
@@ -103,7 +103,7 @@ struct AcceptReschedule {
103 103
104 #[derive(Serialize, ToSchema)]104 #[derive(Serialize, ToSchema)]
105 struct SlotResponse {105 struct SlotResponse {
106- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]106+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
107 id: String,107 id: String,
108 /// Whose calendar this is.108 /// Whose calendar this is.
109 teacher: PersonRef,109 teacher: PersonRef,
@@ -134,7 +134,7 @@ impl SlotResponse {
134 134
135 #[derive(Serialize, ToSchema)]135 #[derive(Serialize, ToSchema)]
136 struct AppointmentResponse {136 struct AppointmentResponse {
137- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]137+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
138 id: String,138 id: String,
139 /// The slot this booking sits on.139 /// The slot this booking sits on.
140 slot: String,140 slot: String,
@@ -901,7 +901,7 @@ async fn ensure_requester(
901 #[cfg(test)]901 #[cfg(test)]
902 mod tests {902 mod tests {
903 use super::*;903 use super::*;
904- use crate::database::init_mem;904+ use crate::database::init_test_db;
905 use crate::domain::user::{Password, Username};905 use crate::domain::user::{Password, Username};
906 906
907 /// A user at `role`, minted through the real create path.907 /// A user at `role`, minted through the real create path.
@@ -922,7 +922,7 @@ mod tests {
922 /// level that has to hold when the next route arrives with `CurrentUser`.922 /// level that has to hold when the next route arrives with `CurrentUser`.
923 #[tokio::test]923 #[tokio::test]
924 async fn demoted_slot_owner_loses_management() {924 async fn demoted_slot_owner_loses_management() {
925- let db = init_mem().await.unwrap();925+ let (db, _leases) = init_test_db().await;
926 let owner = user("ogretmen", Role::Teacher, &db).await;926 let owner = user("ogretmen", Role::Teacher, &db).await;
927 let slot = service::appointment_slot::create(927 let slot = service::appointment_slot::create(
928 &db,928 &db,
src/web/bank_questions.rsmodified+4 -4
@@ -94,7 +94,7 @@ struct CreateBankQuestion {
94 /// school's subjects; it is *not* held to a course here (the bank spans94 /// school's subjects; it is *not* held to a course here (the bank spans
95 /// courses), only checked against the target exam's course when the95 /// courses), only checked against the target exam's course when the
96 /// template is instantiated.96 /// template is instantiated.
97- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]97+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
98 subject_id: String,98 subject_id: String,
99 #[schema(example = "What is 2 + 2?", max_length = 2000)]99 #[schema(example = "What is 2 + 2?", max_length = 2000)]
100 text: String,100 text: String,
@@ -921,7 +921,7 @@ async fn delete_choice_image(
921 #[cfg(test)]921 #[cfg(test)]
922 mod tests {922 mod tests {
923 use super::*;923 use super::*;
924- use crate::database::{Database, init_mem};924+ use crate::database::{Database, init_test_db};
925 use crate::domain::role::Role;925 use crate::domain::role::Role;
926 use crate::domain::user::{Password, Username};926 use crate::domain::user::{Password, Username};
927 927
@@ -946,12 +946,12 @@ mod tests {
946 /// must hold when a future route arrives with a different extractor.946 /// must hold when a future route arrives with a different extractor.
947 #[tokio::test]947 #[tokio::test]
948 async fn demoted_owner_loses_their_own_template() {948 async fn demoted_owner_loses_their_own_template() {
949- let db = init_mem().await.unwrap();949+ let (db, _leases) = init_test_db().await;
950 let owner = user("ogretmen", Role::Teacher, &db).await;950 let owner = user("ogretmen", Role::Teacher, &db).await;
951 let question = bank_question::create(951 let question = bank_question::create(
952 &db,952 &db,
953 owner.get_id().clone(),953 owner.get_id().clone(),
954- SubjectId::from_key("01TESTSUBJECTAAAAAAAAAAAAA"),954+ SubjectId::from_key("019732e3-7b00-7000-8000-00000000a2b3"),
955 QuestionText::try_new("2 + 2 = ?").unwrap(),955 QuestionText::try_new("2 + 2 = ?").unwrap(),
956 QuestionPoints::try_new(1).unwrap(),956 QuestionPoints::try_new(1).unwrap(),
957 QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(),957 QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(),
src/web/board_ws.rsmodified+1 -1
@@ -674,7 +674,7 @@ mod tests {
674 use crate::domain::board::BoardTitle;674 use crate::domain::board::BoardTitle;
675 use crate::domain::user::{Password, Username};675 use crate::domain::user::{Password, Username};
676 676
677- let db = crate::database::init_mem().await.unwrap();677+ let (db, _leases) = crate::database::init_test_db().await;
678 let password = Password::try_new("secret1").unwrap();678 let password = Password::try_new("secret1").unwrap();
679 let creator = crate::service::user::create(679 let creator = crate::service::user::create(
680 &db,680 &db,
src/web/chatbot.rsmodified+5 -5
@@ -77,7 +77,7 @@ struct CreateChatbotThread {
77 /// sorted by it, so the thread just written to is always first.77 /// sorted by it, so the thread just written to is always first.
78 #[derive(Serialize, ToSchema)]78 #[derive(Serialize, ToSchema)]
79 struct ChatbotThreadResponse {79 struct ChatbotThreadResponse {
80- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]80+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
81 id: String,81 id: String,
82 #[schema(example = "Fizik ödevi")]82 #[schema(example = "Fizik ödevi")]
83 title: Option<String>,83 title: Option<String>,
@@ -261,7 +261,7 @@ struct SendChatbotMessage {
261 #[derive(Serialize, ToSchema)]261 #[derive(Serialize, ToSchema)]
262 struct AcceptedResponse {262 struct AcceptedResponse {
263 /// The assistant row reserved for the answer.263 /// The assistant row reserved for the answer.
264- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]264+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
265 message_id: String,265 message_id: String,
266 /// Always `pending` — that is what "accepted" means here.266 /// Always `pending` — that is what "accepted" means here.
267 #[schema(example = "pending")]267 #[schema(example = "pending")]
@@ -272,9 +272,9 @@ struct AcceptedResponse {
272 /// set only when `status` is `failed`.272 /// set only when `status` is `failed`.
273 #[derive(Serialize, ToSchema)]273 #[derive(Serialize, ToSchema)]
274 struct ChatbotMessageResponse {274 struct ChatbotMessageResponse {
275- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]275+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
276 id: String,276 id: String,
277- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]277+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
278 thread_id: String,278 thread_id: String,
279 /// `user` or `assistant`.279 /// `user` or `assistant`.
280 #[schema(example = "assistant")]280 #[schema(example = "assistant")]
@@ -900,7 +900,7 @@ mod tests {
900 // A run of failed answers must make the window reach further back, not900 // A run of failed answers must make the window reach further back, not
901 // shrink it: filtering a fixed-size tail after the fact handed the901 // shrink it: filtering a fixed-size tail after the fact handed the
902 // service a handful of unanswered prompts and nothing older.902 // service a handful of unanswered prompts and nothing older.
903- let db = crate::database::init_mem().await.unwrap();903+ let (db, _leases) = crate::database::init_test_db().await;
904 // A real thread row: every turn is written through it, so a turn with904 // A real thread row: every turn is written through it, so a turn with
905 // no thread is refused.905 // no thread is refused.
906 db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0")906 db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0")
src/web/classes.rsmodified+1 -1
@@ -1496,7 +1496,7 @@ mod tests {
1496 use crate::domain::role::Role;1496 use crate::domain::role::Role;
1497 use crate::domain::user::{Password, Username};1497 use crate::domain::user::{Password, Username};
1498 1498
1499- let db = crate::database::init_mem().await.unwrap();1499+ let (db, _leases) = crate::database::init_test_db().await;
1500 assert!(teacher_or_none(None, &db).await.unwrap().is_none());1500 assert!(teacher_or_none(None, &db).await.unwrap().is_none());
1501 assert!(teacher_or_none(Some(""), &db).await.unwrap().is_none());1501 assert!(teacher_or_none(Some(""), &db).await.unwrap().is_none());
1502 1502
src/web/course_notes.rsmodified+2 -2
@@ -68,7 +68,7 @@ async fn note_with_course(id: &str, db: &Database) -> Result<(CourseNote, Course
68 68
69 #[derive(Deserialize, ToSchema)]69 #[derive(Deserialize, ToSchema)]
70 struct CreateCourseNote {70 struct CreateCourseNote {
71- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]71+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
72 course: String,72 course: String,
73 #[schema(example = "Chapter 3 recap", max_length = 200)]73 #[schema(example = "Chapter 3 recap", max_length = 200)]
74 title: String,74 title: String,
@@ -153,7 +153,7 @@ async fn create(
153 #[derive(Deserialize, IntoParams)]153 #[derive(Deserialize, IntoParams)]
154 struct CourseFilter {154 struct CourseFilter {
155 /// The course to list notes for (required).155 /// The course to list notes for (required).
156- #[param(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]156+ #[param(example = "019732e3-7b00-7000-8000-00000000dead")]
157 course: String,157 course: String,
158 }158 }
159 159
src/web/courses.rsmodified+10 -10
@@ -108,7 +108,7 @@ struct UpdateCourse {
108 #[derive(Deserialize, ToSchema)]108 #[derive(Deserialize, ToSchema)]
109 struct EnrollUser {109 struct EnrollUser {
110 /// The user to enroll.110 /// The user to enroll.
111- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]111+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
112 user_id: String,112 user_id: String,
113 }113 }
114 114
@@ -116,7 +116,7 @@ struct EnrollUser {
116 struct AssignTeacher {116 struct AssignTeacher {
117 /// The staff member to put in charge of the course. Must hold the117 /// The staff member to put in charge of the course. Must hold the
118 /// `teacher` role or higher.118 /// `teacher` role or higher.
119- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]119+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
120 user_id: String,120 user_id: String,
121 }121 }
122 122
@@ -177,7 +177,7 @@ struct EnrollmentResponse {
177 /// class drops the student or detaches the course; a `null` one is nobody's177 /// class drops the student or detaches the course; a `null` one is nobody's
178 /// to take back. Without it no client could tell which of its roster rows a178 /// to take back. Without it no client could tell which of its roster rows a
179 /// class change is about to remove.179 /// class change is about to remove.
180- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]180+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
181 source: Option<String>,181 source: Option<String>,
182 }182 }
183 183
@@ -1020,7 +1020,7 @@ struct CreateHomework {
1020 /// The course subject this homework belongs to1020 /// The course subject this homework belongs to
1021 /// (`GET /courses/{id}/subjects`). Required — every homework is tagged with1021 /// (`GET /courses/{id}/subjects`). Required — every homework is tagged with
1022 /// one of its course's subjects.1022 /// one of its course's subjects.
1023- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]1023+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
1024 subject_id: String,1024 subject_id: String,
1025 /// When the homework is due, UTC unix-milliseconds. Required; must not be1025 /// When the homework is due, UTC unix-milliseconds. Required; must not be
1026 /// in the past. Late submissions are still accepted, just flagged late.1026 /// in the past. Late submissions are still accepted, just flagged late.
@@ -1282,7 +1282,7 @@ async fn list_course_sessions(
1282 #[cfg(test)]1282 #[cfg(test)]
1283 mod tests {1283 mod tests {
1284 use super::*;1284 use super::*;
1285- use crate::database::init_mem;1285+ use crate::database::init_test_db;
1286 use crate::domain::user::{Password, Username};1286 use crate::domain::user::{Password, Username};
1287 1287
1288 /// A user at `role`, minted through the real create path.1288 /// A user at `role`, minted through the real create path.
@@ -1320,7 +1320,7 @@ mod tests {
1320 /// so the grant itself has to re-read the live role on every call.1320 /// so the grant itself has to re-read the live role on every call.
1321 #[tokio::test]1321 #[tokio::test]
1322 async fn demoted_creator_loses_management_and_ownership() {1322 async fn demoted_creator_loses_management_and_ownership() {
1323- let db = init_mem().await.unwrap();1323+ let (db, _leases) = init_test_db().await;
1324 let creator = user("teacher", Role::Teacher, &db).await;1324 let creator = user("teacher", Role::Teacher, &db).await;
1325 let course = course(&creator, &db).await;1325 let course = course(&creator, &db).await;
1326 assert!(can_manage_course(&course, &creator));1326 assert!(can_manage_course(&course, &creator));
@@ -1346,7 +1346,7 @@ mod tests {
1346 /// but the grant must not depend on that sweep having run.1346 /// but the grant must not depend on that sweep having run.
1347 #[tokio::test]1347 #[tokio::test]
1348 async fn demoted_assigned_teacher_loses_management() {1348 async fn demoted_assigned_teacher_loses_management() {
1349- let db = init_mem().await.unwrap();1349+ let (db, _leases) = init_test_db().await;
1350 let creator = user("creator", Role::Teacher, &db).await;1350 let creator = user("creator", Role::Teacher, &db).await;
1351 let assigned = user("assigned", Role::Teacher, &db).await;1351 let assigned = user("assigned", Role::Teacher, &db).await;
1352 let course =1352 let course =
@@ -1372,13 +1372,13 @@ mod tests {
1372 /// hand the office staff somebody else's lesson.1372 /// hand the office staff somebody else's lesson.
1373 #[tokio::test]1373 #[tokio::test]
1374 async fn a_manager_scheduling_a_lesson_names_the_teacher_not_themselves() {1374 async fn a_manager_scheduling_a_lesson_names_the_teacher_not_themselves() {
1375- let db = init_mem().await.unwrap();1375+ let (db, _leases) = init_test_db().await;
1376 let manager = user("manager", Role::Manager, &db).await;1376 let manager = user("manager", Role::Manager, &db).await;
1377 let teacher = user("teacher", Role::Teacher, &db).await;1377 let teacher = user("teacher", Role::Teacher, &db).await;
1378 let course = course(&manager, &db).await;1378 let course = course(&manager, &db).await;
1379 let st = AppState {1379 let st = AppState {
1380 db: db.clone(),1380 db: db.clone(),
1381- tenants: crate::database::init_mem_tenants().await.unwrap(),1381+ tenants: crate::database::init_test_tenants().await,
1382 files_path: std::env::temp_dir(),1382 files_path: std::env::temp_dir(),
1383 cookie_secure: false,1383 cookie_secure: false,
1384 rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),1384 rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),
@@ -1417,7 +1417,7 @@ mod tests {
1417 /// creator was demoted and which has no assigned teachers.1417 /// creator was demoted and which has no assigned teachers.
1418 #[tokio::test]1418 #[tokio::test]
1419 async fn manager_still_manages_a_demoted_creators_course() {1419 async fn manager_still_manages_a_demoted_creators_course() {
1420- let db = init_mem().await.unwrap();1420+ let (db, _leases) = init_test_db().await;
1421 let creator = user("teacher", Role::Teacher, &db).await;1421 let creator = user("teacher", Role::Teacher, &db).await;
1422 let course = course(&creator, &db).await;1422 let course = course(&creator, &db).await;
1423 crate::service::user::set_role(&db, creator.get_id(), Role::Student)1423 crate::service::user::set_role(&db, creator.get_id(), Role::Student)
src/web/dto.rsmodified+5 -5
@@ -74,7 +74,7 @@ impl From<DomainRole> for Role {
74 /// show a raw ULID to a human.74 /// show a raw ULID to a human.
75 #[derive(Serialize, Clone, ToSchema)]75 #[derive(Serialize, Clone, ToSchema)]
76 pub struct PersonRef {76 pub struct PersonRef {
77- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]77+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
78 pub id: String,78 pub id: String,
79 #[schema(example = "ada")]79 #[schema(example = "ada")]
80 pub username: String,80 pub username: String,
@@ -151,7 +151,7 @@ pub async fn person_map(
151 /// (register/login/me) and `users` (listing, role and profile changes).151 /// (register/login/me) and `users` (listing, role and profile changes).
152 #[derive(Serialize, ToSchema)]152 #[derive(Serialize, ToSchema)]
153 pub struct UserResponse {153 pub struct UserResponse {
154- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]154+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
155 pub id: String,155 pub id: String,
156 #[schema(example = "ada")]156 #[schema(example = "ada")]
157 pub username: String,157 pub username: String,
@@ -212,7 +212,7 @@ impl UserResponse {
212 /// blocks embed the course they average).212 /// blocks embed the course they average).
213 #[derive(Serialize, ToSchema)]213 #[derive(Serialize, ToSchema)]
214 pub struct CourseResponse {214 pub struct CourseResponse {
215- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]215+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
216 pub id: String,216 pub id: String,
217 /// Who created (and owns) the course. Only they and managers/admins may217 /// Who created (and owns) the course. Only they and managers/admins may
218 /// delete it or change who teaches it.218 /// delete it or change who teaches it.
@@ -268,7 +268,7 @@ impl CourseResponse {
268 /// delete).268 /// delete).
269 #[derive(Serialize, ToSchema)]269 #[derive(Serialize, ToSchema)]
270 pub struct SubjectResponse {270 pub struct SubjectResponse {
271- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]271+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
272 pub id: String,272 pub id: String,
273 /// The course whose curriculum this subject belongs to.273 /// The course whose curriculum this subject belongs to.
274 pub course: String,274 pub course: String,
@@ -296,7 +296,7 @@ impl SubjectResponse {
296 /// submission (against `due_at`), never stored on the homework itself.296 /// submission (against `due_at`), never stored on the homework itself.
297 #[derive(Serialize, ToSchema)]297 #[derive(Serialize, ToSchema)]
298 pub struct HomeworkResponse {298 pub struct HomeworkResponse {
299- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]299+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
300 pub id: String,300 pub id: String,
301 /// The course this homework belongs to.301 /// The course this homework belongs to.
302 pub course: String,302 pub course: String,
src/web/events.rsmodified+2 -2
@@ -912,7 +912,7 @@ async fn unregister(
912 #[cfg(test)]912 #[cfg(test)]
913 mod tests {913 mod tests {
914 use super::*;914 use super::*;
915- use crate::database::init_mem;915+ use crate::database::init_test_db;
916 use crate::domain::user::{Password, Username};916 use crate::domain::user::{Password, Username};
917 917
918 /// A user at `role`, minted through the real create path.918 /// A user at `role`, minted through the real create path.
@@ -936,7 +936,7 @@ mod tests {
936 /// helper is what must hold when a future route arrives with `CurrentUser`.936 /// helper is what must hold when a future route arrives with `CurrentUser`.
937 #[tokio::test]937 #[tokio::test]
938 async fn demoted_event_creator_loses_management() {938 async fn demoted_event_creator_loses_management() {
939- let db = init_mem().await.unwrap();939+ let (db, _leases) = init_test_db().await;
940 let creator = user("ogretmen", Role::Teacher, &db).await;940 let creator = user("ogretmen", Role::Teacher, &db).await;
941 let event = service::event::create(941 let event = service::event::create(
942 &db,942 &db,
src/web/exams/mod.rsmodified+1 -1
@@ -183,7 +183,7 @@ struct GradeResult {
183 #[schema(example = 85, minimum = 0, maximum = 100)]183 #[schema(example = 85, minimum = 0, maximum = 100)]
184 mark: i64,184 mark: i64,
185 /// The student being graded.185 /// The student being graded.
186- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]186+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
187 user_id: String,187 user_id: String,
188 }188 }
189 189
src/web/exams/questions.rsmodified+2 -2
@@ -14,7 +14,7 @@ use crate::service::exam_question;
14 pub(crate) struct CreateQuestion {14 pub(crate) struct CreateQuestion {
15 /// The subject this question belongs to — one of the exam's course's15 /// The subject this question belongs to — one of the exam's course's
16 /// subjects (`GET /courses/{id}/subjects`). Required.16 /// subjects (`GET /courses/{id}/subjects`). Required.
17- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]17+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
18 subject_id: String,18 subject_id: String,
19 /// The question itself.19 /// The question itself.
20 #[schema(example = "What is 2 + 2?", max_length = 2000)]20 #[schema(example = "What is 2 + 2?", max_length = 2000)]
@@ -435,7 +435,7 @@ pub(crate) async fn delete_question(
435 pub(crate) struct InstantiateFromBank {435 pub(crate) struct InstantiateFromBank {
436 /// The subject to file the new question under — one of the exam's course's436 /// The subject to file the new question under — one of the exam's course's
437 /// subjects (the same-course rule the bank row itself is exempt from).437 /// subjects (the same-course rule the bank row itself is exempt from).
438- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]438+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
439 subject_id: String,439 subject_id: String,
440 }440 }
441 441
src/web/homework.rsmodified+2 -2
@@ -407,7 +407,7 @@ async fn delete_homework(
407 /// separately from `GET /homework/{id}/submission/files/{fid}`.407 /// separately from `GET /homework/{id}/submission/files/{fid}`.
408 #[derive(Serialize, ToSchema)]408 #[derive(Serialize, ToSchema)]
409 struct HomeworkFileResponse {409 struct HomeworkFileResponse {
410- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]410+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
411 id: String,411 id: String,
412 /// The uploader's original filename.412 /// The uploader's original filename.
413 #[schema(example = "odev.pdf")]413 #[schema(example = "odev.pdf")]
@@ -886,7 +886,7 @@ async fn delete_submission_file(
886 #[derive(Deserialize, ToSchema)]886 #[derive(Deserialize, ToSchema)]
887 struct GradeHomework {887 struct GradeHomework {
888 /// The student being graded.888 /// The student being graded.
889- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]889+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
890 user: String,890 user: String,
891 /// The verdict: `done`, `incomplete`, or `missing`.891 /// The verdict: `done`, `incomplete`, or `missing`.
892 #[schema(example = "done")]892 #[schema(example = "done")]
src/web/messages.rsmodified+1 -1
@@ -30,7 +30,7 @@ pub fn routes() -> OpenApiRouter<AppState> {
30 #[derive(Deserialize, ToSchema)]30 #[derive(Deserialize, ToSchema)]
31 struct SendMessage {31 struct SendMessage {
32 /// The receiving user's id (find people via `GET /users/search`).32 /// The receiving user's id (find people via `GET /users/search`).
33- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]33+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
34 recipient_id: String,34 recipient_id: String,
35 #[schema(example = "About today's study session", max_length = 200)]35 #[schema(example = "About today's study session", max_length = 200)]
36 subject: String,36 subject: String,
src/web/mod.rsmodified+1 -1
@@ -380,7 +380,7 @@ mod tests {
380 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};380 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
381 use crate::domain::user::{Password, Username};381 use crate::domain::user::{Password, Username};
382 382
383- let db = crate::database::init_mem().await.unwrap();383+ let (db, _leases) = crate::database::init_test_db().await;
384 let office = UserId::from_key("office");384 let office = UserId::from_key("office");
385 let teacher = crate::service::user::create(385 let teacher = crate::service::user::create(
386 &db,386 &db,
src/web/payments.rsmodified+2 -2
@@ -333,7 +333,7 @@ async fn delete_plan(
333 struct AssignFeePlan {333 struct AssignFeePlan {
334 /// The students to place on the plan, at most 200 per call. Each is334 /// The students to place on the plan, at most 200 per call. Each is
335 /// reported on individually — one bad id does not lose the rest.335 /// reported on individually — one bad id does not lose the rest.
336- #[schema(max_items = 200, example = json!(["01JC0Z0Z0Z0Z0Z0Z0Z0Z0Z0Z0Z"]))]336+ #[schema(max_items = 200, example = json!(["019732e3-7b00-7000-8000-000000000a0b"]))]
337 student_ids: Vec<String>,337 student_ids: Vec<String>,
338 }338 }
339 339
@@ -1086,7 +1086,7 @@ mod tests {
1086 /// shape of `source` links is exactly what the fold walks.1086 /// shape of `source` links is exactly what the fold walks.
1087 #[tokio::test]1087 #[tokio::test]
1088 async fn the_statement_rolls_each_charge_up_from_its_own_lines() {1088 async fn the_statement_rolls_each_charge_up_from_its_own_lines() {
1089- let db = crate::database::init_mem().await.unwrap();1089+ let (db, _leases) = crate::database::init_test_db().await;
1090 let manager = UserId::from_key("mgr1");1090 let manager = UserId::from_key("mgr1");
1091 let student = UserId::from_key("stu1");1091 let student = UserId::from_key("stu1");
1092 let future = Timestamp::now().as_millis() + 30 * 24 * 60 * 60 * 1000;1092 let future = Timestamp::now().as_millis() + 30 * 24 * 60 * 60 * 1000;
src/web/tenant_state.rsmodified+3 -3
@@ -180,7 +180,7 @@ mod tests {
180 use axum::{Router, body::Body, http::Request};180 use axum::{Router, body::Body, http::Request};
181 use tower::ServiceExt;181 use tower::ServiceExt;
182 182
183- use crate::database::init_mem_tenants;183+ use crate::database::init_test_tenants;
184 use crate::db::session;184 use crate::db::session;
185 use crate::domain::user::{Password, Username};185 use crate::domain::user::{Password, Username};
186 use crate::tenant::DEMO_SLUG;186 use crate::tenant::DEMO_SLUG;
@@ -197,7 +197,7 @@ mod tests {
197 /// A two-route app, one live cookie of each kind, and the registry behind197 /// A two-route app, one live cookie of each kind, and the registry behind
198 /// them.198 /// them.
199 async fn harness() -> (Router, String, String, crate::tenant::Tenants) {199 async fn harness() -> (Router, String, String, crate::tenant::Tenants) {
200- let tenants = init_mem_tenants().await.expect("in-memory deployment");200+ let tenants = init_test_tenants().await;
201 let school = tenants201 let school = tenants
202 .get(&Slug::try_new(DEMO_SLUG).unwrap())202 .get(&Slug::try_new(DEMO_SLUG).unwrap())
203 .await203 .await
@@ -343,7 +343,7 @@ mod tests {
343 /// still passes — the verdict came from the memoized extension.343 /// still passes — the verdict came from the memoized extension.
344 #[tokio::test]344 #[tokio::test]
345 async fn a_request_resolves_its_school_exactly_once() {345 async fn a_request_resolves_its_school_exactly_once() {
346- let tenants = init_mem_tenants().await.expect("in-memory deployment");346+ let tenants = init_test_tenants().await;
347 let demo = Slug::try_new(DEMO_SLUG).unwrap();347 let demo = Slug::try_new(DEMO_SLUG).unwrap();
348 let state = AppState {348 let state = AppState {
349 db: tenants.control().clone(),349 db: tenants.control().clone(),
src/web/users.rsmodified+3 -3
@@ -706,7 +706,7 @@ async fn my_students(
706 /// A user's public profile. Contact details are not part of it, at any role.706 /// A user's public profile. Contact details are not part of it, at any role.
707 #[derive(Serialize, ToSchema)]707 #[derive(Serialize, ToSchema)]
708 struct ProfileResponse {708 struct ProfileResponse {
709- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]709+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
710 id: String,710 id: String,
711 #[schema(example = "ada")]711 #[schema(example = "ada")]
712 username: String,712 username: String,
@@ -763,7 +763,7 @@ struct ProfileAvatar {
763 /// `GET /classes/{id}`, which is teacher+.763 /// `GET /classes/{id}`, which is teacher+.
764 #[derive(Serialize, ToSchema)]764 #[derive(Serialize, ToSchema)]
765 struct ProfileClassRef {765 struct ProfileClassRef {
766- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]766+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
767 id: String,767 id: String,
768 #[schema(example = "9-A")]768 #[schema(example = "9-A")]
769 name: String,769 name: String,
@@ -774,7 +774,7 @@ struct ProfileClassRef {
774 /// A course as a profile shows it — a label, nothing more.774 /// A course as a profile shows it — a label, nothing more.
775 #[derive(Serialize, ToSchema)]775 #[derive(Serialize, ToSchema)]
776 struct ProfileCourseRef {776 struct ProfileCourseRef {
777- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]777+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
778 id: String,778 id: String,
779 #[schema(example = "Matematik")]779 #[schema(example = "Matematik")]
780 title: String,780 title: String,
tests/board_invite.rsmodified+21 -15
@@ -13,7 +13,7 @@
13 mod common;13 mod common;
14 14
15 use axum::http::StatusCode;15 use axum::http::StatusCode;
16-use common::{Res, app_and_db, create_course, enroll, login, login_as, me_id, send};16+use common::{ABSENT_ID, Res, app_and_db, create_course, enroll, login, login_as, me_id, send};
17 use hezarfen_backend::constant::MAX_BOARD_PARTICIPANTS;17 use hezarfen_backend::constant::MAX_BOARD_PARTICIPANTS;
18 use hezarfen_backend::domain::board::BoardId;18 use hezarfen_backend::domain::board::BoardId;
19 use hezarfen_backend::domain::user::UserId;19 use hezarfen_backend::domain::user::UserId;
@@ -281,13 +281,20 @@ async fn a_deleted_user_in_a_source_is_dropped() {
281 enroll(&app, &teacher, &course, &ghost_id).await;281 enroll(&app, &teacher, &course, &ghost_id).await;
282 282
283 // The row goes without the cascade a real DELETE runs, which is exactly the283 // The row goes without the cascade a real DELETE runs, which is exactly the
284- // state a stale enrollment leaves behind.284+ // state a stale enrollment leaves behind. Real FKs refuse that state, so
285- db.query("DELETE type::record('user', $key)")285+ // the delete is forced the one way Postgres allows: FK triggers suspended
286- .bind(("key", ghost_id.clone()))286+ // for the one statement (`hezarfen` owns the cluster, so it may).
287+ let mut tx = db.begin().await.unwrap();
288+ sqlx::query("SET LOCAL session_replication_role = replica")
289+ .execute(&mut *tx)
287 .await290 .await
288- .unwrap()
289- .check()
290 .unwrap();291 .unwrap();
292+ sqlx::query("DELETE FROM app_user WHERE id = $1")
293+ .bind(UserId::from_key(&ghost_id))
294+ .execute(&mut *tx)
295+ .await
296+ .unwrap();
297+ tx.commit().await.unwrap();
291 298
292 let board = a_board(&app, &teacher).await;299 let board = a_board(&app, &teacher).await;
293 let res = invite(300 let res = invite(
@@ -324,14 +331,13 @@ async fn an_over_cap_invite_is_refused_whole_and_changes_nothing() {
324 // The ids need not resolve — the roster is only repaired at boot, and the331 // The ids need not resolve — the roster is only repaired at boot, and the
325 // guard under test counts entries.332 // guard under test counts entries.
326 let full: Vec<_> = (0..MAX_BOARD_PARTICIPANTS)333 let full: Vec<_> = (0..MAX_BOARD_PARTICIPANTS)
327- .map(|n| UserId::from_key(&format!("filler{n}")).record())334+ .map(|_| UserId::generate())
328 .collect();335 .collect();
329- db.query("UPDATE $b SET participants = $who")336+ sqlx::query("UPDATE board SET participants = $1 WHERE id = $2")
330- .bind(("b", BoardId::from_key(&board).record()))337+ .bind(&full)
331- .bind(("who", full))338+ .bind(BoardId::from_key(&board))
339+ .execute(&db)
332 .await340 .await
333- .unwrap()
334- .check()
335 .unwrap();341 .unwrap();
336 let before = roster(&app, &teacher, &board).await;342 let before = roster(&app, &teacher, &board).await;
337 assert_eq!(before.len(), MAX_BOARD_PARTICIPANTS);343 assert_eq!(before.len(), MAX_BOARD_PARTICIPANTS);
@@ -488,15 +494,15 @@ async fn an_unknown_source_is_a_400_and_not_the_boards_404() {
488 494
489 for (source, field) in [495 for (source, field) in [
490 (496 (
491- json!({"kind": "class", "class": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}),497+ json!({"kind": "class", "class": ABSENT_ID}),
492 "class",498 "class",
493 ),499 ),
494 (500 (
495- json!({"kind": "course", "course": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}),501+ json!({"kind": "course", "course": ABSENT_ID}),
496 "course",502 "course",
497 ),503 ),
498 (504 (
499- json!({"kind": "event", "event": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}),505+ json!({"kind": "event", "event": ABSENT_ID}),
500 "event",506 "event",
501 ),507 ),
502 ] {508 ] {
tests/regress_course_delete.rsmodified+20 -17
@@ -133,15 +133,11 @@ async fn a_course_delete_gives_back_the_kind_references_its_marks_held() {
133 assert_eq!(res.status, StatusCode::OK, "{}", res.body);133 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
134 134
135 let counted = |db: hezarfen_backend::database::Database| async move {135 let counted = |db: hezarfen_backend::database::Database| async move {
136- db.query("SELECT VALUE count ?? 0 FROM kind_ref:midterm")136+ sqlx::query_as::<_, (i64,)>("SELECT count FROM kind_ref WHERE name = 'midterm'")
137+ .fetch_optional(&db)
137 .await138 .await
138 .expect("kind_ref read")139 .expect("kind_ref read")
139- .check()140+ .map(|(count,)| count)
140- .expect("kind_ref read")
141- .take::<Vec<i64>>(0)
142- .expect("kind_ref count")
143- .first()
144- .copied()
145 .unwrap_or(0)141 .unwrap_or(0)
146 };142 };
147 assert_eq!(counted(db.clone()).await, 1, "the mark must be counted");143 assert_eq!(counted(db.clone()).await, 1, "the mark must be counted");
@@ -177,9 +173,11 @@ async fn a_course_delete_gives_back_the_kind_references_its_marks_held() {
177 /// unreachable (every route to an attempt goes through its exam) with the173 /// unreachable (every route to an attempt goes through its exam) with the
178 /// student's lifetime sitting counter up for good.174 /// student's lifetime sitting counter up for good.
179 ///175 ///
180-/// The in-memory engine is enough, as it is next door: this asserts a *lock*,176+/// Postgres hands out the same pairing the lease used to: the sitting's
181-/// not the store's conflict detection, and a mutex behaves the same on either177+/// transaction holds the exam row's write lock across the sleeping trigger, so
182-/// engine.178+/// the delete cannot even reach its attempt sweep until the sitting has
179+/// committed. Mutation-proven: dropping the lease from the cascade turns it
180+/// red.
183 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]181 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
184 async fn an_attempt_started_inside_a_course_delete_never_outlives_it() {182 async fn an_attempt_started_inside_a_course_delete_never_outlives_it() {
185 let (app, db) = app_and_db().await;183 let (app, db) = app_and_db().await;
@@ -188,15 +186,20 @@ async fn an_attempt_started_inside_a_course_delete_never_outlives_it() {
188 let student_id = me_id(&app, &student).await;186 let student_id = me_id(&app, &student).await;
189 187
190 // Hold the sitting's own write open for a full second, gates already188 // Hold the sitting's own write open for a full second, gates already
191- // passed, so the unenroll and the delete both land inside it.189+ // passed, so the unenroll and the delete both land inside it. An AFTER
192- db.query(190+ // INSERT trigger sleeping inside the create's own transaction is the
193- "DEFINE EVENT hold_the_start ON TABLE exam_attempt WHEN $event = 'CREATE' \191+ // Postgres shape of the old window event.
194- THEN { SLEEP 1s; };",192+ let mut conn = db.acquire().await.expect("acquire for the trigger");
193+ sqlx::raw_sql(
194+ "CREATE FUNCTION heztest_hold_start() RETURNS trigger AS $$
195+ BEGIN PERFORM pg_sleep(1.0); RETURN NULL; END;
196+ $$ LANGUAGE plpgsql;
197+ CREATE TRIGGER heztest_hold_start AFTER INSERT ON exam_attempt
198+ FOR EACH ROW EXECUTE FUNCTION heztest_hold_start();",
195 )199 )
200+ .execute(&mut *conn)
196 .await201 .await
197- .expect("define the window event")202+ .expect("define the window trigger");
198- .check()
199- .expect("check the window event");
200 203
201 let course = common::create_course(&app, &teacher, "Kimya").await;204 let course = common::create_course(&app, &teacher, "Kimya").await;
202 enroll(&app, &teacher, &course, &student_id).await;205 enroll(&app, &teacher, &course, &student_id).await;
tests/regress_meals.rsmodified+56 -36
@@ -14,6 +14,7 @@ use common::{app_and_db, id_of, login, login_as, me_id, send, set_role};
14 use hezarfen_backend::db::meal_attendance;14 use hezarfen_backend::db::meal_attendance;
15 use hezarfen_backend::db::menu;15 use hezarfen_backend::db::menu;
16 use hezarfen_backend::domain::meal_attendance::MealAttendanceStatus;16 use hezarfen_backend::domain::meal_attendance::MealAttendanceStatus;
17+use hezarfen_backend::domain::meal_booking::MealBookingId;
17 use hezarfen_backend::domain::menu::{MenuDate, MenuId, MenuSlot};18 use hezarfen_backend::domain::menu::{MenuDate, MenuId, MenuSlot};
18 use hezarfen_backend::domain::settings::MealSlotDef;19 use hezarfen_backend::domain::settings::MealSlotDef;
19 use hezarfen_backend::domain::user::UserId;20 use hezarfen_backend::domain::user::UserId;
@@ -541,13 +542,20 @@ async fn a_dish_write_is_refused_once_its_menu_is_gone() {
541 let dish = add_dish(&app, &mgr, &menu, 1_000).await;542 let dish = add_dish(&app, &mgr, &menu, 1_000).await;
542 543
543 // The menu row alone is removed, leaving the dish exactly as a delete544 // The menu row alone is removed, leaving the dish exactly as a delete
544- // interrupted between the row and its cascade would have.545+ // interrupted between the row and its cascade would have. Real FKs refuse
545- db.query("DELETE $id")546+ // that state, so the delete is forced the one way Postgres allows: FK
546- .bind(("id", MenuId::from_key(&menu).record()))547+ // triggers suspended for the one statement.
548+ let mut tx = db.begin().await.unwrap();
549+ sqlx::query("SET LOCAL session_replication_role = replica")
550+ .execute(&mut *tx)
547 .await551 .await
548- .unwrap()
549- .check()
550 .unwrap();552 .unwrap();
553+ sqlx::query("DELETE FROM menu WHERE id = $1")
554+ .bind(MenuId::from_key(&menu))
555+ .execute(&mut *tx)
556+ .await
557+ .unwrap();
558+ tx.commit().await.unwrap();
551 559
552 let res = send(560 let res = send(
553 &app,561 &app,
@@ -688,14 +696,14 @@ async fn a_slot_whose_name_would_break_the_menu_url_cannot_be_published() {
688 assert_eq!(res.status, StatusCode::OK, "{}", res.body);696 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
689 697
690 // ...and the stale row is that list as a database written before the rule.698 // ...and the stale row is that list as a database written before the rule.
691- db.query(699+ sqlx::query("UPDATE settings SET meal_slots = $1 WHERE id = 'school'")
692- "UPDATE settings:school SET meal_slots = \700+ .bind(sqlx::types::Json(json!([
693- [{ name: 'a/b', serving_minute: NONE }, { name: 'lunch', serving_minute: NONE }]",701+ { "name": "a/b", "serving_minute": null },
694- )702+ { "name": "lunch", "serving_minute": null }
695- .await703+ ])))
696- .unwrap()704+ .execute(&db)
697- .check()705+ .await
698- .unwrap();706+ .unwrap();
699 707
700 let res = send(708 let res = send(
701 &app,709 &app,
@@ -1012,11 +1020,12 @@ async fn two_first_profile_writes_land_without_a_500() {
1012 /// the store had given away. The stored state was right throughout; only the1020 /// the store had given away. The stored state was right throughout; only the
1013 /// answer lied.1021 /// answer lied.
1014 ///1022 ///
1015-/// The cancel is injected the way `regress_roles` does it: a `DEFINE EVENT`1023+/// The cancel is injected where the old `DEFINE EVENT` fired it: inside the
1016-/// fires inside the very write the replay makes — here the charge it replays,1024+/// very write the replay makes — here the charge it replays, which is why the
1017-/// which is why the ledger is stripped first (a charge already there is a1025+/// ledger is stripped first (a charge already there is a no-op). An AFTER
1018-/// no-op). Fenced on `attempt = 1`, so the re-booked seat's own charge does not1026+/// INSERT trigger on the ledger cancels the seat inside the charge's own
1019-/// trip it a second time.1027+/// transaction, fenced on the attempt-1 charge id, so the re-booked seat's own
1028+/// charge does not trip it a second time.
1020 #[tokio::test]1029 #[tokio::test]
1021 async fn a_replayed_booking_answers_off_the_row_the_store_holds() {1030 async fn a_replayed_booking_answers_off_the_row_the_store_holds() {
1022 let (app, db) = app_and_db().await;1031 let (app, db) = app_and_db().await;
@@ -1036,18 +1045,29 @@ async fn a_replayed_booking_answers_off_the_row_the_store_holds() {
1036 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);1045 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1037 let booking = id_of(&res.body);1046 let booking = id_of(&res.body);
1038 1047
1039- db.query(format!(1048+ let mut conn = db.acquire().await.expect("acquire for the trigger");
1040- "DELETE meal_ledger;1049+ sqlx::query("DELETE FROM meal_ledger")
1041- DEFINE EVENT cancel_inside ON TABLE meal_ledger WHEN $event = 'CREATE' THEN {{1050+ .execute(&db)
1042- UPDATE type::record('meal_booking', '{booking}') \1051+ .await
1043- SET status = 'cancelled', cancelled_at = 1 WHERE attempt = 1;1052+ .unwrap();
1044- }};"1053+ // The trigger derives the seat off the charge id itself (`{booking}_c{attempt}`),
1045- ))1054+ // so the text stays static: every attempt-1 charge cancels its own booking.
1055+ sqlx::raw_sql(
1056+ "CREATE FUNCTION heztest_cancel_inside() RETURNS trigger AS $$
1057+ BEGIN
1058+ IF right(NEW.id, 3) = '_c1' THEN
1059+ UPDATE meal_booking SET status = 'cancelled', cancelled_at = 1
1060+ WHERE menu || '_' || student::text || '_c1' = NEW.id;
1061+ END IF;
1062+ RETURN NULL;
1063+ END;
1064+ $$ LANGUAGE plpgsql;
1065+ CREATE TRIGGER heztest_cancel_inside AFTER INSERT ON meal_ledger
1066+ FOR EACH ROW EXECUTE FUNCTION heztest_cancel_inside();",
1067+ )
1068+ .execute(&mut *conn)
1046 .await1069 .await
1047- .unwrap()1070+ .expect("define the cancel trigger");
1048- .check()
1049- .unwrap();
1050-
1051 let res = send(1071 let res = send(
1052 &app,1072 &app,
1053 "POST",1073 "POST",
@@ -1357,13 +1377,13 @@ async fn an_over_ceiling_seat_from_an_older_build_is_still_cancellable() {
1357 let booking = id_of(&res.body);1377 let booking = id_of(&res.body);
1358 1378
1359 // Aged past the ceiling, the way an older binary would have left it.1379 // Aged past the ceiling, the way an older binary would have left it.
1360- db.query(format!(1380+ let booking_id = MealBookingId::from_key(&booking);
1361- "UPDATE type::record('meal_booking', '{booking}') SET attempt = 25"1381+ sqlx::query("UPDATE meal_booking SET attempt = 25 WHERE menu = $1 AND student = $2")
1362- ))1382+ .bind(booking_id.menu())
1363- .await1383+ .bind(booking_id.student())
1364- .unwrap()1384+ .execute(&db)
1365- .check()1385+ .await
1366- .unwrap();1386+ .unwrap();
1367 1387
1368 let res = send(1388 let res = send(
1369 &app,1389 &app,
tests/regress_profile.rsmodified+26 -29
@@ -14,7 +14,7 @@ use axum::Router;
14 use axum::http::StatusCode;14 use axum::http::StatusCode;
15 use common::{15 use common::{
16 app_and_db, create_course, create_exam_with, create_homework, create_subject, enroll, id_of,16 app_and_db, create_course, create_exam_with, create_homework, create_subject, enroll, id_of,
17- items, login, login_as, me_id, send, set_role,17+ items, login, login_as, me_id, send, set_role, ABSENT_ID,
18 };18 };
19 use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN};19 use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN};
20 use hezarfen_backend::database::Database;20 use hezarfen_backend::database::Database;
@@ -347,33 +347,30 @@ async fn a_profile_read_heals_a_missed_badge_then_writes_nothing() {
347 let ada = login(&app, "ada").await;347 let ada = login(&app, "ada").await;
348 let ada_id = me_id(&app, &ada).await;348 let ada_id = me_id(&app, &ada).await;
349 349
350- // Fires inside any write to the award table, so a write this read should350+ // The award table watched through its rows: the read must not add, remove
351- // not make cannot hide behind an unchanged-looking response.351+ // or alter one. (The old engine counted writes with a `DEFINE EVENT`;
352- db.query(352+ // Postgres has no triggers to hang that on, and the write the guard
353- "DEFINE EVENT award_write ON badge_award WHEN true THEN {353+ // bites on — an insert, or a re-stamp of `earned_at` — always changes
354- UPSERT type::record('award_write_probe', 'n') SET n = (n ?? 0) + 1;354+ // what the rows hold.)
355- };",355+ let awards = || async {
356- )356+ let rows: Vec<(uuid::Uuid, String, Option<i64>)> =
357- .await357+ sqlx::query_as(
358- .unwrap()358+ "SELECT app_user, badge, earned_at FROM badge_award ORDER BY app_user, badge",
359- .check()359+ )
360- .unwrap();360+ .fetch_all(&db)
361- let writes = || async {
362- db.query("SELECT VALUE n FROM award_write_probe:n")
363 .await361 .await
364- .unwrap()362+ .unwrap();
365- .take::<Vec<i64>>(0)363+ rows
366- .unwrap()
367- .first()
368- .copied()
369- .unwrap_or(0)
370 };364 };
371-365+ assert!(awards().await.is_empty(), "nothing has been awarded yet");
372- db.query("UPDATE type::record('user', $id) SET homework_submitted_total = 10")366+
373- .bind(("id", ada_id.clone()))367+ // A counter is moved behind the API's back — exactly what a lost
368+ // `badge::sync` leaves behind, since every counter writer logs and
369+ // swallows that error.
370+ sqlx::query("UPDATE app_user SET homework_submitted_total = 10 WHERE id = $1")
371+ .bind(hezarfen_backend::domain::user::UserId::from_key(&ada_id))
372+ .execute(&db)
374 .await373 .await
375- .unwrap()
376- .check()
377 .unwrap();374 .unwrap();
378 375
379 let healed = profile(&app, &ada, &ada_id).await;376 let healed = profile(&app, &ada, &ada_id).await;
@@ -391,15 +388,15 @@ async fn a_profile_read_heals_a_missed_badge_then_writes_nothing() {
391 healed.body388 healed.body
392 );389 );
393 assert_eq!(healed.body["stats"]["homework_submitted_total"], 10);390 assert_eq!(healed.body["stats"]["homework_submitted_total"], 10);
394- let after_heal = writes().await;391+ let after_heal = awards().await;
395- assert!(after_heal > 0, "the heal wrote the awards");392+ assert!(!after_heal.is_empty(), "the heal wrote the awards");
396 393
397 // Steady state: everything earned is already held, so this read must not394 // Steady state: everything earned is already held, so this read must not
398 // touch the award table at all.395 // touch the award table at all.
399 let again = profile(&app, &ada, &ada_id).await;396 let again = profile(&app, &ada, &ada_id).await;
400 assert_eq!(again.status, StatusCode::OK, "{}", again.body);397 assert_eq!(again.status, StatusCode::OK, "{}", again.body);
401 assert_eq!(again.body["badges"], healed.body["badges"], "same shelf");398 assert_eq!(again.body["badges"], healed.body["badges"], "same shelf");
402- assert_eq!(writes().await, after_heal, "a profile read wrote something");399+ assert_eq!(awards().await, after_heal, "a profile read wrote something");
403 }400 }
404 401
405 /// A fresh account reads a true `0` on every counter — never `null`, never an402 /// A fresh account reads a true `0` on every counter — never `null`, never an
@@ -1570,6 +1567,6 @@ async fn an_unknown_user_profile_is_a_404() {
1570 let (app, db) = app_and_db().await;1567 let (app, db) = app_and_db().await;
1571 let teacher = login_as(&app, &db, "teach", "teacher").await;1568 let teacher = login_as(&app, &db, "teach", "teacher").await;
1572 1569
1573- let gone = profile(&app, &teacher, "01J8XZ0K3Q8G7X2M4N5P6R7S8T").await;1570+ let gone = profile(&app, &teacher, ABSENT_ID).await;
1574 assert_eq!(gone.status, StatusCode::NOT_FOUND, "{}", gone.body);1571 assert_eq!(gone.status, StatusCode::NOT_FOUND, "{}", gone.body);
1575 }1572 }
tests/regress_review.rsmodified+2 -2
@@ -21,7 +21,7 @@ mod common;
21 use axum::http::StatusCode;21 use axum::http::StatusCode;
22 use common::{22 use common::{
23 app_and_db, create_course, create_exam_with, create_subject, enroll, id_of, login, login_as,23 app_and_db, create_course, create_exam_with, create_subject, enroll, id_of, login, login_as,
24- me_id, send,24+ me_id, send, ABSENT_ID,
25 };25 };
26 use serde_json::json;26 use serde_json::json;
27 27
@@ -677,7 +677,7 @@ async fn the_review_gate_does_not_leak_allow_review_to_outsiders() {
677 677
678 // The oracle: to a caller with no mark the two exams must be one answer —678 // The oracle: to a caller with no mark the two exams must be one answer —
679 // and the same answer an exam that does not exist gives.679 // and the same answer an exam that does not exist gives.
680- let nowhere = review_of(&outsider, "01J8XZ0K3Q8G7X2M4N5P6R7S8T").await;680+ let nowhere = review_of(&outsider, ABSENT_ID).await;
681 assert_eq!(nowhere, StatusCode::NOT_FOUND);681 assert_eq!(nowhere, StatusCode::NOT_FOUND);
682 for (who, cookie) in [("unenrolled student", &outsider), ("parent", &parent)] {682 for (who, cookie) in [("unenrolled student", &outsider), ("parent", &parent)] {
683 let on_open = review_of(cookie, &open).await;683 let on_open = review_of(cookie, &open).await;
tests/regress_role_sweep.rsmodified+126 -73
@@ -13,13 +13,13 @@
13 //!13 //!
14 //! Each defect is pinned twice: the ordering the claim enforces (the demotion14 //! Each defect is pinned twice: the ordering the claim enforces (the demotion
15 //! already committed — the sequential half), and the interleaving itself, held15 //! already committed — the sequential half), and the interleaving itself, held
16-//! open by a `DEFINE EVENT` on the `user` table so the demotion's transaction is16+//! open by an AFTER DELETE trigger sleeping inside the sweep, so the demotion's
17-//! still running when the grant is written.17+//! transaction is still running when the grant is written.
18 18
19 mod common;19 mod common;
20 20
21 use axum::http::StatusCode;21 use axum::http::StatusCode;
22-use common::{app_and_db, login_as, me_id, send};22+use common::{app_and_db, login_as, me_id, send, set_role};
23 use hezarfen_backend::database::Database;23 use hezarfen_backend::database::Database;
24 use hezarfen_backend::db::enrollment;24 use hezarfen_backend::db::enrollment;
25 use hezarfen_backend::domain::class_group::{ClassGroupId, ClassName};25 use hezarfen_backend::domain::class_group::{ClassGroupId, ClassName};
@@ -31,22 +31,52 @@ use hezarfen_backend::domain::user::UserId;
31 use hezarfen_backend::service::registration;31 use hezarfen_backend::service::registration;
32 use hezarfen_backend::service::{class_group, class_member};32 use hezarfen_backend::service::{class_group, class_member};
33 use serde_json::json;33 use serde_json::json;
34-34+use sqlx::Row as _;
35-/// How many rows `sql` selects ids for.35+
36-async fn rows(sql: &str, db: &Database) -> usize {36+/// How many rows `table` holds.
37- let mut result = db.query(sql).await.unwrap().check().unwrap();37+async fn rows(table: &str, db: &Database) -> usize {
38- result38+ sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
39- .take::<Vec<surrealdb::types::RecordId>>(0)39+ "SELECT count(*) FROM {table}"
40- .unwrap()40+ )))
41- .len()41+ .fetch_one(db)
42+ .await
43+ .unwrap() as usize
42 }44 }
43 45
44 /// Every row's counter added up, re-read out of the store — never off a return46 /// Every row's counter added up, re-read out of the store — never off a return
45 /// value, and summed because the race tests leave a second parent standing (the47 /// value, and summed because the race tests leave a second parent standing (the
46 /// bait) whose seat has to come back too.48 /// bait) whose seat has to come back too.
47-async fn counter(sql: &str, db: &Database) -> i64 {49+async fn counter(column: &str, table: &str, db: &Database) -> i64 {
48- let mut result = db.query(sql).await.unwrap().check().unwrap();50+ sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
49- result.take::<Vec<i64>>(0).unwrap().into_iter().sum()51+ "SELECT COALESCE(sum({column}), 0)::bigint FROM {table}"
52+ )))
53+ .fetch_one(db)
54+ .await
55+ .unwrap()
56+}
57+
58+/// A real `app_user` row for the fixture actor a domain call must name:
59+/// every actor column is a foreign key now, so actors are rows, not fabricated
60+/// ids. The username is unique, so every call for the same name shares one row,
61+/// whichever call minted it. These actors never log in, so the hash is a stub.
62+async fn fixture_actor(db: &Database, username: &str) -> UserId {
63+ sqlx::query(
64+ "INSERT INTO app_user (id, username, password_hash, role) \
65+ VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING",
66+ )
67+ .bind(UserId::generate().uuid())
68+ .bind(username)
69+ .execute(db)
70+ .await
71+ .unwrap();
72+ let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1")
73+ .bind(username)
74+ .fetch_one(db)
75+ .await
76+ .unwrap()
77+ .try_get(0)
78+ .unwrap();
79+ UserId::from_key(&id.to_string())
50 }80 }
51 81
52 /// Demote through the real path — the sweeps ride the role write.82 /// Demote through the real path — the sweeps ride the role write.
@@ -61,31 +91,34 @@ async fn demote(user: &UserId, to: Role, db: &Database) {
61 }91 }
62 92
63 /// Hold the demotion's transaction open *past the point its sweep has looked*:93 /// Hold the demotion's transaction open *past the point its sweep has looked*:
64-/// a `DEFINE EVENT` on the child table fires inside the sweep's own `DELETE`,94+/// an AFTER DELETE trigger on the child table sleeps inside the sweep's own
65-/// so a grant written during the sleep lands after the snapshot that sweep is95+/// `DELETE`, so a grant written during the sleep lands after the snapshot that
66-/// working from and before the transaction commits. That is the write-skew96+/// sweep is working from and before the transaction commits. That is the
67-/// itself, opened by the schema rather than by a lucky interleaving.97+/// write-skew itself, opened by the schema rather than by a lucky interleaving.
68 ///98 ///
69 /// It bites only where the sweep has something to delete, so every caller99 /// It bites only where the sweep has something to delete, so every caller
70 /// leaves one row of that kind behind first — the bait. Holding the *role*100 /// leaves one row of that kind behind first — the bait. Holding the *role*
71 /// write instead proves nothing: the sweeps run after it, so they see the new101 /// write instead proves nothing: the sweeps run after it, so they see the new
72 /// row and free it even on unfixed code.102 /// row and free it even on unfixed code.
73 async fn hold_the_sweep(table: &str, db: &Database) {103 async fn hold_the_sweep(table: &str, db: &Database) {
74- db.query(format!(104+ let mut conn = db.acquire().await.expect("acquire for the trigger");
75- "DEFINE EVENT hold_the_sweep ON TABLE {table} WHEN $event = 'DELETE' \105+ sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
76- THEN {{ SLEEP 2s }};"106+ "CREATE FUNCTION heztest_hold_the_sweep() RETURNS trigger AS $$
77- ))107+ BEGIN PERFORM pg_sleep(2.0); RETURN NULL; END;
108+ $$ LANGUAGE plpgsql;
109+ CREATE TRIGGER heztest_hold_the_sweep AFTER DELETE ON {table}
110+ FOR EACH ROW EXECUTE FUNCTION heztest_hold_the_sweep();"
111+ )))
112+ .execute(&mut *conn)
78 .await113 .await
79- .unwrap()114+ .expect("define the window trigger");
80- .check()
81- .unwrap();
82 }115 }
83 116
84-/// One held window at a time. Each race test below keeps a database117+/// One held window at a time. Each race test below holds a database
85-/// transaction open for seconds while `cap`'s counter lock is process-wide, so118+/// transaction open for seconds against the shared Postgres server, so run in
86-/// run in parallel they push each other clean out of their windows: measured,119+/// parallel they push each other clean out of their windows: measured, all
87-/// all three then pass on code with the claim removed, while serialized all120+/// three then pass on code with the claim removed, while serialized all three
88-/// three fail it. Same trap as the process-wide `EXAM_LOCK` note in121+/// fail it. Same trap as the process-wide `EXAM_LOCK` note in
89 /// `regress_course_delete`, and the guard is handed back into a binding that122 /// `regress_course_delete`, and the guard is handed back into a binding that
90 /// lives for the whole test the way `init_test_server`'s does.123 /// lives for the whole test the way `init_test_server`'s does.
91 static ONE_WINDOW_AT_A_TIME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());124 static ONE_WINDOW_AT_A_TIME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
@@ -95,7 +128,7 @@ static ONE_WINDOW_AT_A_TIME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_
95 ///128 ///
96 /// The wait is a fixed delay against a two-second window, so a loaded machine129 /// The wait is a fixed delay against a two-second window, so a loaded machine
97 /// still lands in it — and the caller proves it did rather than trusting it:130 /// still lands in it — and the caller proves it did rather than trusting it:
98-/// [`still_running`] is asserted the moment the raced write returns. A window131+/// [`still_queued`] is asserted while the demotion runs. A window
99 /// missed the other way (the demotion committing first) would make every one of132 /// missed the other way (the demotion committing first) would make every one of
100 /// these tests pass on unfixed code, which is the failure mode a race test has133 /// these tests pass on unfixed code, which is the failure mode a race test has
101 /// to be loudest about.134 /// to be loudest about.
@@ -113,13 +146,16 @@ async fn demote_in_the_window(
113 handle146 handle
114 }147 }
115 148
116-/// The raced write returned while the demotion's transaction was still open —149+/// The raced write is *queued*, not answered: the claim locks the user row the
117-/// which, since every statement in it but the held one is sub-millisecond, is150+/// demotion is holding, so a raced write that answered inside the window —
118-/// the window.151+/// which is what unfixed code, sharing no key with the demotion, did — fails
119-fn still_running(demoting: &tokio::task::JoinHandle<()>) {152+/// here instead of in the stored-state assertions.
153+async fn still_queued<T>(raced: &tokio::task::JoinHandle<T>) {
154+ // race-window staging — do not convert to poll
155+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
120 assert!(156 assert!(
121- !demoting.is_finished(),157+ !raced.is_finished(),
122- "the demotion committed before the raced write: this run proved nothing"158+ "the raced write answered inside the demotion's window: nothing queued"
123 );159 );
124 }160 }
125 161
@@ -165,14 +201,15 @@ async fn a_seat_is_refused_once_the_holder_is_a_parent() {
165 let event = a_registration_event(&app, &teacher, 1).await;201 let event = a_registration_event(&app, &teacher, 1).await;
166 demote(&student, Role::Parent, &db).await;202 demote(&student, Role::Parent, &db).await;
167 203
168- let refused = registration::register(&db, &event, &student, &UserId::from_key("staff")).await;204+ let refused = registration::register(&db, &event, &student, &fixture_actor(&db, "staff").await)
205+ .await;
169 assert!(206 assert!(
170 refused.is_err(),207 refused.is_err(),
171 "a parent may not be given a seat: {refused:?}"208 "a parent may not be given a seat: {refused:?}"
172 );209 );
173- assert_eq!(rows("SELECT VALUE id FROM registration", &db).await, 0);210+ assert_eq!(rows("registration", &db).await, 0);
174 assert_eq!(211 assert_eq!(
175- counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await,212+ counter("registration_count", "event", &db).await,
176 0,213 0,
177 "…and the event must not count one, or the last place is denied forever"214 "…and the event must not count one, or the last place is denied forever"
178 );215 );
@@ -190,29 +227,36 @@ async fn a_seat_never_survives_the_demotion_it_raced() {
190 let event = a_registration_event(&app, &teacher, 1).await;227 let event = a_registration_event(&app, &teacher, 1).await;
191 // The bait: a seat the sweep will delete, which is what holds it open.228 // The bait: a seat the sweep will delete, which is what holds it open.
192 let earlier = a_registration_event(&app, &teacher, 1).await;229 let earlier = a_registration_event(&app, &teacher, 1).await;
193- registration::register(&db, &earlier, &student, &UserId::from_key("staff"))230+ registration::register(&db, &earlier, &student, &fixture_actor(&db, "staff").await)
194 .await231 .await
195 .unwrap();232 .unwrap();
196 hold_the_sweep("registration", &db).await;233 hold_the_sweep("registration", &db).await;
197 234
198- // The seat is written inside the held window: past the sweep's snapshot,235+ // The grant is written while the demotion holds its window: the claim
199- // before the commit.236+ // queues on the demoted user's row, past the sweep's snapshot.
200 let demoting = demote_in_the_window(&student, Role::Parent, &db).await;237 let demoting = demote_in_the_window(&student, Role::Parent, &db).await;
201- let seat = registration::register(&db, &event, &student, &UserId::from_key("staff")).await;238+ let seat = {
202- still_running(&demoting);239+ let (db, event) = (db.clone(), event);
240+ let staff = fixture_actor(&db, "staff").await;
241+ tokio::spawn(async move {
242+ registration::register(&db, &event, &student, &staff).await
243+ })
244+ };
245+ still_queued(&seat).await;
203 demoting.await.unwrap();246 demoting.await.unwrap();
247+ let seat = seat.await.expect("raced registration task");
204 248
205 assert!(249 assert!(
206 !matches!(seat, Err(hezarfen_backend::error::AppError::Db(_))),250 !matches!(seat, Err(hezarfen_backend::error::AppError::Db(_))),
207 "a raced registration must be answered, not 500: {seat:?}"251 "a raced registration must be answered, not 500: {seat:?}"
208 );252 );
209 assert_eq!(253 assert_eq!(
210- rows("SELECT VALUE id FROM registration", &db).await,254+ rows("registration", &db).await,
211 0,255 0,
212 "the seat a parent cannot free must not exist ({seat:?})"256 "the seat a parent cannot free must not exist ({seat:?})"
213 );257 );
214 assert_eq!(258 assert_eq!(
215- counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await,259+ counter("registration_count", "event", &db).await,
216 0,260 0,
217 "…and its place must be back on the list"261 "…and its place must be back on the list"
218 );262 );
@@ -226,17 +270,13 @@ async fn a_stranded_parent_seat_is_freeable_by_a_teacher() {
226 let (app, db) = app_and_db().await;270 let (app, db) = app_and_db().await;
227 let (teacher, student) = a_school(&app, &db).await;271 let (teacher, student) = a_school(&app, &db).await;
228 let event = a_registration_event(&app, &teacher, 1).await;272 let event = a_registration_event(&app, &teacher, 1).await;
229- registration::register(&db, &event, &student, &UserId::from_key("staff"))273+ registration::register(&db, &event, &student, &fixture_actor(&db, "staff").await)
230 .await274 .await
231 .unwrap();275 .unwrap();
232 // The state the old race left: the seat stands, the account is a parent,276 // The state the old race left: the seat stands, the account is a parent,
233- // and the sweep that should have taken it never saw it.277+ // and the sweep that should have taken it never saw it. `set_role` is the
234- db.query("UPDATE $usr SET role = 'parent'")278+ // harness's bare role write — no cascade, which is exactly the staleness.
235- .bind(("usr", student.record()))279+ set_role(&db, "ogrenci", "parent").await;
236- .await
237- .unwrap()
238- .check()
239- .unwrap();
240 280
241 let freed = send(281 let freed = send(
242 &app,282 &app,
@@ -253,7 +293,7 @@ async fn a_stranded_parent_seat_is_freeable_by_a_teacher() {
253 freed.body293 freed.body
254 );294 );
255 assert_eq!(295 assert_eq!(
256- counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await,296+ counter("registration_count", "event", &db).await,
257 0,297 0,
258 "the place comes back with the row"298 "the place comes back with the row"
259 );299 );
@@ -272,14 +312,15 @@ async fn an_enrollment_is_refused_once_the_student_is_demoted() {
272 let course = a_course(&app, &teacher).await;312 let course = a_course(&app, &teacher).await;
273 demote(&student, Role::Teacher, &db).await;313 demote(&student, Role::Teacher, &db).await;
274 314
275- let refused = enrollment::enroll(&db, &course, &student, &UserId::from_key("staff")).await;315+ let staff = fixture_actor(&db, "staff").await;
316+ let refused = enrollment::enroll(&db, &course, &student, &staff).await;
276 assert!(317 assert!(
277 refused.is_err(),318 refused.is_err(),
278 "only students hold enrollments: {refused:?}"319 "only students hold enrollments: {refused:?}"
279 );320 );
280- assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 0);321+ assert_eq!(rows("enrollment", &db).await, 0);
281 assert_eq!(322 assert_eq!(
282- counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await,323+ counter("enrollment_count", "course", &db).await,
283 0,324 0,
284 "…and a counted seat would also freeze the course's delete guard"325 "…and a counted seat would also freeze the course's delete guard"
285 );326 );
@@ -293,23 +334,28 @@ async fn an_enrollment_never_survives_the_demotion_it_raced() {
293 let course = a_course(&app, &teacher).await;334 let course = a_course(&app, &teacher).await;
294 // The bait: a row the sweep will delete, which is what holds it open.335 // The bait: a row the sweep will delete, which is what holds it open.
295 let earlier = CourseId::from_key(&common::create_course(&app, &teacher, "fizik").await);336 let earlier = CourseId::from_key(&common::create_course(&app, &teacher, "fizik").await);
296- enrollment::enroll(&db, &earlier, &student, &UserId::from_key("staff"))337+ let staff = fixture_actor(&db, "staff").await;
338+ enrollment::enroll(&db, &earlier, &student, &staff)
297 .await339 .await
298 .unwrap();340 .unwrap();
299 hold_the_sweep("enrollment", &db).await;341 hold_the_sweep("enrollment", &db).await;
300 342
301 let demoting = demote_in_the_window(&student, Role::Teacher, &db).await;343 let demoting = demote_in_the_window(&student, Role::Teacher, &db).await;
302- let enrolled = enrollment::enroll(&db, &course, &student, &UserId::from_key("staff")).await;344+ let enrolled = {
303- still_running(&demoting);345+ let (db, course) = (db.clone(), course);
346+ tokio::spawn(async move { enrollment::enroll(&db, &course, &student, &staff).await })
347+ };
348+ still_queued(&enrolled).await;
304 demoting.await.unwrap();349 demoting.await.unwrap();
350+ let enrolled = enrolled.await.expect("raced enrollment task");
305 351
306 assert_eq!(352 assert_eq!(
307- rows("SELECT VALUE id FROM enrollment", &db).await,353+ rows("enrollment", &db).await,
308 0,354 0,
309 "a teacher may not be left on a course roster ({enrolled:?})"355 "a teacher may not be left on a course roster ({enrolled:?})"
310 );356 );
311 assert_eq!(357 assert_eq!(
312- counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await,358+ counter("enrollment_count", "course", &db).await,
313 0359 0
314 );360 );
315 }361 }
@@ -321,9 +367,10 @@ async fn a_class(db: &Database) -> ClassGroupId {
321 }367 }
322 368
323 async fn a_class_named(name: &str, db: &Database) -> ClassGroupId {369 async fn a_class_named(name: &str, db: &Database) -> ClassGroupId {
370+ let manager = fixture_actor(db, "manager").await;
324 class_group::create(371 class_group::create(
325 db,372 db,
326- &UserId::from_key("manager"),373+ &manager,
327 ClassName::try_new(name).unwrap(),374 ClassName::try_new(name).unwrap(),
328 None,375 None,
329 None,376 None,
@@ -342,14 +389,15 @@ async fn a_membership_is_refused_once_the_student_is_demoted() {
342 let class = a_class(&db).await;389 let class = a_class(&db).await;
343 demote(&student, Role::Parent, &db).await;390 demote(&student, Role::Parent, &db).await;
344 391
345- let refused = class_member::add(&db, &class, &student, &UserId::from_key("manager")).await;392+ let manager = fixture_actor(&db, "manager").await;
393+ let refused = class_member::add(&db, &class, &student, &manager).await;
346 assert!(394 assert!(
347 refused.is_err(),395 refused.is_err(),
348 "only students belong to a class: {refused:?}"396 "only students belong to a class: {refused:?}"
349 );397 );
350- assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);398+ assert_eq!(rows("class_member", &db).await, 0);
351 assert_eq!(399 assert_eq!(
352- counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await,400+ counter("class_member_count", "class_group", &db).await,
353 0,401 0,
354 "…and a counted member would freeze the class's delete guard"402 "…and a counted member would freeze the class's delete guard"
355 );403 );
@@ -363,23 +411,28 @@ async fn a_membership_never_survives_the_demotion_it_raced() {
363 let class = a_class(&db).await;411 let class = a_class(&db).await;
364 // The bait: a membership the sweep will delete, which holds it open.412 // The bait: a membership the sweep will delete, which holds it open.
365 let earlier = a_class_named("9-B", &db).await;413 let earlier = a_class_named("9-B", &db).await;
366- class_member::add(&db, &earlier, &student, &UserId::from_key("manager"))414+ let manager = fixture_actor(&db, "manager").await;
415+ class_member::add(&db, &earlier, &student, &manager)
367 .await416 .await
368 .unwrap();417 .unwrap();
369 hold_the_sweep("class_member", &db).await;418 hold_the_sweep("class_member", &db).await;
370 419
371 let demoting = demote_in_the_window(&student, Role::Parent, &db).await;420 let demoting = demote_in_the_window(&student, Role::Parent, &db).await;
372- let joined = class_member::add(&db, &class, &student, &UserId::from_key("manager")).await;421+ let joined = {
373- still_running(&demoting);422+ let (db, class) = (db.clone(), class);
423+ tokio::spawn(async move { class_member::add(&db, &class, &student, &manager).await })
424+ };
425+ still_queued(&joined).await;
374 demoting.await.unwrap();426 demoting.await.unwrap();
427+ let joined = joined.await.expect("raced membership task");
375 428
376 assert_eq!(429 assert_eq!(
377- rows("SELECT VALUE id FROM class_member", &db).await,430+ rows("class_member", &db).await,
378 0,431 0,
379 "a parent may not be left on a class roster ({joined:?})"432 "a parent may not be left on a class roster ({joined:?})"
380 );433 );
381 assert_eq!(434 assert_eq!(
382- counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await,435+ counter("class_member_count", "class_group", &db).await,
383 0436 0
384 );437 );
385 }438 }