forge
Explore
Log in

Don't you dare go Hollow

Port remaining regress suites to the Postgres harness

Browse files at this commit

8af2a2bdd27d3e53b6b39a1d00763f875d67a2c1Ahmet Kaan GümüşParent: 43ba495
  • test
    • port remaining regress suites to the Postgres harness
Show full message
🧪 test: port remaining regress suites to the Postgres harness
tests/builder_api.rsmodified+48 -54
@@ -805,16 +805,15 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() {
805805 assert_eq!(total(&notes.body), 0, "old rows survived the drop");
806806 }
807807
808-/// Claim 2, remote mode: `Tenants::create`/`drop` interpolate the slug into
809-/// `DEFINE DATABASE` / `REMOVE DATABASE`. Not injectable — but the statements
810-/// must at least *execute* for every slug `Slug::try_new` accepts. Run the exact
811-/// production statements against a live SurrealDB parser.
808+/// Claim 2, the school lifecycle: `Tenants::create`/`drop` interpolate the slug
809+/// into `CREATE DATABASE` / `DROP DATABASE`. Not injectable — but the statements
810+/// must at least *execute* for every slug `Slug::try_new` accepts. Each slug is
811+/// driven through the real lifecycle over HTTP, which is exactly those
812+/// statements against the live server.
812813 #[tokio::test]
813814 async fn probe_remote_mode_database_statements_execute_for_every_accepted_slug() {
814- let Some(deployment) = common::remote_deployment(&[]).await else {
815- return;
816- };
817- let control = deployment.tenants.control();
815+ let (app, _db, _tenants) = deployment().await;
816+ let builder = builder_login(&app).await;
818817 let mut broken: Vec<String> = Vec::new();
819818
820819 for raw in [
@@ -827,32 +826,38 @@ async fn probe_remote_mode_database_statements_execute_for_every_accepted_slug()
827826 "12345",
828827 "a1",
829828 ] {
830- let Ok(slug) = Slug::try_new(raw) else {
829+ // The demo school this deployment already carries is the one slug the
830+ // create would refuse as taken; the rest are free.
831+ if Slug::try_new(raw).is_err() || raw == DEMO_SLUG {
831832 continue;
832- };
833- // The exact statements `Tenants::create` / `drop` send, via the same
834- // identifier quoting they use.
835- let ident = hezarfen_backend::tenant::quoted_ident(&slug);
836- let define = control
837- .query(format!("DEFINE DATABASE IF NOT EXISTS {ident}"))
838- .await
839- .map_err(|e| e.to_string())
840- .and_then(|r| r.check().map(|_| ()).map_err(|e| e.to_string()));
841- let remove = control
842- .query(format!("REMOVE DATABASE IF EXISTS {ident}"))
843- .await
844- .map_err(|e| e.to_string())
845- .and_then(|r| r.check().map(|_| ()).map_err(|e| e.to_string()));
846- if let Err(err) = define {
847- broken.push(format!("DEFINE DATABASE {raw} -> {err}"));
848833 }
849- if let Err(err) = remove {
850- broken.push(format!("REMOVE DATABASE {raw} -> {err}"));
834+ // The exact statements `Tenants::create` / `drop` send, through the
835+ // routes that send them.
836+ let made = create_school(&app, &builder, raw, "secret1").await;
837+ if made.status != StatusCode::CREATED {
838+ broken.push(format!(
839+ "CREATE DATABASE {raw} -> {} {:?}",
840+ made.status, made.body
841+ ));
842+ }
843+ let dropped = send(
844+ &app,
845+ "DELETE",
846+ &format!("/schools/{raw}"),
847+ Some(&builder),
848+ None,
849+ )
850+ .await;
851+ if dropped.status != StatusCode::NO_CONTENT {
852+ broken.push(format!(
853+ "DROP DATABASE {raw} -> {} {:?}",
854+ dropped.status, dropped.body
855+ ));
851856 }
852857 }
853858 assert!(
854859 broken.is_empty(),
855- "slugs accepted by Slug::try_new whose remote-mode statements do not execute:\n{}",
860+ "slugs accepted by Slug::try_new whose school statements do not execute:\n{}",
856861 broken.join("\n")
857862 );
858863 }
@@ -1220,14 +1225,12 @@ async fn probe_concurrent_creates_of_one_slug_leave_one_school() {
12201225 assert_eq!(opens, 1, "{opens} of the two admin passwords open p6race");
12211226 }
12221227
1223-/// Claim 1/2 driven against a **real remote deployment** — the mode every test
1224-/// above skips, and the only one where `DEFINE DATABASE` / `REMOVE DATABASE`
1225-/// actually run. `ata-koleji` is the slug the OpenAPI schema advertises.
1228+/// Claim 1/2 driven against a full deployment of its own, where the school
1229+/// lifecycle's `CREATE DATABASE` / `DROP DATABASE` actually run.
1230+/// `ata-koleji` is the slug the OpenAPI schema advertises.
12261231 #[tokio::test]
12271232 async fn probe_remote_deployment_creates_and_deletes_a_hyphenated_school() {
1228- let Some(deployment) = common::remote_deployment(&[]).await else {
1229- return;
1230- };
1233+ let deployment = common::deployment_with(&[]).await;
12311234 let app = deployment.app;
12321235 builder::ensure(
12331236 deployment.tenants.control(),
@@ -2005,18 +2008,11 @@ async fn probe_a_refused_batch_leaves_the_row_byte_identical() {
20052008 let builder = builder_login(&app).await;
20062009
20072010 async fn raw_row(tenants: &Tenants) -> Vec<String> {
2008- tenants
2009- .control()
2010- .query(format!(
2011- "SELECT VALUE modules FROM type::record('school', '{DEMO_SLUG}')"
2012- ))
2011+ sqlx::query_scalar("SELECT modules FROM school WHERE slug = $1")
2012+ .bind(DEMO_SLUG)
2013+ .fetch_one(tenants.control())
20132014 .await
20142015 .expect("raw read")
2015- .check()
2016- .expect("raw check")
2017- .take::<Vec<Vec<String>>>(0)
2018- .expect("modules column")
2019- .remove(0)
20202016 }
20212017
20222018 let before = raw_row(&tenants).await;
@@ -2048,13 +2044,11 @@ async fn probe_a_refused_batch_leaves_the_row_byte_identical() {
20482044 /// a thread-local subscriber cannot measure this reliably: `tracing` caches a
20492045 /// callsite's interest process-wide the first time any thread reaches it, and
20502046 /// with tests running in parallel that thread is usually a sibling with no
2051-/// subscriber — the SurrealDB callsites are then disabled for the whole
2052-/// process before this test ever asks, and the count is 0 (measured: 0 in 7 of
2053-/// 8 runs against noisy siblings; a global subscriber counted on 6 of 6).
2054-/// Global is safe here because this subscriber only counts: it stores nothing,
2055-/// prints nothing, and its `enabled` refuses every callsite that is not a
2056-/// SurrealDB one on *this* test's thread, so a sibling test neither pays for it
2057-/// nor lands in the figure.
2047+/// subscriber — the sqlx callsites are then disabled for the whole process
2048+/// before this test ever asks, and the count is 0. Global is safe here because
2049+/// this subscriber only counts: it stores nothing, prints nothing, and its
2050+/// `enabled` refuses every callsite that is not a sqlx one on *this* test's
2051+/// thread, so a sibling test neither pays for it nor lands in the figure.
20582052 #[tokio::test]
20592053 async fn probe_registry_reads_per_request() {
20602054 use std::sync::Arc;
@@ -2072,7 +2066,7 @@ async fn probe_registry_reads_per_request() {
20722066 tracing::subscriber::Interest::sometimes()
20732067 }
20742068 fn enabled(&self, meta: &tracing::Metadata<'_>) -> bool {
2075- meta.target().starts_with("surrealdb") && std::thread::current().id() == self.thread
2069+ meta.target().starts_with("sqlx") && std::thread::current().id() == self.thread
20762070 }
20772071 fn new_span(&self, _: &span::Attributes<'_>) -> span::Id {
20782072 self.count.fetch_add(1, Ordering::Relaxed);
@@ -2100,10 +2094,10 @@ async fn probe_registry_reads_per_request() {
21002094 let res = send(&app, "GET", "/notes", Some(&cookie), None).await;
21012095 assert_eq!(res.status, StatusCode::OK, "{:?}", res.body);
21022096 let seen = count.load(Ordering::Relaxed);
2103- println!("PROBE surrealdb spans/events for GET /notes = {seen}");
2097+ println!("PROBE sqlx spans/events for GET /notes = {seen}");
21042098 assert!(
21052099 seen > 0,
2106- "UNMEASURED: the surrealdb SDK emitted no tracing spans, so per-request \
2100+ "UNMEASURED: sqlx emitted no tracing spans, so per-request \
21072101 registry reads cannot be counted this way"
21082102 );
21092103 }
tests/regress_blueprints.rsmodified+181 -212
@@ -13,45 +13,47 @@
1313 mod common;
1414
1515 use axum::http::StatusCode;
16-use common::{Res, app_and_db, create_course, login_as, me_id, send};
16+use common::{GHOST_ID, Res, app_and_db, create_course, login_as, me_id, send};
1717 use hezarfen_backend::database::Database;
1818 use hezarfen_backend::domain::class_blueprint::ClassBlueprint;
1919 use hezarfen_backend::domain::course::CourseId;
20+use hezarfen_backend::domain::timestamp::Timestamp;
2021 use hezarfen_backend::domain::user::UserId;
2122 use hezarfen_backend::error::AppError;
2223 use hezarfen_backend::service::class_blueprint;
2324 use serde_json::{Value, json};
2425
25-/// One counter, re-read out of the store.
26-async fn counter(sql: &str, db: &Database) -> i64 {
27- let mut result = db.query(sql).await.unwrap().check().unwrap();
28- result
29- .take::<Vec<i64>>(0)
30- .unwrap()
31- .first()
32- .copied()
33- .unwrap_or(0)
26+/// One counter, re-read out of the store. `sql` is a whole scalar query.
27+async fn counter(sql: &'static str, db: &Database) -> i64 {
28+ sqlx::query_scalar(sql).fetch_one(db).await.unwrap()
3429 }
3530
36-/// How many rows `sql` selects ids for.
37-async fn rows(sql: &str, db: &Database) -> i64 {
38- let mut result = db.query(sql).await.unwrap().check().unwrap();
39- result
40- .take::<Vec<surrealdb::types::RecordId>>(0)
41- .unwrap()
42- .len() as i64
31+/// How many rows `sql` counts.
32+async fn rows(sql: &'static str, db: &Database) -> i64 {
33+ counter(sql, db).await
34+}
35+
36+/// One row's counter column, re-read out of the store.
37+async fn count_on(column: &'static str, table: &'static str, id: &str, db: &Database) -> i64 {
38+ sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
39+ "SELECT {column} FROM {table} WHERE id = $1"
40+ )))
41+ .bind(uuid::Uuid::parse_str(id).expect("a uuid row id"))
42+ .fetch_one(db)
43+ .await
44+ .unwrap()
4345 }
4446
4547 /// Is that course on that class, in the store?
4648 async fn attached(class: &str, course: &str, db: &Database) -> bool {
47- rows(
48- &format!(
49- "SELECT VALUE id FROM class_course WHERE class = class_group:{class} \
50- AND course = course:{course}"
51- ),
52- db,
49+ sqlx::query_scalar::<_, i64>(
50+ "SELECT count(*) FROM class_course WHERE class = $1 AND course = $2",
5351 )
52+ .bind(uuid::Uuid::parse_str(class).expect("a uuid class id"))
53+ .bind(uuid::Uuid::parse_str(course).expect("a uuid course id"))
54+ .fetch_one(db)
5455 .await
56+ .unwrap()
5557 == 1
5658 }
5759
@@ -59,33 +61,26 @@ async fn attached(class: &str, course: &str, db: &Database) -> bool {
5961 /// no such key at all — which is the whole provenance rule: absent means a
6062 /// human attached it.
6163 async fn source_of(class: &str, course: &str, db: &Database) -> Option<String> {
62- let mut result = db
63- .query(format!(
64- "SELECT VALUE (IF source != NONE THEN record::id(source) ELSE '' END) \
65- FROM class_course WHERE class = class_group:{class} AND course = course:{course}"
66- ))
67- .await
68- .unwrap()
69- .check()
70- .unwrap();
71- result
72- .take::<Vec<String>>(0)
73- .unwrap()
74- .into_iter()
75- .next()
76- .filter(|key| !key.is_empty())
64+ sqlx::query_scalar::<_, Option<String>>(
65+ "SELECT source FROM class_course WHERE class = $1 AND course = $2",
66+ )
67+ .bind(uuid::Uuid::parse_str(class).expect("a uuid class id"))
68+ .bind(uuid::Uuid::parse_str(course).expect("a uuid course id"))
69+ .fetch_one(db)
70+ .await
71+ .unwrap()
7772 }
7873
7974 /// Does that grade's template still name that course, in the store?
8075 async fn templated(grade: &str, course: &str, db: &Database) -> bool {
81- rows(
82- &format!(
83- "SELECT VALUE id FROM class_blueprint \
84- WHERE grade = '{grade}' AND course:{course} IN courses"
85- ),
86- db,
76+ sqlx::query_scalar::<_, i64>(
77+ "SELECT count(*) FROM class_blueprint WHERE grade = $1 AND $2 = ANY(courses)",
8778 )
79+ .bind(grade)
80+ .bind(CourseId::from_key(course))
81+ .fetch_one(db)
8882 .await
83+ .unwrap()
8984 == 1
9085 }
9186
@@ -250,7 +245,7 @@ async fn a_blueprint_is_created_read_updated_and_deleted() {
250245 )
251246 .await;
252247 assert_eq!(dropped.status, StatusCode::NO_CONTENT);
253- assert_eq!(rows("SELECT VALUE id FROM class_blueprint", &db).await, 0);
248+ assert_eq!(rows("SELECT count(*) FROM class_blueprint", &db).await, 0);
254249 let gone = send(&app, "GET", "/classes/blueprints/9", Some(&manager), None).await;
255250 assert_eq!(gone.status, StatusCode::NOT_FOUND);
256251
@@ -313,23 +308,20 @@ async fn a_fresh_class_takes_its_grades_blueprint() {
313308 "the blueprint must own what it attached"
314309 );
315310 assert_eq!(
316- rows(
317- &format!(
318- "SELECT VALUE id FROM enrollment WHERE course = course:{course} \
319- AND user = user:{student}"
320- ),
321- &db
311+ sqlx::query_scalar::<_, i64>(
312+ "SELECT count(*) FROM enrollment WHERE course = $1 AND app_user = $2",
322313 )
323- .await,
314+ .bind(CourseId::from_key(course))
315+ .bind(UserId::from_key(&student))
316+ .fetch_one(&db)
317+ .await
318+ .unwrap(),
324319 1,
325320 "stocking a class enrolls its roster, in real rows"
326321 );
327322 }
328323 assert_eq!(
329- counter(
330- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"),
331- &db
332- )
324+ count_on("class_course_count", "class_group", &class, &db)
333325 .await,
334326 2
335327 );
@@ -345,7 +337,7 @@ async fn a_fresh_class_takes_its_grades_blueprint() {
345337 .await;
346338 assert_eq!(twice.status, StatusCode::OK);
347339 assert!(skips(&twice).is_empty());
348- assert_eq!(rows("SELECT VALUE id FROM class_course", &db).await, 2);
340+ assert_eq!(rows("SELECT count(*) FROM class_course", &db).await, 2);
349341
350342 // A class whose grade no blueprint covers is a 404, not an empty success.
351343 let other = create_class(&app, &manager, "10-A", "10").await;
@@ -411,10 +403,7 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() {
411403 );
412404 }
413405 assert_eq!(
414- counter(
415- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"),
416- &db
417- )
406+ count_on("class_course_count", "class_group", &class, &db)
418407 .await,
419408 2
420409 );
@@ -425,14 +414,14 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() {
425414 let student = student_in(&app, &db, &class, &manager, "ali").await;
426415 for course in [&algebra, &physics] {
427416 assert_eq!(
428- rows(
429- &format!(
430- "SELECT VALUE id FROM enrollment WHERE course = course:{course} \
431- AND user = user:{student}"
432- ),
433- &db
417+ sqlx::query_scalar::<_, i64>(
418+ "SELECT count(*) FROM enrollment WHERE course = $1 AND app_user = $2",
434419 )
435- .await,
420+ .bind(CourseId::from_key(course))
421+ .bind(UserId::from_key(&student))
422+ .fetch_one(&db)
423+ .await
424+ .unwrap(),
436425 1,
437426 "a stocked class enrolls its roster like any other"
438427 );
@@ -454,11 +443,13 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() {
454443 assert!(skips(&res).is_empty(), "{:?}", res.body);
455444 let bare = res.body["class"]["id"].as_str().unwrap();
456445 assert_eq!(
457- rows(
458- &format!("SELECT VALUE id FROM class_course WHERE class = class_group:{bare}"),
459- &db
446+ sqlx::query_scalar::<_, i64>(
447+ "SELECT count(*) FROM class_course WHERE class = $1",
460448 )
461- .await,
449+ .bind(uuid::Uuid::parse_str(bare).expect("a uuid class id"))
450+ .fetch_one(&db)
451+ .await
452+ .unwrap(),
462453 0,
463454 "nothing may be attached to a section no template reached"
464455 );
@@ -496,10 +487,10 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() {
496487 // meets when a course goes after it read the list. Nothing carries it yet
497488 // (no section exists at grade 9), so this is the pair that cannot fit when
498489 // the first one is created.
499- db.query(format!("DELETE course:{physics}"))
490+ sqlx::query("DELETE FROM course WHERE id = $1")
491+ .bind(CourseId::from_key(&physics))
492+ .execute(&db)
500493 .await
501- .unwrap()
502- .check()
503494 .unwrap();
504495 assert!(
505496 templated("9", &physics, &db).await,
@@ -531,11 +522,11 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() {
531522 .expect("class id")
532523 .to_string();
533524 assert_eq!(
534- rows(
535- &format!("SELECT VALUE id FROM class_group WHERE id = class_group:{class}"),
536- &db
537- )
538- .await,
525+ sqlx::query_scalar::<_, i64>("SELECT count(*) FROM class_group WHERE id = $1")
526+ .bind(uuid::Uuid::parse_str(&class).expect("a uuid class id"))
527+ .fetch_one(&db)
528+ .await
529+ .unwrap(),
539530 1,
540531 "the class is really there — the skip is a report, not a rollback"
541532 );
@@ -544,11 +535,11 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() {
544535 "…and the course that did fit is on it"
545536 );
546537 assert_eq!(
547- rows(
548- &format!("SELECT VALUE id FROM class_course WHERE class = class_group:{class}"),
549- &db
550- )
551- .await,
538+ sqlx::query_scalar::<_, i64>("SELECT count(*) FROM class_course WHERE class = $1")
539+ .bind(uuid::Uuid::parse_str(&class).expect("a uuid class id"))
540+ .fetch_one(&db)
541+ .await
542+ .unwrap(),
552543 1
553544 );
554545 // The dangling id is pruned by the run that found it, here as anywhere.
@@ -580,7 +571,7 @@ async fn an_edit_retro_pumps_every_class_at_the_grade() {
580571 )
581572 .await;
582573 assert_eq!(made.status, StatusCode::CREATED);
583- assert_eq!(rows("SELECT VALUE id FROM class_course", &db).await, 0);
574+ assert_eq!(rows("SELECT count(*) FROM class_course", &db).await, 0);
584575
585576 // …and the edit is what has to reach the two classes standing there.
586577 let patched = send(
@@ -605,37 +596,28 @@ async fn an_edit_retro_pumps_every_class_at_the_grade() {
605596 // grade.
606597 for class in [&a, &b] {
607598 assert_eq!(
608- counter(
609- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"),
610- &db
611- )
599+ count_on("class_course_count", "class_group", class, &db)
612600 .await,
613601 1
614602 );
615603 }
616604 assert_eq!(
617- counter(
618- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{ten}"),
619- &db
620- )
605+ count_on("class_course_count", "class_group", &ten, &db)
621606 .await,
622607 0
623608 );
624609 assert_eq!(
625- counter(
626- &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{algebra}"),
627- &db
628- )
610+ count_on("enrollment_count", "course", &algebra, &db)
629611 .await,
630612 1,
631613 "one student at the grade, one seat"
632614 );
633615 assert_eq!(
634- rows(
635- &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali}"),
636- &db
637- )
638- .await,
616+ sqlx::query_scalar::<_, i64>("SELECT count(*) FROM enrollment WHERE app_user = $1")
617+ .bind(UserId::from_key(&ali))
618+ .fetch_one(&db)
619+ .await
620+ .unwrap(),
639621 1
640622 );
641623 }
@@ -687,23 +669,17 @@ async fn a_class_that_does_not_fit_is_reported_not_aborted() {
687669 // Nothing moved on the skipped class: not its attachment counter, and not
688670 // one of the seats the refused attach touched on its way to the refusal.
689671 assert_eq!(
690- counter(
691- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{full}"),
692- &db
693- )
672+ count_on("class_course_count", "class_group", &full, &db)
694673 .await,
695674 0
696675 );
697676 assert_eq!(
698- counter(
699- &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{tight}"),
700- &db
701- )
677+ count_on("enrollment_count", "course", &tight, &db)
702678 .await,
703679 0,
704680 "the empty class took no seat, and the refused one gave every seat back"
705681 );
706- assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 0);
682+ assert_eq!(rows("SELECT count(*) FROM enrollment", &db).await, 0);
707683 }
708684
709685 /// One cause, one code, whichever door it came through: the `409` a manager's
@@ -848,36 +824,27 @@ async fn a_removal_spares_a_hand_attached_course() {
848824 "…and nothing else — a hand attach survives"
849825 );
850826 assert_eq!(
851- counter(
852- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{pumped}"),
853- &db
854- )
827+ count_on("class_course_count", "class_group", &pumped, &db)
855828 .await,
856829 0,
857830 "the detach gives the class its count back"
858831 );
859832 assert_eq!(
860- counter(
861- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{byhand}"),
862- &db
863- )
833+ count_on("class_course_count", "class_group", &byhand, &db)
864834 .await,
865835 1
866836 );
867837 assert_eq!(
868- rows(
869- &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali}"),
870- &db
871- )
872- .await,
838+ sqlx::query_scalar::<_, i64>("SELECT count(*) FROM enrollment WHERE app_user = $1")
839+ .bind(UserId::from_key(&ali))
840+ .fetch_one(&db)
841+ .await
842+ .unwrap(),
873843 0,
874844 "the enrollments the blueprint pumped go with it"
875845 );
876846 assert_eq!(
877- counter(
878- &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{algebra}"),
879- &db
880- )
847+ count_on("enrollment_count", "course", &algebra, &db)
881848 .await,
882849 1,
883850 "the hand-attached class keeps its student's seat"
@@ -907,12 +874,11 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() {
907874 )
908875 .await;
909876 assert_eq!(attached_by_hand.status, StatusCode::CREATED);
910- // Age the row to before the column existed. `UNSET`, not `= NONE`: an
911- // absent key is what the store holds today, and it is what the rule reads.
912- db.query("UPDATE class_course UNSET source")
877+ // Age the row to before the column existed: a NULL `source` is what the
878+ // store holds for a hand attach, and it is what the rule reads.
879+ sqlx::query("UPDATE class_course SET source = NULL")
880+ .execute(&db)
913881 .await
914- .unwrap()
915- .check()
916882 .unwrap();
917883 assert_eq!(source_of(&class, &algebra, &db).await, None);
918884
@@ -961,10 +927,7 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() {
961927 "a pre-migration row is hand-attached and unreachable by any blueprint sweep"
962928 );
963929 assert_eq!(
964- counter(
965- &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{algebra}"),
966- &db
967- )
930+ count_on("enrollment_count", "course", &algebra, &db)
968931 .await,
969932 1
970933 );
@@ -979,15 +942,14 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() {
979942 /// `class_course` row tagged with a record nothing can reach, since the grade
980943 /// label *is* the id and no sweep will ever run for it again.
981944 ///
982-/// Racing two requests would be a coin flip the in-memory engine lies about, so
983-/// the delete is injected by the database itself: a `DEFINE EVENT` on
984-/// `class_course` fires *inside* the pump's own transaction, the instant the
985-/// link row lands — which is exactly "after the guard passed, before the
986-/// commit", every single time. This is a below-the-lock probe by construction
987-/// (the store deletes the row, not `service::class_blueprint::delete`), so it does not
988-/// test `BLUEPRINT_LOCK`; it pins the end state that lock prevents in-process,
989-/// and the recovery contract that covers the one residue it cannot — a process
990-/// crash between the delete and its sweep.
945+/// Under Postgres the window itself is shut — `class_course.source` is a real
946+/// foreign key, so a blueprint delete inside the attach's transaction takes the
947+/// attach down with it, and a crash between the delete and its sweep is one
948+/// transaction. What the store can no longer refuse is the residue an old
949+/// volume can still carry, so the stranded row is forged the one way Postgres
950+/// allows (FK triggers suspended for the one transaction) and what is pinned is
951+/// the recovery contract for it: a human detaches it one course at a time, and
952+/// the counters come back exact.
991953 #[tokio::test]
992954 async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() {
993955 let (app, db) = app_and_db().await;
@@ -1019,41 +981,46 @@ async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() {
1019981 assert_eq!(moved.status, StatusCode::OK, "{:?}", moved.body);
1020982 assert!(!attached(&class, &algebra, &db).await);
1021983
1022- // Delete the blueprint from inside the very write that attaches on its
1023- // behalf.
1024- db.query(
1025- "DEFINE EVENT lose_blueprint ON TABLE class_course WHEN $event = 'CREATE' \
1026- THEN { DELETE type::record('class_blueprint', '9'); };",
984+ // The stranded state: the link row committed, the blueprint it names did
985+ // not survive. Real FKs refuse that state, so it is written with FK
986+ // triggers suspended — the manager id is real, the `source` FK is the one
987+ // the strand consists of.
988+ let manager_id = UserId::from_key(&me_id(&app, &manager).await);
989+ let mut tx = db.begin().await.unwrap();
990+ sqlx::query("SET LOCAL session_replication_role = replica")
991+ .execute(&mut *tx)
992+ .await
993+ .unwrap();
994+ sqlx::query("DELETE FROM class_blueprint WHERE grade = '9'")
995+ .execute(&mut *tx)
996+ .await
997+ .unwrap();
998+ sqlx::query(
999+ "INSERT INTO class_course (class, course, attached_by, attached_at, source) \
1000+ VALUES ($1, $2, $3, $4, '9')",
10271001 )
1002+ .bind(uuid::Uuid::parse_str(&class).expect("a uuid class id"))
1003+ .bind(CourseId::from_key(&algebra))
1004+ .bind(manager_id)
1005+ .bind(Timestamp::now().as_millis())
1006+ .execute(&mut *tx)
10281007 .await
1029- .unwrap()
1030- .check()
10311008 .unwrap();
1032-
1033- let pumped = send(
1034- &app,
1035- "POST",
1036- &format!("/classes/{class}/blueprint"),
1037- Some(&manager),
1038- None,
1039- )
1040- .await;
1041- assert_eq!(pumped.status, StatusCode::OK, "{:?}", pumped.body);
1042- assert!(
1043- skips(&pumped).is_empty(),
1044- "the pump was told it succeeded — which is what makes the row below \
1045- invisible to the caller: {:?}",
1046- pumped.body
1047- );
1009+ sqlx::query("UPDATE class_group SET class_course_count = 1 WHERE id = $1")
1010+ .bind(uuid::Uuid::parse_str(&class).expect("a uuid class id"))
1011+ .execute(&mut *tx)
1012+ .await
1013+ .unwrap();
1014+ tx.commit().await.unwrap();
10481015
10491016 assert_eq!(
1050- rows("SELECT VALUE id FROM class_blueprint", &db).await,
1017+ rows("SELECT count(*) FROM class_blueprint", &db).await,
10511018 0,
10521019 "the injected delete really landed"
10531020 );
10541021 assert!(
10551022 attached(&class, &algebra, &db).await,
1056- "the link committed after its blueprint was gone: this is the stranded \
1023+ "the link stands after its blueprint was gone: this is the stranded \
10571024 row, tagged with a record no sweep can ever reach"
10581025 );
10591026 assert_eq!(source_of(&class, &algebra, &db).await, Some("9".into()));
@@ -1076,10 +1043,7 @@ async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() {
10761043 );
10771044 assert!(!attached(&class, &algebra, &db).await);
10781045 assert_eq!(
1079- counter(
1080- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"),
1081- &db
1082- )
1046+ count_on("class_course_count", "class_group", &class, &db)
10831047 .await,
10841048 0,
10851049 "a stranded row still releases its counter when it is detached"
@@ -1460,14 +1424,11 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() {
14601424
14611425 // The state a sweep that died half-way leaves: the list is stored without
14621426 // history, its attachment is not.
1463- db.query(
1464- "UPDATE type::record('class_blueprint', '9') SET courses = [type::record('course', $c)]",
1465- )
1466- .bind(("c", algebra.clone()))
1467- .await
1468- .unwrap()
1469- .check()
1470- .unwrap();
1427+ sqlx::query("UPDATE class_blueprint SET courses = $1 WHERE grade = '9'")
1428+ .bind(vec![CourseId::from_key(&algebra)])
1429+ .execute(&db)
1430+ .await
1431+ .unwrap();
14711432
14721433 let courses = held(&app, &manager, "9").await;
14731434 assert_eq!(
@@ -1490,19 +1451,19 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() {
14901451 "re-sending the stored list must finish the removal it stored"
14911452 );
14921453 assert_eq!(
1493- rows(
1494- &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali} AND course = course:{history}"),
1495- &db
1454+ sqlx::query_scalar::<_, i64>(
1455+ "SELECT count(*) FROM enrollment WHERE app_user = $1 AND course = $2",
14961456 )
1497- .await,
1457+ .bind(UserId::from_key(&ali))
1458+ .bind(CourseId::from_key(&history))
1459+ .fetch_one(&db)
1460+ .await
1461+ .unwrap(),
14981462 0,
14991463 "…enrollments and all"
15001464 );
15011465 assert_eq!(
1502- counter(
1503- &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{history}"),
1504- &db
1505- )
1466+ count_on("enrollment_count", "course", &history, &db)
15061467 .await,
15071468 0,
15081469 "…with the seat given back"
@@ -1512,11 +1473,14 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() {
15121473 "and the course the template still holds is untouched"
15131474 );
15141475 assert_eq!(
1515- rows(
1516- &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali} AND course = course:{algebra}"),
1517- &db
1476+ sqlx::query_scalar::<_, i64>(
1477+ "SELECT count(*) FROM enrollment WHERE app_user = $1 AND course = $2",
15181478 )
1519- .await,
1479+ .bind(UserId::from_key(&ali))
1480+ .bind(CourseId::from_key(&algebra))
1481+ .fetch_one(&db)
1482+ .await
1483+ .unwrap(),
15201484 1
15211485 );
15221486 }
@@ -1538,14 +1502,17 @@ async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() {
15381502 let history = create_course(&app, &manager, "history").await;
15391503 let class = create_class(&app, &manager, "9-A", "9").await;
15401504
1541- db.query(format!(
1542- "DEFINE EVENT kill_on_create ON TABLE class_blueprint WHEN $event = 'CREATE' \
1543- THEN {{ DELETE type::record('course', '{algebra}'); }};"
1544- ))
1505+ let mut conn = db.acquire().await.expect("acquire for the trigger");
1506+ sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
1507+ "CREATE FUNCTION heztest_kill_on_create() RETURNS trigger AS $$
1508+ BEGIN DELETE FROM course WHERE id = '{algebra}'; RETURN NULL; END;
1509+ $$ LANGUAGE plpgsql;
1510+ CREATE TRIGGER heztest_kill_on_create AFTER INSERT ON class_blueprint
1511+ FOR EACH ROW EXECUTE FUNCTION heztest_kill_on_create();"
1512+ )))
1513+ .execute(&mut *conn)
15451514 .await
1546- .unwrap()
1547- .check()
1548- .unwrap();
1515+ .expect("define the kill-on-create trigger");
15491516 let made = send(
15501517 &app,
15511518 "POST",
@@ -1571,14 +1538,16 @@ async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() {
15711538 );
15721539
15731540 // The same window on the edit route.
1574- db.query(format!(
1575- "DEFINE EVENT kill_on_update ON TABLE class_blueprint WHEN $event = 'UPDATE' \
1576- THEN {{ DELETE type::record('course', '{history}'); }};"
1577- ))
1541+ sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
1542+ "CREATE FUNCTION heztest_kill_on_update() RETURNS trigger AS $$
1543+ BEGIN DELETE FROM course WHERE id = '{history}'; RETURN NULL; END;
1544+ $$ LANGUAGE plpgsql;
1545+ CREATE TRIGGER heztest_kill_on_update AFTER UPDATE ON class_blueprint
1546+ FOR EACH ROW EXECUTE FUNCTION heztest_kill_on_update();"
1547+ )))
1548+ .execute(&mut *conn)
15781549 .await
1579- .unwrap()
1580- .check()
1581- .unwrap();
1550+ .expect("define the kill-on-update trigger");
15821551 let patched = send(
15831552 &app,
15841553 "PATCH",
@@ -1624,7 +1593,7 @@ async fn a_template_write_refuses_a_course_that_is_gone() {
16241593 let manager = login_as(&app, &db, "mgr", "manager").await;
16251594 let by = UserId::from_key(&me_id(&app, &manager).await);
16261595 let algebra = CourseId::from_key(&create_course(&app, &manager, "algebra").await);
1627- let ghost = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");
1596+ let ghost = CourseId::from_key(GHOST_ID);
16281597
16291598 let refused = class_blueprint::create(
16301599 &db,
@@ -1638,7 +1607,7 @@ async fn a_template_write_refuses_a_course_that_is_gone() {
16381607 "a course that is gone is a 400, not a template naming it: {refused:?}"
16391608 );
16401609 assert_eq!(
1641- rows("SELECT VALUE id FROM class_blueprint", &db).await,
1610+ rows("SELECT count(*) FROM class_blueprint", &db).await,
16421611 0,
16431612 "…and nothing may be stored"
16441613 );
tests/regress_classes.rsmodified+200 -156
@@ -6,7 +6,7 @@
66 mod common;
77
88 use axum::http::StatusCode;
9-use common::{Res, app_and_db, create_course, login_as, me_id, send, total};
9+use common::{ABSENT_ID, GHOST_ID, Res, app_and_db, create_course, login_as, me_id, send, total};
1010 use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
1111 use hezarfen_backend::database::Database;
1212 use hezarfen_backend::domain::class_group::ClassName;
@@ -15,25 +15,62 @@ use hezarfen_backend::domain::user::UserId;
1515 use hezarfen_backend::error::AppError;
1616 use hezarfen_backend::service::{class_course, class_group, class_member};
1717 use serde_json::json;
18+use sqlx::Row as _;
1819
19-/// One counter, re-read out of the store — never off a response body.
20-async fn counter(sql: &str, db: &Database) -> i64 {
21- let mut result = db.query(sql).await.unwrap().check().unwrap();
22- result
23- .take::<Vec<i64>>(0)
24- .unwrap()
25- .first()
26- .copied()
27- .unwrap_or(0)
20+/// One counter, re-read out of the store — never off a response body. `sql`
21+/// is a whole scalar query; each call spells the aggregate it asserts on.
22+async fn counter(sql: &'static str, db: &Database) -> i64 {
23+ sqlx::query_scalar(sql).fetch_one(db).await.unwrap()
24+}
25+
26+/// How many rows `sql` counts.
27+async fn rows(sql: &'static str, db: &Database) -> i64 {
28+ counter(sql, db).await
2829 }
2930
30-/// How many rows `sql` selects ids for.
31-async fn rows(sql: &str, db: &Database) -> i64 {
32- let mut result = db.query(sql).await.unwrap().check().unwrap();
33- result
34- .take::<Vec<surrealdb::types::RecordId>>(0)
31+/// A real `app_user` row for the fixture actor or member a domain call must
32+/// name: the actor and member columns are foreign keys now, so they are rows,
33+/// not fabricated ids. The username is unique, so every call for the same name
34+/// shares one row, whichever call minted it. These rows never log in, so the
35+/// hash is a stub.
36+async fn fixture_user(db: &Database, username: &str) -> UserId {
37+ sqlx::query(
38+ "INSERT INTO app_user (id, username, password_hash, role) \
39+ VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING",
40+ )
41+ .bind(UserId::generate().uuid())
42+ .bind(username)
43+ .execute(db)
44+ .await
45+ .unwrap();
46+ let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1")
47+ .bind(username)
48+ .fetch_one(db)
49+ .await
3550 .unwrap()
36- .len() as i64
51+ .try_get(0)
52+ .unwrap();
53+ UserId::from_key(&id.to_string())
54+}
55+
56+/// Delete a row the way a racing write that lost would have left it: the row
57+/// gone, its referring rows untouched. Real FKs refuse that state, so the
58+/// delete is forced the one way Postgres allows: FK triggers suspended for the
59+/// one transaction.
60+async fn wipe_row(table: &str, id: uuid::Uuid, db: &Database) {
61+ let mut tx = db.begin().await.unwrap();
62+ sqlx::query("SET LOCAL session_replication_role = replica")
63+ .execute(&mut *tx)
64+ .await
65+ .unwrap();
66+ sqlx::query(sqlx::AssertSqlSafe(format!(
67+ "DELETE FROM {table} WHERE id = $1"
68+ )))
69+ .bind(id)
70+ .execute(&mut *tx)
71+ .await
72+ .unwrap();
73+ tx.commit().await.unwrap();
3774 }
3875
3976 /// Delete a course row the way a *concurrent* `DELETE /courses/{id}` racing an
@@ -42,12 +79,12 @@ async fn rows(sql: &str, db: &Database) -> i64 {
4279 /// the state from a test — and the state the pump's in-transaction claim exists
4380 /// to make unreachable in the first place.
4481 async fn wipe_course_row(course: &str, db: &Database) {
45- db.query("DELETE type::record('course', $key)")
46- .bind(("key", course.to_string()))
47- .await
48- .unwrap()
49- .check()
50- .unwrap();
82+ wipe_row(
83+ "course",
84+ uuid::Uuid::parse_str(course).expect("a uuid course id"),
85+ db,
86+ )
87+ .await;
5188 }
5289
5390 /// B1(a). A class with *zero* members makes the pump's pair loop empty, so the
@@ -57,7 +94,7 @@ async fn wipe_course_row(course: &str, db: &Database) {
5794 #[tokio::test]
5895 async fn an_attach_onto_a_deleted_course_writes_no_link() {
5996 let (_app, db) = app_and_db().await;
60- let manager = UserId::from_key("manager");
97+ let manager = fixture_user(&db, "manager").await;
6198 let class = class_group::create(
6299 &db,
63100 &manager,
@@ -70,7 +107,7 @@ async fn an_attach_onto_a_deleted_course_writes_no_link() {
70107 .unwrap();
71108 // A course id nothing ever created: the same row a delete that won the race
72109 // leaves behind.
73- let ghost = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");
110+ let ghost = CourseId::from_key(GHOST_ID);
74111
75112 let refused = class_course::attach(&db, class.get_id(), &ghost, &manager).await;
76113 assert!(
@@ -78,12 +115,12 @@ async fn an_attach_onto_a_deleted_course_writes_no_link() {
78115 "attaching a course that is gone must be refused: {refused:?}"
79116 );
80117 assert_eq!(
81- rows("SELECT VALUE id FROM class_course", &db).await,
118+ rows("SELECT count(*) FROM class_course", &db).await,
82119 0,
83120 "no link row may point at a course that does not exist"
84121 );
85122 assert_eq!(
86- counter("SELECT VALUE class_course_count ?? 0 FROM class_group", &db).await,
123+ counter("SELECT COALESCE(sum(class_course_count), 0)::bigint FROM class_group", &db).await,
87124 0,
88125 "…and the class must not count one either, or it is undeletable forever"
89126 );
@@ -222,7 +259,7 @@ async fn a_member_add_names_a_stale_link_rather_than_calling_it_full() {
222259 refused.body
223260 );
224261 assert_eq!(
225- rows("SELECT VALUE id FROM class_member", &db).await,
262+ rows("SELECT count(*) FROM class_member", &db).await,
226263 0,
227264 "a refused add writes nothing"
228265 );
@@ -294,7 +331,7 @@ async fn a_hand_enroll_takes_the_row_off_the_class() {
294331 "a hand enroll must take the row off the class"
295332 );
296333 assert_eq!(
297- rows("SELECT VALUE id FROM enrollment WHERE source != NONE", &db).await,
334+ rows("SELECT count(*) FROM enrollment WHERE source IS NOT NULL", &db).await,
298335 0,
299336 "…in the stored row, not just the response"
300337 );
@@ -311,12 +348,12 @@ async fn a_hand_enroll_takes_the_row_off_the_class() {
311348 .await;
312349 assert_eq!(removed.status, StatusCode::NO_CONTENT);
313350 assert_eq!(
314- rows("SELECT VALUE id FROM enrollment", &db).await,
351+ rows("SELECT count(*) FROM enrollment", &db).await,
315352 1,
316353 "the class may not unenroll a student an operator enrolled by hand"
317354 );
318355 assert_eq!(
319- counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await,
356+ counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", &db).await,
320357 1,
321358 "…and the seat it never paid for may not be released"
322359 );
@@ -362,7 +399,7 @@ async fn a_role_change_sweeps_memberships_and_enrollments_together() {
362399 Some(json!({ "user_id": student_id })),
363400 )
364401 .await;
365- assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 1);
402+ assert_eq!(rows("SELECT count(*) FROM enrollment", &db).await, 1);
366403
367404 let promoted = send(
368405 &app,
@@ -374,19 +411,19 @@ async fn a_role_change_sweeps_memberships_and_enrollments_together() {
374411 .await;
375412 assert_eq!(promoted.status, StatusCode::OK);
376413
377- assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
414+ assert_eq!(rows("SELECT count(*) FROM class_member", &db).await, 0);
378415 assert_eq!(
379- rows("SELECT VALUE id FROM enrollment", &db).await,
416+ rows("SELECT count(*) FROM enrollment", &db).await,
380417 0,
381418 "a non-student holds no roster row, whoever wrote it"
382419 );
383420 assert_eq!(
384- counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await,
421+ counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", &db).await,
385422 0,
386423 "the seat comes back exactly once"
387424 );
388425 assert_eq!(
389- counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await,
426+ counter("SELECT COALESCE(sum(class_member_count), 0)::bigint FROM class_group", &db).await,
390427 0
391428 );
392429 // Nothing is left tagged with the class, so letting it go strands nothing.
@@ -463,7 +500,7 @@ async fn the_roster_cap_is_claimed_off_the_live_capacity_column() {
463500 // off the (full) counter, and costs no seat.
464501 assert_eq!(enroll(first_id.clone()).await.status, StatusCode::OK);
465502 assert_eq!(
466- counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await,
503+ counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", &db).await,
467504 1
468505 );
469506
@@ -480,7 +517,7 @@ async fn the_roster_cap_is_claimed_off_the_live_capacity_column() {
480517 assert_eq!(raised.status, StatusCode::OK);
481518 assert_eq!(enroll(second_id.clone()).await.status, StatusCode::OK);
482519 assert_eq!(
483- counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await,
520+ counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", &db).await,
484521 2
485522 );
486523
@@ -488,10 +525,9 @@ async fn the_roster_cap_is_claimed_off_the_live_capacity_column() {
488525 // conditional write matches nothing either way, and only that path pays for
489526 // the read that tells them apart.
490527 wipe_course_row(&course, &db).await;
491- db.query("DELETE enrollment")
528+ sqlx::query("DELETE FROM enrollment")
529+ .execute(&db)
492530 .await
493- .unwrap()
494- .check()
495531 .unwrap();
496532 assert_eq!(enroll(first_id).await.status, StatusCode::NOT_FOUND);
497533 }
@@ -504,7 +540,7 @@ async fn the_roster_cap_is_claimed_off_the_live_capacity_column() {
504540 #[tokio::test]
505541 async fn a_roster_is_ordered_by_when_a_student_was_added() {
506542 let (_app, db) = app_and_db().await;
507- let manager = UserId::from_key("manager");
543+ let manager = fixture_user(&db, "manager").await;
508544 let class = class_group::create(
509545 &db,
510546 &manager,
@@ -518,25 +554,27 @@ async fn a_roster_is_ordered_by_when_a_student_was_added() {
518554 .get_id()
519555 .clone();
520556
521- // Keys chosen so `id DESC` (c, b, a) is not the reverse of the insertion
522- // order (a, c, b): only a real stamp can tell the two apart. The waits are
523- // what keep the millisecond stamps distinct — a tie falls back to the id,
524- // which is the very order under test.
525- let added = ["a", "c", "b"];
526- for key in added {
527- class_member::add(&db, &class, &UserId::from_key(key), &manager)
557+ // Members added in an order no id ordering reproduces: only a real stamp
558+ // can tell the two apart. The waits are what keep the stamps distinct —
559+ // a tie falls back to the id, which is the very order under test. The
560+ // minted rows carry uuid ids, so the assertions read back through the
561+ // name -> id map.
562+ let mut names: Vec<(&str, UserId)> = Vec::new();
563+ for key in ["a", "c", "b"] {
564+ let member = fixture_user(&db, key).await;
565+ class_member::add(&db, &class, &member, &manager)
528566 .await
529567 .unwrap();
568+ names.push((key, member));
530569 tokio::time::sleep(std::time::Duration::from_millis(2)).await;
531570 }
571+ let name_of =
572+ |id: &UserId| names.iter().find(|(_, mid)| mid == id).map(|(k, _)| *k).unwrap();
532573
533574 let (roster, _) = class_member::list_for_class(&db, &class, None, 0)
534575 .await
535576 .unwrap();
536- let order: Vec<&str> = roster
537- .iter()
538- .map(|member| member.get_user().key())
539- .collect();
577+ let order: Vec<&str> = roster.iter().map(|member| name_of(member.get_user())).collect();
540578 assert_eq!(
541579 order,
542580 vec!["b", "c", "a"],
@@ -547,19 +585,20 @@ async fn a_roster_is_ordered_by_when_a_student_was_added() {
547585 // all — the state a real volume is in. It is of unknown age, and NONE
548586 // sorting last under DESC is what makes that the oldest, rather than an
549587 // invented number putting it anywhere else.
550- db.query("UPDATE class_member SET added_at = NONE WHERE user = $usr")
551- .bind(("usr", UserId::from_key("c").record()))
552- .await
553- .unwrap()
554- .check()
555- .unwrap();
588+ sqlx::query(
589+ "UPDATE class_member SET added_at = NULL
590+ WHERE app_user = (SELECT id FROM app_user WHERE username = 'c')",
591+ )
592+ .execute(&db)
593+ .await
594+ .unwrap();
556595 let (roster, _) = class_member::list_for_class(&db, &class, None, 0)
557596 .await
558597 .unwrap();
559598 assert_eq!(
560599 roster
561600 .iter()
562- .map(|member| member.get_user().key())
601+ .map(|member| name_of(member.get_user()))
563602 .collect::<Vec<_>>(),
564603 vec!["b", "a", "c"],
565604 "a stamp-less row must sort oldest, not first"
@@ -586,7 +625,7 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() {
586625 .get_id()
587626 .clone();
588627
589- // Courses are ULID-keyed, so their ids rise with creation; attaching them
628+ // Course ids rise with creation (monotonic mint); attaching them
590629 // back-to-front makes id order and attach order disagree.
591630 let mut courses = Vec::new();
592631 for title in ["first", "second", "third"] {
@@ -604,7 +643,7 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() {
604643 let (attached, _) = class_course::list_for_class(&db, &class, None, 0)
605644 .await
606645 .unwrap();
607- let order: Vec<&str> = attached
646+ let order: Vec<String> = attached
608647 .iter()
609648 .map(|link| link.get_course().key())
610649 .collect();
@@ -626,7 +665,7 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() {
626665 #[tokio::test]
627666 async fn a_class_refuses_the_member_past_its_ceiling() {
628667 let (_app, db) = app_and_db().await;
629- let manager = UserId::from_key("manager");
668+ let manager = fixture_user(&db, "manager").await;
630669 let class = class_group::create(
631670 &db,
632671 &manager,
@@ -639,18 +678,19 @@ async fn a_class_refuses_the_member_past_its_ceiling() {
639678 .unwrap()
640679 .get_id()
641680 .clone();
642- db.query("UPDATE $class SET class_member_count = $at")
643- .bind(("class", class.record()))
644- .bind(("at", MAX_CLASS_MEMBERS - 1))
681+ sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2")
682+ .bind(MAX_CLASS_MEMBERS - 1)
683+ .bind(class.clone())
684+ .execute(&db)
645685 .await
646- .unwrap()
647- .check()
648686 .unwrap();
649687
650- class_member::add(&db, &class, &UserId::from_key("last"), &manager)
688+ let last = fixture_user(&db, "last").await;
689+ class_member::add(&db, &class, &last, &manager)
651690 .await
652691 .expect("the place under the ceiling is still free");
653- let refused = class_member::add(&db, &class, &UserId::from_key("over"), &manager).await;
692+ let over = fixture_user(&db, "over").await;
693+ let refused = class_member::add(&db, &class, &over, &manager).await;
654694 assert!(
655695 matches!(refused, Err(AppError::ConflictCoded { code, ref message })
656696 if code == "class_at_roster_ceiling"
@@ -659,22 +699,18 @@ async fn a_class_refuses_the_member_past_its_ceiling() {
659699 must name the ceiling the prose does — the roster, not the course list: {refused:?}"
660700 );
661701 assert_eq!(
662- counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await,
702+ counter("SELECT COALESCE(sum(class_member_count), 0)::bigint FROM class_group", &db).await,
663703 MAX_CLASS_MEMBERS,
664704 "a refused add may not tick the counter past the cap"
665705 );
666- assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 1);
706+ assert_eq!(rows("SELECT count(*) FROM class_member", &db).await, 1);
667707
668708 // And the refusal a *deleted* class earns must stay a 404: both come out of
669709 // the same counter claim matching nothing, and only one of them is a
670710 // ceiling anybody can make room under.
671- db.query("DELETE $class")
672- .bind(("class", class.record()))
673- .await
674- .unwrap()
675- .check()
676- .unwrap();
677- let gone = class_member::add(&db, &class, &UserId::from_key("ghost"), &manager).await;
711+ wipe_row("class_group", class.uuid(), &db).await;
712+ let ghost = fixture_user(&db, "ghost").await;
713+ let gone = class_member::add(&db, &class, &ghost, &manager).await;
678714 assert!(
679715 matches!(gone, Err(AppError::NotFound)),
680716 "a class that is gone is a 404: {gone:?}"
@@ -709,12 +745,11 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() {
709745 .get_id()
710746 .clone();
711747 let algebra = CourseId::from_key(&create_course(&app, &cookie, "algebra").await);
712- db.query("UPDATE $class SET class_member_count = $over")
713- .bind(("class", class.record()))
714- .bind(("over", MAX_CLASS_MEMBERS + 1))
748+ sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2")
749+ .bind(MAX_CLASS_MEMBERS + 1)
750+ .bind(class.clone())
751+ .execute(&db)
715752 .await
716- .unwrap()
717- .check()
718753 .unwrap();
719754
720755 let refused = class_course::attach(&db, &class, &algebra, &manager).await;
@@ -725,24 +760,23 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() {
725760 "the refusal must name the axis that is over, not the one with room: {refused:?}"
726761 );
727762 assert_eq!(
728- rows("SELECT VALUE id FROM class_course", &db).await,
763+ rows("SELECT count(*) FROM class_course", &db).await,
729764 0,
730765 "a refused attach may not leave the link behind"
731766 );
732767 assert_eq!(
733- counter("SELECT VALUE class_course_count ?? 0 FROM class_group", &db).await,
768+ counter("SELECT COALESCE(sum(class_course_count), 0)::bigint FROM class_group", &db).await,
734769 0,
735770 "…nor tick the axis it was refused on"
736771 );
737772
738773 // Back under the ceiling, the very same attach goes through: the refusal is
739774 // the standing count, not the class.
740- db.query("UPDATE $class SET class_member_count = $at")
741- .bind(("class", class.record()))
742- .bind(("at", MAX_CLASS_MEMBERS))
775+ sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2")
776+ .bind(MAX_CLASS_MEMBERS)
777+ .bind(class.clone())
778+ .execute(&db)
743779 .await
744- .unwrap()
745- .check()
746780 .unwrap();
747781 class_course::attach(&db, &class, &algebra, &manager)
748782 .await
@@ -754,7 +788,7 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() {
754788 #[tokio::test]
755789 async fn a_class_over_the_course_ceiling_takes_no_member() {
756790 let (_app, db) = app_and_db().await;
757- let manager = UserId::from_key("manager");
791+ let manager = fixture_user(&db, "manager").await;
758792 let class = class_group::create(
759793 &db,
760794 &manager,
@@ -767,15 +801,15 @@ async fn a_class_over_the_course_ceiling_takes_no_member() {
767801 .unwrap()
768802 .get_id()
769803 .clone();
770- db.query("UPDATE $class SET class_course_count = $over")
771- .bind(("class", class.record()))
772- .bind(("over", MAX_CLASS_COURSES + 1))
804+ sqlx::query("UPDATE class_group SET class_course_count = $1 WHERE id = $2")
805+ .bind(MAX_CLASS_COURSES + 1)
806+ .bind(class.clone())
807+ .execute(&db)
773808 .await
774- .unwrap()
775- .check()
776809 .unwrap();
777810
778- let refused = class_member::add(&db, &class, &UserId::from_key("ali"), &manager).await;
811+ let ali = fixture_user(&db, "ali").await;
812+ let refused = class_member::add(&db, &class, &ali, &manager).await;
779813 assert!(
780814 matches!(refused, Err(AppError::ConflictCoded { code, ref message })
781815 if code == "class_course_list_too_large"
@@ -783,9 +817,9 @@ async fn a_class_over_the_course_ceiling_takes_no_member() {
783817 "the refusal must name the courses, not the roster — in its code as well as \
784818 its prose: {refused:?}"
785819 );
786- assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
820+ assert_eq!(rows("SELECT count(*) FROM class_member", &db).await, 0);
787821 assert_eq!(
788- counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await,
822+ counter("SELECT COALESCE(sum(class_member_count), 0)::bigint FROM class_group", &db).await,
789823 0
790824 );
791825 }
@@ -908,7 +942,7 @@ async fn a_student_or_a_ghost_cannot_be_the_homeroom_teacher() {
908942 let manager = login_as(&app, &db, "manager", "manager").await;
909943 let student = login_as(&app, &db, "ali", "student").await;
910944 let student_id = me_id(&app, &student).await;
911- let ghost = "01J8XZ0K3Q8G7X2M4N5P6R7S8T";
945+ let ghost = GHOST_ID;
912946
913947 for bad in [student_id.as_str(), ghost] {
914948 let refused = send(
@@ -922,7 +956,7 @@ async fn a_student_or_a_ghost_cannot_be_the_homeroom_teacher() {
922956 assert_eq!(refused.status, StatusCode::BAD_REQUEST, "create with {bad}");
923957 }
924958 assert_eq!(
925- rows("SELECT VALUE id FROM class_group", &db).await,
959+ rows("SELECT count(*) FROM class_group", &db).await,
926960 0,
927961 "a refused create may write no class"
928962 );
@@ -1249,7 +1283,7 @@ async fn only_staff_and_a_linked_parent_read_another_users_classes() {
12491283 let ghost = send(
12501284 &app,
12511285 "GET",
1252- "/classes/user/01J8XZ0K3Q8G7X2M4N5P6R7S8T",
1286+ &format!("/classes/user/{ABSENT_ID}"),
12531287 Some(&teacher),
12541288 None,
12551289 )
@@ -1292,12 +1326,12 @@ async fn a_membership_whose_class_is_gone_is_counted_but_skipped() {
12921326 }
12931327 // The guard would refuse this, so it is spelled as the raw row loss it
12941328 // stands in for; the membership row is deliberately left behind.
1295- db.query("DELETE type::record('class_group', $key)")
1296- .bind(("key", classes[0].clone()))
1297- .await
1298- .unwrap()
1299- .check()
1300- .unwrap();
1329+ wipe_row(
1330+ "class_group",
1331+ uuid::Uuid::parse_str(&classes[0]).expect("a uuid class id"),
1332+ &db,
1333+ )
1334+ .await;
13011335
13021336 let res = send(&app, "GET", "/classes/me", Some(&student), None).await;
13031337 assert_eq!(
@@ -1339,28 +1373,38 @@ async fn a_membership_whose_class_is_gone_is_counted_but_skipped() {
13391373 // single time. Nothing in `src/` knows about it — the seam is the schema, and
13401374 // these tests are what stop the three `undo_if_demoted` calls being deleted.
13411375
1342-/// Demote `user` from inside the next write to `table`, the instant it lands.
1376+/// Demote `user` from inside the next write to `table`, the instant it lands:
1377+/// an AFTER trigger fires inside the write's own transaction, between the
1378+/// handler's role check and its post-write re-read.
13431379 async fn demote_during_writes_to(table: &str, event: &str, user: &str, db: &Database) {
1344- db.query(format!(
1345- "DEFINE EVENT demote_mid_write ON TABLE {table} WHEN $event = '{event}' THEN {{ \
1346- UPDATE type::record('user', '{user}') SET role = 'student'; }};"
1347- ))
1380+ let firing = match event {
1381+ "CREATE" => "INSERT",
1382+ "UPDATE" => "UPDATE",
1383+ other => panic!("unknown event kind {other}"),
1384+ };
1385+ let mut conn = db.acquire().await.expect("acquire for the trigger");
1386+ sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
1387+ "CREATE FUNCTION heztest_demote_mid_write() RETURNS trigger AS $$
1388+ BEGIN
1389+ UPDATE app_user SET role = 'student' WHERE id = '{user}';
1390+ RETURN NULL;
1391+ END;
1392+ $$ LANGUAGE plpgsql;
1393+ CREATE TRIGGER heztest_demote_mid_write AFTER {firing} ON {table}
1394+ FOR EACH ROW EXECUTE FUNCTION heztest_demote_mid_write();"
1395+ )))
1396+ .execute(&mut *conn)
13481397 .await
1349- .unwrap()
1350- .check()
1351- .unwrap();
1398+ .expect("define the demote trigger");
13521399 }
13531400
13541401 /// The homeroom teacher's live role, straight out of the store.
13551402 async fn role_of(user: &str, db: &Database) -> String {
1356- let mut result = db
1357- .query("SELECT VALUE role FROM user WHERE id = type::record('user', $k)")
1358- .bind(("k", user.to_string()))
1403+ sqlx::query_scalar("SELECT role FROM app_user WHERE id = $1")
1404+ .bind(UserId::from_key(user))
1405+ .fetch_one(db)
13591406 .await
13601407 .unwrap()
1361- .check()
1362- .unwrap();
1363- result.take::<Vec<String>>(0).unwrap().pop().unwrap()
13641408 }
13651409
13661410 /// `POST /classes` naming a teacher who is demoted while the row is being
@@ -1407,12 +1451,12 @@ async fn a_create_whose_teacher_is_demoted_mid_write_rolls_back_whole() {
14071451 );
14081452 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");
14091453 assert_eq!(
1410- rows("SELECT VALUE id FROM class_group", &db).await,
1454+ rows("SELECT count(*) FROM class_group", &db).await,
14111455 0,
14121456 "the 409 promises nothing was created — so nothing may be there"
14131457 );
14141458 assert_eq!(
1415- counter("SELECT VALUE class_count ?? 0 FROM term", &db).await,
1459+ counter("SELECT COALESCE(sum(class_count), 0)::bigint FROM term", &db).await,
14161460 0,
14171461 "…and least of all a reference stranded on the term"
14181462 );
@@ -1471,12 +1515,12 @@ async fn a_rolled_back_create_at_a_blueprinted_grade_leaves_nothing_behind() {
14711515 res.body
14721516 );
14731517 assert_eq!(
1474- rows("SELECT VALUE id FROM class_group", &db).await,
1518+ rows("SELECT count(*) FROM class_group", &db).await,
14751519 0,
14761520 "the rollback must still have been able to delete the class"
14771521 );
14781522 assert_eq!(
1479- rows("SELECT VALUE id FROM class_course", &db).await,
1523+ rows("SELECT count(*) FROM class_course", &db).await,
14801524 0,
14811525 "…which it only can because nothing was stocked onto it first"
14821526 );
@@ -1516,8 +1560,8 @@ async fn a_patch_whose_teacher_is_demoted_mid_write_undoes_the_column() {
15161560 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");
15171561 assert_eq!(
15181562 counter(
1519- "SELECT VALUE (IF teacher = NONE { 0 } ELSE { 1 }) FROM class_group",
1520- &db
1563+ "SELECT count(*) FROM class_group WHERE teacher IS NOT NULL",
1564+ &db,
15211565 )
15221566 .await,
15231567 0,
@@ -1566,7 +1610,7 @@ async fn a_course_assignment_whose_teacher_is_demoted_mid_write_is_undone() {
15661610 );
15671611 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");
15681612 assert_eq!(
1569- counter("SELECT VALUE array::len(teachers ?? []) FROM course", &db).await,
1613+ counter("SELECT COALESCE(sum(cardinality(teachers)), 0)::bigint FROM course", &db).await,
15701614 0,
15711615 "the assignment must be dropped again, not left granting nothing"
15721616 );
@@ -1589,15 +1633,21 @@ async fn a_rollback_the_guard_refuses_is_a_500_not_a_lying_409() {
15891633 let teacher = login_as(&app, &db, "teacher", "teacher").await;
15901634 let teacher_id = me_id(&app, &teacher).await;
15911635
1592- db.query(format!(
1593- "DEFINE EVENT demote_and_occupy ON TABLE class_group WHEN $event = 'CREATE' THEN {{ \
1594- UPDATE type::record('user', '{teacher_id}') SET role = 'student'; \
1595- UPDATE $after.id SET class_member_count = 1; }};"
1596- ))
1636+ let mut conn = db.acquire().await.expect("acquire for the trigger");
1637+ sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
1638+ "CREATE FUNCTION heztest_demote_and_occupy() RETURNS trigger AS $$
1639+ BEGIN
1640+ UPDATE app_user SET role = 'student' WHERE id = '{teacher_id}';
1641+ UPDATE class_group SET class_member_count = 1 WHERE id = NEW.id;
1642+ RETURN NULL;
1643+ END;
1644+ $$ LANGUAGE plpgsql;
1645+ CREATE TRIGGER heztest_demote_and_occupy AFTER INSERT ON class_group
1646+ FOR EACH ROW EXECUTE FUNCTION heztest_demote_and_occupy();"
1647+ )))
1648+ .execute(&mut *conn)
15971649 .await
1598- .unwrap()
1599- .check()
1600- .unwrap();
1650+ .expect("define the demote-and-occupy trigger");
16011651
16021652 let res = send(
16031653 &app,
@@ -1615,14 +1665,14 @@ async fn a_rollback_the_guard_refuses_is_a_500_not_a_lying_409() {
16151665 res.body
16161666 );
16171667 assert_eq!(
1618- rows("SELECT VALUE id FROM class_group", &db).await,
1668+ rows("SELECT count(*) FROM class_group", &db).await,
16191669 1,
16201670 "the class really is still there — which is why the 409 would have lied"
16211671 );
16221672 assert_eq!(
16231673 counter(
1624- "SELECT VALUE (IF teacher = NONE { 0 } ELSE { 1 }) FROM class_group",
1625- &db
1674+ "SELECT count(*) FROM class_group WHERE teacher IS NOT NULL",
1675+ &db,
16261676 )
16271677 .await,
16281678 0,
@@ -1759,7 +1809,7 @@ async fn a_detach_never_hands_a_row_to_a_class_that_is_gone() {
17591809 let (app, db) = app_and_db().await;
17601810 let staff = login_as(&app, &db, "manager", "manager").await;
17611811 let manager = UserId::from_key(&me_id(&app, &staff).await);
1762- let student = UserId::from_key("student");
1812+ let student = fixture_user(&db, "heir_ogrenci").await;
17631813 let algebra = CourseId::from_key(&create_course(&app, &staff, "algebra").await);
17641814 let mut made = Vec::new();
17651815 for name in ["9-B", "9-A"] {
@@ -1784,35 +1834,29 @@ async fn a_detach_never_hands_a_row_to_a_class_that_is_gone() {
17841834 }
17851835 let (owner, heir) = (made[0].clone(), made[1].clone());
17861836 assert_eq!(
1787- rows(
1788- &format!(
1789- "SELECT VALUE id FROM enrollment WHERE source = class_group:{}",
1790- owner.key()
1791- ),
1792- &db
1837+ sqlx::query_scalar::<_, i64>(
1838+ "SELECT count(*) FROM enrollment WHERE source = $1",
17931839 )
1794- .await,
1840+ .bind(owner.clone())
1841+ .fetch_one(&db)
1842+ .await
1843+ .unwrap(),
17951844 1,
17961845 "the second attach skips the row the first wrote, so the first owns it"
17971846 );
17981847
17991848 // The heir's class row goes while both of its link rows stay: the state a
18001849 // class deleted out from under its own links leaves.
1801- db.query("DELETE $c")
1802- .bind(("c", heir.record()))
1803- .await
1804- .unwrap()
1805- .check()
1806- .unwrap();
1850+ wipe_row("class_group", heir.uuid(), &db).await;
18071851
18081852 class_course::detach(&db, &owner, &algebra).await.unwrap();
18091853 assert_eq!(
1810- rows("SELECT VALUE id FROM enrollment", &db).await,
1854+ rows("SELECT count(*) FROM enrollment", &db).await,
18111855 0,
18121856 "a row handed to a class that is not there is one nothing can ever sweep"
18131857 );
18141858 assert_eq!(
1815- counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await,
1859+ counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", &db).await,
18161860 0,
18171861 "…and its seat must come back with it"
18181862 );
tests/regress_course_child_orphans.rsmodified+79 -86
@@ -15,33 +15,23 @@
1515 //! `must_exist` still accepts its id, so a bank template can be
1616 //! tagged with a subject nobody can reach.
1717 //!
18-//! All three creates now go through `cap::touch_and_create`, which *moves* the
19-//! course's roster counter (bumped, gated, put back by captured value) inside
20-//! the create's own transaction: the write lands on the very record the delete
21-//! removes, so the store refuses one of the two. `SET x = x` would not do —
22-//! SurrealDB elides an `UPDATE` that leaves the document unchanged, and an
23-//! elided write sits in no write set at all.
18+//! All three creates now go through a claim that locks the course row inside
19+//! the create's own transaction: the write lands on the very row the delete
20+//! removes, so the store refuses one of the two.
2421 //!
2522 //! Two halves, and they are not interchangeable. **This file is the sequential
26-//! one**: it runs anywhere, on the in-memory engine, and pins the existence
27-//! contract (a create against a course that is already gone must be a 404, not
28-//! an orphan) plus the restore (the borrowed counter comes back exactly as it
29-//! was, or the course is undeletable forever — a worse bug than the one being
30-//! fixed).
23+//! one**: it pins the existence contract (a create against a course that is
24+//! already gone must be a 404, not an orphan) plus the restore (the borrowed
25+//! counter comes back exactly as it was, or the course is undeletable forever —
26+//! a worse bug than the one being fixed).
3127 //!
3228 //! The **race** half drives the real interleaving and lives in-crate, one pin
3329 //! per child beside the create it pins —
3430 //! `db::exam::tests::an_exam_never_outlives_its_course`,
3531 //! `db::course_session::tests::a_session_never_outlives_its_course`,
3632 //! `db::subject::tests::a_subject_never_outlives_its_course` — over the
37-//! shared harness `db::course::assert_no_child_outlives_a_course_delete`.
38-//! It is `#[ignore]`d and needs a real server, because the subject there *is*
39-//! the store's conflict detection, which the embedded engine does not have: it
40-//! commits both sides and answers `Ok` to each, so a race test on `memory`
41-//! passes over the hole (same reason `domain::class_course`'s twin is ignored).
42-//! Only in-crate tests can reach `database::init_test_server` and the
43-//! `RACE_LOCK` that serializes them, and a hand-copied bootstrap here would
44-//! drift out of the real one silently.
33+//! shared harness `db::course::assert_no_child_outlives_a_course_delete`,
34+//! against the same per-test Postgres this file runs on.
4535
4636 mod common;
4737
@@ -63,16 +53,34 @@ use hezarfen_backend::domain::timestamp::Timestamp;
6353 use hezarfen_backend::domain::user::UserId;
6454 use hezarfen_backend::error::AppError;
6555 use serde_json::json;
56+use sqlx::Row as _;
6657 use tokio::task::JoinHandle;
6758
68-fn teacher() -> UserId {
69- UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA")
59+async fn teacher(db: &Database) -> UserId {
60+ // Creator columns are foreign keys now, so the fixture teacher is a row,
61+ // not a fabricated id. It never logs in, so the hash is a stub.
62+ sqlx::query(
63+ "INSERT INTO app_user (id, username, password_hash, role) \
64+ VALUES ($1, 'doktor', 'x', 'teacher') ON CONFLICT DO NOTHING",
65+ )
66+ .bind(UserId::generate().uuid())
67+ .execute(db)
68+ .await
69+ .unwrap();
70+ let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = 'doktor'")
71+ .fetch_one(db)
72+ .await
73+ .unwrap()
74+ .try_get(0)
75+ .unwrap();
76+ UserId::from_key(&id.to_string())
7077 }
7178
7279 async fn a_course(db: &Database) -> CourseId {
80+ let teacher = teacher(db).await;
7381 course::create(
7482 db,
75- &teacher(),
83+ &teacher,
7684 CourseTitle::try_new("Fizik").unwrap(),
7785 CourseDescription::try_new("").unwrap(),
7886 CourseKind::course(),
@@ -102,10 +110,11 @@ async fn drop_course(course: &CourseId, db: &Database) -> Result<bool, AppError>
102110
103111 fn make_exam(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {
104112 tokio::spawn(async move {
113+ let teacher = teacher(&db).await;
105114 let kinds = Settings::defaults().get_exam_kinds().to_vec();
106115 hezarfen_backend::db::exam::create(
107116 &db,
108- &teacher(),
117+ &teacher,
109118 &course,
110119 ExamTitle::try_new("quiz").unwrap(),
111120 ExamDescription::try_new("").unwrap(),
@@ -123,10 +132,11 @@ fn make_exam(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>>
123132
124133 fn make_session(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {
125134 tokio::spawn(async move {
135+ let teacher = teacher(&db).await;
126136 db_course_session::create(
127137 &db,
128138 &course,
129- &teacher(),
139+ &teacher,
130140 SessionTopic::try_new("limits").unwrap(),
131141 Timestamp::from_millis(1),
132142 None,
@@ -151,10 +161,11 @@ fn make_subject(course: CourseId, db: Database) -> JoinHandle<Result<(), AppErro
151161
152162 fn make_note(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {
153163 tokio::spawn(async move {
164+ let teacher = teacher(&db).await;
154165 hezarfen_backend::db::course_note::create(
155166 &db,
156167 &course,
157- &teacher(),
168+ &teacher,
158169 CourseNoteTitle::try_new("plan").unwrap(),
159170 CourseNoteContent::try_new("").unwrap(),
160171 )
@@ -166,19 +177,13 @@ fn make_note(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>>
166177 /// How many rows of `table` name `course`. Stored state, never a return value:
167178 /// the whole point is what the store kept.
168179 async fn children(table: &str, course: &CourseId, db: &Database) -> usize {
169- let mut result = db
170- .query(format!(
171- "SELECT VALUE id FROM {table} WHERE course = $course"
172- ))
173- .bind(("course", course.record()))
174- .await
175- .unwrap()
176- .check()
177- .unwrap();
178- result
179- .take::<Vec<surrealdb::types::RecordId>>(0)
180- .unwrap()
181- .len()
180+ sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
181+ "SELECT count(*) FROM {table} WHERE course = $1"
182+ )))
183+ .bind(course.clone())
184+ .fetch_one(db)
185+ .await
186+ .unwrap() as usize
182187 }
183188
184189 // --- the sequential half: the existence contract ---------------------------
@@ -191,7 +196,7 @@ async fn a_create_against_a_deleted_course_refuses(
191196 table: &str,
192197 make: fn(CourseId, Database) -> JoinHandle<Result<(), AppError>>,
193198 ) {
194- let db = database::init_mem().await.unwrap();
199+ let (db, _dbs) = database::init_test_db().await;
195200 let course = a_course(&db).await;
196201 assert!(drop_course(&course, &db).await.unwrap(), "the course goes");
197202
@@ -227,28 +232,27 @@ async fn a_course_note_under_a_deleted_course_is_refused() {
227232 a_create_against_a_deleted_course_refuses("course_note", make_note).await;
228233 }
229234
230-/// The counter the three creates borrow is *given back* — absent stays absent.
231-/// A bump left behind is not a smaller bug than the orphan it prevents: the
232-/// course's delete guard is `WHERE (enrollment_count ?? 0) = 0`, so a course
233-/// that once had an exam created under it would be undeletable forever, and the
234-/// boot backfill keys on the column being `NONE`.
235+/// The counter the three creates borrow is *given back*. A bump left behind is
236+/// not a smaller bug than the orphan it prevents: the course's delete guard
237+/// reads `enrollment_count`, so a course that once had an exam created under it
238+/// would be undeletable forever.
235239 #[tokio::test]
236240 async fn the_creates_give_the_courses_roster_counter_back_untouched() {
237- let db = database::init_mem().await.unwrap();
241+ let (db, _dbs) = database::init_test_db().await;
238242 let course = a_course(&db).await;
239- let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE";
240243
241244 for make in [make_exam, make_session, make_subject, make_note] {
242245 make(course.clone(), db.clone()).await.unwrap().unwrap();
243246 }
244- let mut result = db.query(absent).await.unwrap().check().unwrap();
247+ let bumped = sqlx::query_scalar::<_, i64>(
248+ "SELECT count(*) FROM course WHERE enrollment_count <> 0",
249+ )
250+ .fetch_one(&db)
251+ .await
252+ .unwrap();
245253 assert_eq!(
246- result
247- .take::<Vec<surrealdb::types::RecordId>>(0)
248- .unwrap()
249- .len(),
250- 1,
251- "the borrowed counter must be restored to absent, not to 0"
254+ bumped, 0,
255+ "the borrowed counter must be restored to 0, not left bumped"
252256 );
253257 // The proof that matters to a user: the course is still deletable.
254258 assert!(
@@ -262,12 +266,13 @@ async fn the_creates_give_the_courses_roster_counter_back_untouched() {
262266 /// `course_note_file` children with it too, not just itself.
263267 #[tokio::test]
264268 async fn a_course_note_and_its_files_never_outlive_a_course_delete() {
265- let db = database::init_mem().await.unwrap();
269+ let (db, _dbs) = database::init_test_db().await;
266270 let course = a_course(&db).await;
271+ let teacher = teacher(&db).await;
267272 let note = hezarfen_backend::db::course_note::create(
268273 &db,
269274 &course,
270- &teacher(),
275+ &teacher,
271276 CourseNoteTitle::try_new("plan").unwrap(),
272277 CourseNoteContent::try_new("body").unwrap(),
273278 )
@@ -292,18 +297,15 @@ async fn a_course_note_and_its_files_never_outlive_a_course_delete() {
292297 0,
293298 "a course_note survived its course's delete"
294299 );
295- let mut result = db
296- .query("SELECT VALUE id FROM course_note_file WHERE course_note = $note")
297- .bind(("note", note.get_id().record()))
298- .await
299- .unwrap()
300- .check()
301- .unwrap();
300+ let files = sqlx::query_as::<_, (uuid::Uuid,)>(
301+ "SELECT id FROM course_note_file WHERE course_note = $1",
302+ )
303+ .bind(note.get_id().clone())
304+ .fetch_all(&db)
305+ .await
306+ .unwrap();
302307 assert_eq!(
303- result
304- .take::<Vec<surrealdb::types::RecordId>>(0)
305- .unwrap()
306- .len(),
308+ files.len(),
307309 0,
308310 "a course_note_file survived its note's course's delete"
309311 );
@@ -316,12 +318,13 @@ async fn a_course_note_and_its_files_never_outlive_a_course_delete() {
316318 /// three creates above.
317319 #[tokio::test]
318320 async fn a_course_note_file_under_a_deleted_note_is_refused() {
319- let db = database::init_mem().await.unwrap();
321+ let (db, _dbs) = database::init_test_db().await;
320322 let course = a_course(&db).await;
323+ let teacher = teacher(&db).await;
321324 let note = hezarfen_backend::db::course_note::create(
322325 &db,
323326 &course,
324- &teacher(),
327+ &teacher,
325328 CourseNoteTitle::try_new("plan").unwrap(),
326329 CourseNoteContent::try_new("").unwrap(),
327330 )
@@ -348,29 +351,19 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() {
348351 matches!(file, Err(AppError::Conflict(_))),
349352 "a file upload under a deleted note must refuse, not {file:?}"
350353 );
351- let mut result = db
352- .query("SELECT VALUE id FROM course_note_file WHERE course_note = $note")
353- .bind(("note", note.get_id().record()))
354- .await
355- .unwrap()
356- .check()
357- .unwrap();
354+ let files = sqlx::query_as::<_, (uuid::Uuid,)>(
355+ "SELECT id FROM course_note_file WHERE course_note = $1",
356+ )
357+ .bind(note.get_id().clone())
358+ .fetch_all(&db)
359+ .await
360+ .unwrap();
358361 assert_eq!(
359- result
360- .take::<Vec<surrealdb::types::RecordId>>(0)
361- .unwrap()
362- .len(),
362+ files.len(),
363363 0,
364364 "a refused upload left a row naming a note that is gone"
365365 );
366366 }
367-
368-/// #22, the course's own children over HTTP: a course in an archived term is a
369-/// past year, so its subjects and course notes (and note files) refuse every
370-/// write with the coded 409 while all their reads keep answering. The guard
371-/// sits in each write handler after its authorization check — 403 before 409 —
372-/// on the `course` the shared loaders already hand back, never inside those
373-/// loaders, which the read handlers share.
374367 #[tokio::test]
375368 async fn an_archived_term_freezes_a_course_s_subjects_and_notes() {
376369 let (app, db) = app_and_db().await;
tests/regress_homework_orphans.rsmodified+69 -75
@@ -13,10 +13,10 @@
1313 //! The lock-level races pin the handlers.
1414 //!
1515 //! Every race here is judged on the *store*, never on what a request answered:
16-//! the in-memory engine forges wins under concurrency (src/domain/cap.rs), so a
17-//! 404 or a 204 is evidence of nothing. The windows are opened by the database
18-//! itself — a `DEFINE EVENT` on the table under write fires *inside* the
19-//! writing transaction — rather than by a lucky interleaving.
16+//! under concurrency a 404 or a 204 is evidence of nothing. The windows are
17+//! opened by the database itself — an AFTER trigger on the table under write
18+//! sleeps *inside* the writing transaction — rather than by a lucky
19+//! interleaving.
2020
2121 mod common;
2222
@@ -26,44 +26,32 @@ use common::{
2626 id_of, items, login_as, me_id, multipart_file, send, send_raw, unenroll, upload_file_at,
2727 };
2828 use hezarfen_backend::database::Database;
29+use hezarfen_backend::domain::user::UserId;
2930 use serde_json::{Value, json};
30-use surrealdb::types::RecordId;
31-
32-/// `HOMEWORK_LOCK` is process-wide, and every race below holds a lease of it
33-/// for seconds. Two of them running at once starve each other's window — the
34-/// second one's gates then run *after* the staging meant to happen inside them,
35-/// and the test judges an interleaving that never happened. One at a time; the
36-/// deterministic tests need no ticket.
37-static ONE_RACE_AT_A_TIME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
31+use sqlx::Row as _;
3832
3933 /// A due date comfortably clear of the 60s past-scheduling grace.
4034 fn far_future() -> i64 {
4135 hezarfen_backend::domain::timestamp::Timestamp::now().as_millis() + 7_200_000
4236 }
4337
44-/// How many rows `sql` selects ids for — the stored state, out of the store.
45-async fn rows(db: &Database, sql: &str) -> usize {
46- let mut result = db.query(sql).await.unwrap().check().unwrap();
47- result.take::<Vec<RecordId>>(0).unwrap().len()
38+/// How many rows `sql` counts — the stored state, out of the store.
39+async fn rows(db: &Database, sql: &'static str) -> usize {
40+ sqlx::query_scalar::<_, i64>(sql)
41+ .fetch_one(db)
42+ .await
43+ .unwrap() as usize
4844 }
4945
5046 /// One integer field off one user row, absent counting as zero.
5147 async fn counter(db: &Database, user: &str, field: &str) -> i64 {
52- let mut result = db
53- .query(format!(
54- "SELECT VALUE ({field} ?? 0) FROM type::record('user', $key)"
55- ))
56- .bind(("key", user.to_string()))
57- .await
58- .unwrap()
59- .check()
60- .unwrap();
61- result
62- .take::<Vec<i64>>(0)
63- .unwrap()
64- .first()
65- .copied()
66- .unwrap_or(0)
48+ sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
49+ "SELECT COALESCE({field}, 0) FROM app_user WHERE id = $1"
50+ )))
51+ .bind(UserId::from_key(user))
52+ .fetch_one(db)
53+ .await
54+ .unwrap()
6755 }
6856
6957 /// Upload `bytes` onto the caller's submission to `hw` — no assertion.
@@ -114,22 +102,25 @@ async fn course_with_student(
114102 /// green over the hole.
115103 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
116104 async fn an_upload_inside_a_homework_delete_never_orphans() {
117- let _serial = ONE_RACE_AT_A_TIME.lock().await;
118105 let (app, db) = app_and_db().await;
119106 let teacher = login_as(&app, &db, "ogretmen_odev", "teacher").await;
120107 let (course, subject, student, student_id) =
121108 course_with_student(&app, &db, &teacher, "fizik").await;
122109 let hw = create_homework(&app, &teacher, &course, &subject, "deneme", far_future()).await;
123110
124- // Hold the delete open once the cascade has run but before it commits.
125- db.query(
126- "DEFINE EVENT hold_the_window ON TABLE homework WHEN $event = 'DELETE' \
127- THEN { SLEEP 3s; };",
111+ // Hold the delete open once the cascade has run but before it commits: an
112+ // AFTER DELETE trigger sleeping inside the delete's own transaction.
113+ let mut conn = db.acquire().await.expect("acquire for the trigger");
114+ sqlx::raw_sql(
115+ "CREATE FUNCTION heztest_hold_the_window() RETURNS trigger AS $$
116+ BEGIN PERFORM pg_sleep(3.0); RETURN NULL; END;
117+ $$ LANGUAGE plpgsql;
118+ CREATE TRIGGER heztest_hold_the_window AFTER DELETE ON homework
119+ FOR EACH ROW EXECUTE FUNCTION heztest_hold_the_window();",
128120 )
121+ .execute(&mut *conn)
129122 .await
130- .expect("define the window event")
131- .check()
132- .expect("check the window event");
123+ .expect("define the window trigger");
133124
134125 let drop_it = {
135126 let (app, teacher, hw) = (app.clone(), teacher.clone(), hw.clone());
@@ -176,12 +167,12 @@ async fn an_upload_inside_a_homework_delete_never_orphans() {
176167
177168 // Stored state is the whole verdict.
178169 assert_eq!(
179- rows(&db, "SELECT VALUE id FROM homework_submission").await,
170+ rows(&db, "SELECT count(*) FROM homework_submission").await,
180171 0,
181172 "a submission outlived its homework"
182173 );
183174 assert_eq!(
184- rows(&db, "SELECT VALUE id FROM homework_file").await,
175+ rows(&db, "SELECT count(*) FROM homework_file").await,
185176 0,
186177 "a file outlived its homework"
187178 );
@@ -211,7 +202,6 @@ async fn an_upload_inside_a_homework_delete_never_orphans() {
211202 /// is committed.
212203 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
213204 async fn an_upload_inside_an_audience_patch_is_refused() {
214- let _serial = ONE_RACE_AT_A_TIME.lock().await;
215205 let (app, db) = app_and_db().await;
216206 let teacher = login_as(&app, &db, "ogretmen_kapsam", "teacher").await;
217207 let course = create_course(&app, &teacher, "Coğrafya").await;
@@ -241,14 +231,17 @@ async fn an_upload_inside_an_audience_patch_is_refused() {
241231 );
242232 let hw = id_of(&res.body);
243233
244- db.query(
245- "DEFINE EVENT hold_the_patch ON TABLE homework WHEN $event = 'UPDATE' \
246- THEN { SLEEP 3s; };",
234+ let mut conn = db.acquire().await.expect("acquire for the trigger");
235+ sqlx::raw_sql(
236+ "CREATE FUNCTION heztest_hold_the_patch() RETURNS trigger AS $$
237+ BEGIN PERFORM pg_sleep(3.0); RETURN NULL; END;
238+ $$ LANGUAGE plpgsql;
239+ CREATE TRIGGER heztest_hold_the_patch AFTER UPDATE ON homework
240+ FOR EACH ROW EXECUTE FUNCTION heztest_hold_the_patch();",
247241 )
242+ .execute(&mut *conn)
248243 .await
249- .expect("define the window event")
250- .check()
251- .expect("check the window event");
244+ .expect("define the window trigger");
252245
253246 let narrowing = {
254247 let (app, teacher, hw, kept_id) =
@@ -291,12 +284,12 @@ async fn an_upload_inside_an_audience_patch_is_refused() {
291284 "a student the homework no longer names must be answered 404"
292285 );
293286 assert_eq!(
294- rows(&db, "SELECT VALUE id FROM homework_submission").await,
287+ rows(&db, "SELECT count(*) FROM homework_submission").await,
295288 0,
296289 "a submission landed for a student outside the audience"
297290 );
298291 assert_eq!(
299- rows(&db, "SELECT VALUE id FROM homework_file").await,
292+ rows(&db, "SELECT count(*) FROM homework_file").await,
300293 0,
301294 "... with a file on it"
302295 );
@@ -347,13 +340,13 @@ async fn a_submission_under_a_vanished_homework_is_refused() {
347340 "delete the homework"
348341 );
349342
350- let refused = upsert(&db, &stale, &user, None).await;
343+ let refused = upsert(&db, &stale, &user, None, false).await;
351344 assert!(
352345 refused.is_err(),
353346 "a submission to a homework that is gone must be refused, got {refused:?}"
354347 );
355348 assert_eq!(
356- rows(&db, "SELECT VALUE id FROM homework_submission").await,
349+ rows(&db, "SELECT count(*) FROM homework_submission").await,
357350 0,
358351 "the refused write must leave no row"
359352 );
@@ -427,7 +420,7 @@ async fn a_grade_under_a_vanished_homework_is_refused() {
427420 "a grade on a homework that is gone must be refused, got {refused:?}"
428421 );
429422 assert_eq!(
430- rows(&db, "SELECT VALUE id FROM homework_result").await,
423+ rows(&db, "SELECT count(*) FROM homework_result").await,
431424 0,
432425 "the refused write must leave no row"
433426 );
@@ -479,7 +472,6 @@ async fn a_grade_under_a_vanished_homework_is_refused() {
479472 /// why it is kept and documented rather than trusted to a red test.
480473 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
481474 async fn a_grade_inside_a_course_delete_never_orphans() {
482- let _serial = ONE_RACE_AT_A_TIME.lock().await;
483475 let (app, db) = app_and_db().await;
484476 let teacher = login_as(&app, &db, "ogretmen_ders", "teacher").await;
485477 let (course, subject, _student, student_id) =
@@ -490,14 +482,17 @@ async fn a_grade_inside_a_course_delete_never_orphans() {
490482 // seconds against a one-second wait below: under a loaded test binary the
491483 // spawned request can take a while to be polled at all, and the window has
492484 // to still be open when it gets there.
493- db.query(
494- "DEFINE EVENT hold_the_grade ON TABLE homework_result WHEN $event = 'CREATE' \
495- THEN { SLEEP 3s; };",
485+ let mut conn = db.acquire().await.expect("acquire for the trigger");
486+ sqlx::raw_sql(
487+ "CREATE FUNCTION heztest_hold_the_grade() RETURNS trigger AS $$
488+ BEGIN PERFORM pg_sleep(3.0); RETURN NULL; END;
489+ $$ LANGUAGE plpgsql;
490+ CREATE TRIGGER heztest_hold_the_grade AFTER INSERT ON homework_result
491+ FOR EACH ROW EXECUTE FUNCTION heztest_hold_the_grade();",
496492 )
493+ .execute(&mut *conn)
497494 .await
498- .expect("define the window event")
499- .check()
500- .expect("check the window event");
495+ .expect("define the window trigger");
501496
502497 let grading = {
503498 let (app, teacher, hw, target) =
@@ -550,12 +545,12 @@ async fn a_grade_inside_a_course_delete_never_orphans() {
550545
551546 // Stored state is the whole verdict.
552547 assert_eq!(
553- rows(&db, "SELECT VALUE id FROM homework").await,
548+ rows(&db, "SELECT count(*) FROM homework").await,
554549 0,
555550 "the homework survived its course"
556551 );
557552 assert_eq!(
558- rows(&db, "SELECT VALUE id FROM homework_result").await,
553+ rows(&db, "SELECT count(*) FROM homework_result").await,
559554 0,
560555 "a grade outlived the homework it was written against"
561556 );
@@ -667,7 +662,6 @@ async fn a_student_sees_only_themselves_in_an_assigned_subset() {
667662 /// would fail a *correct* implementation too.
668663 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
669664 async fn a_file_add_racing_a_file_delete_never_500s() {
670- let _serial = ONE_RACE_AT_A_TIME.lock().await;
671665 let (app, db) = app_and_db().await;
672666 let teacher = login_as(&app, &db, "ogretmen_dosya", "teacher").await;
673667 let (course, subject, student, _student_id) =
@@ -688,14 +682,17 @@ async fn a_file_add_racing_a_file_delete_never_500s() {
688682 .await;
689683 let first = listed.body["files"][0]["id"].as_str().unwrap().to_string();
690684
691- db.query(
692- "DEFINE EVENT hold_the_delete ON TABLE homework_file WHEN $event = 'DELETE' \
693- THEN { SLEEP 150ms; };",
685+ let mut conn = db.acquire().await.expect("acquire for the trigger");
686+ sqlx::raw_sql(
687+ "CREATE FUNCTION heztest_hold_the_delete() RETURNS trigger AS $$
688+ BEGIN PERFORM pg_sleep(0.15); RETURN NULL; END;
689+ $$ LANGUAGE plpgsql;
690+ CREATE TRIGGER heztest_hold_the_delete AFTER DELETE ON homework_file
691+ FOR EACH ROW EXECUTE FUNCTION heztest_hold_the_delete();",
694692 )
693+ .execute(&mut *conn)
695694 .await
696- .expect("define the window event")
697- .check()
698- .expect("check the window event");
695+ .expect("define the window trigger");
699696
700697 let removing = {
701698 let (app, student, hw, first) = (app.clone(), student.clone(), hw.clone(), first.clone());
@@ -730,14 +727,11 @@ async fn a_file_add_racing_a_file_delete_never_500s() {
730727 );
731728 // Whatever the order, the stored count matches the stored rows: the
732729 // submission's seat counter is what the cap reads next time.
733- let files = rows(&db, "SELECT VALUE id FROM homework_file").await;
734- let mut result = db
735- .query("SELECT VALUE (file_count ?? 0) FROM homework_submission")
730+ let files = rows(&db, "SELECT count(*) FROM homework_file").await;
731+ let counted: Vec<i64> = sqlx::query_scalar("SELECT file_count FROM homework_submission")
732+ .fetch_all(&db)
736733 .await
737- .unwrap()
738- .check()
739734 .unwrap();
740- let counted: Vec<i64> = result.take(0).unwrap();
741735 assert_eq!(
742736 counted.first().copied().unwrap_or(0),
743737 files as i64,
tests/regress_roles.rsmodified+98 -96
@@ -2,8 +2,7 @@
22 //! 2026-08-02 sweep: an event seat a demotion left claimed forever, and the
33 //! two-query deletes that could orphan a child row.
44 //!
5-//! Every assertion re-reads the *store*. The in-memory engine forges wins under
6-//! concurrency (src/domain/cap.rs), so nothing below is judged on a response
5+//! Every assertion re-reads the *store*: nothing below is judged on a response
76 //! body or asked who won a race — the cascade tests drive the reachable half
87 //! and pin what the store holds once the transaction is done.
98
@@ -14,25 +13,17 @@ use common::{app_and_db, id_of, login, login_as, me_id, send};
1413 use hezarfen_backend::database::Database;
1514 use hezarfen_backend::domain::timestamp::Timestamp;
1615 use serde_json::json;
16+use sqlx::Row as _;
1717
18-/// One counter, re-read out of the store — never off a response body.
19-async fn counter(sql: &str, db: &Database) -> i64 {
20- let mut result = db.query(sql).await.unwrap().check().unwrap();
21- result
22- .take::<Vec<i64>>(0)
23- .unwrap()
24- .first()
25- .copied()
26- .unwrap_or(0)
18+/// One counter, re-read out of the store — never off a response body. `sql`
19+/// is a whole scalar query.
20+async fn counter(sql: &'static str, db: &Database) -> i64 {
21+ sqlx::query_scalar(sql).fetch_one(db).await.unwrap()
2722 }
2823
29-/// How many rows `sql` selects ids for.
30-async fn rows(sql: &str, db: &Database) -> i64 {
31- let mut result = db.query(sql).await.unwrap().check().unwrap();
32- result
33- .take::<Vec<surrealdb::types::RecordId>>(0)
34- .unwrap()
35- .len() as i64
24+/// How many rows `sql` counts.
25+async fn rows(sql: &'static str, db: &Database) -> i64 {
26+ counter(sql, db).await
3627 }
3728
3829 /// Put `user` on `event`'s signup list as `cookie`.
@@ -81,11 +72,10 @@ async fn free_seat(app: &axum::Router, cookie: &str, event: &str, user: &str) ->
8172 /// The API refuses to *schedule* one there (60s grace), so the row is aged in
8273 /// the store — the state a real event reaches by the clock simply running on.
8374 async fn age_event(event: &str, db: &Database) {
84- db.query("UPDATE type::record('event', $key) SET starts_at = 1")
85- .bind(("key", event.to_string()))
75+ sqlx::query("UPDATE event SET starts_at = 1 WHERE id = $1")
76+ .bind(uuid::Uuid::parse_str(event).expect("a uuid event id"))
77+ .execute(db)
8678 .await
87- .unwrap()
88- .check()
8979 .unwrap();
9080 }
9181
@@ -109,7 +99,7 @@ async fn a_demotion_frees_the_event_seat_nothing_else_could_free() {
10999 let res = seat(&app, &teacher, &event, &ali_id).await;
110100 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
111101 assert_eq!(
112- counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await,
102+ counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", &db).await,
113103 1
114104 );
115105
@@ -126,12 +116,12 @@ async fn a_demotion_frees_the_event_seat_nothing_else_could_free() {
126116 // The row goes and the seat comes back with it — one is worthless without
127117 // the other.
128118 assert_eq!(
129- rows("SELECT VALUE id FROM registration", &db).await,
119+ rows("SELECT count(*) FROM registration", &db).await,
130120 0,
131121 "a non-student may hold no signup row"
132122 );
133123 assert_eq!(
134- counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await,
124+ counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", &db).await,
135125 0,
136126 "the seat must be handed back, or the event is full forever"
137127 );
@@ -179,12 +169,12 @@ async fn a_promotion_keeps_the_signup_the_promoted_user_can_still_free() {
179169 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
180170
181171 assert_eq!(
182- rows("SELECT VALUE id FROM registration", &db).await,
172+ rows("SELECT count(*) FROM registration", &db).await,
183173 1,
184174 "a promotion must not destroy a signup its holder can still free"
185175 );
186176 assert_eq!(
187- counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await,
177+ counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", &db).await,
188178 1,
189179 "…and the seat it holds stays claimed with it"
190180 );
@@ -205,9 +195,9 @@ async fn a_promotion_keeps_the_signup_the_promoted_user_can_still_free() {
205195 .expect("re-login");
206196 let res = free_seat(&app, &promoted, &event, &ali_id).await;
207197 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
208- assert_eq!(rows("SELECT VALUE id FROM registration", &db).await, 0);
198+ assert_eq!(rows("SELECT count(*) FROM registration", &db).await, 0);
209199 assert_eq!(
210- counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await,
200+ counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", &db).await,
211201 0
212202 );
213203 }
@@ -247,12 +237,12 @@ async fn a_demotion_leaves_a_frozen_signup_list_exactly_as_it_stands() {
247237 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
248238
249239 assert_eq!(
250- rows("SELECT VALUE id FROM registration", &db).await,
240+ rows("SELECT count(*) FROM registration", &db).await,
251241 1,
252242 "a closed roster must not be rewritten by a role change"
253243 );
254244 assert_eq!(
255- counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await,
245+ counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", &db).await,
256246 1,
257247 "…and its seat stays claimed with it — the row is the seat"
258248 );
@@ -285,12 +275,21 @@ async fn the_sweep_deletes_an_orphan_signup_instead_of_stranding_it() {
285275 // The state a delete that raced a register used to leave: the row outlives
286276 // its event. Written straight into the store, since the cascade now makes
287277 // it unreachable through the API.
288- db.query("DELETE type::record('event', $key)")
289- .bind(("key", doomed.clone()))
278+ // The state a delete that raced a register used to leave: the row outlives
279+ // its event. Written straight into the store, since the cascade now makes
280+ // it unreachable through the API. Real FKs refuse that state, so the
281+ // delete is forced with FK triggers suspended for the one transaction.
282+ let mut tx = db.begin().await.unwrap();
283+ sqlx::query("SET LOCAL session_replication_role = replica")
284+ .execute(&mut *tx)
290285 .await
291- .unwrap()
292- .check()
293286 .unwrap();
287+ sqlx::query("DELETE FROM event WHERE id = $1")
288+ .bind(uuid::Uuid::parse_str(&doomed).expect("a uuid event id"))
289+ .execute(&mut *tx)
290+ .await
291+ .unwrap();
292+ tx.commit().await.unwrap();
294293
295294 let res = send(
296295 &app,
@@ -303,12 +302,12 @@ async fn the_sweep_deletes_an_orphan_signup_instead_of_stranding_it() {
303302 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
304303
305304 assert_eq!(
306- rows("SELECT VALUE id FROM registration", &db).await,
305+ rows("SELECT count(*) FROM registration", &db).await,
307306 0,
308307 "an orphan signup must go with the rest — nothing else can ever remove it"
309308 );
310309 assert_eq!(
311- counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await,
310+ counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", &db).await,
312311 0,
313312 "and the surviving event still gets its seat back"
314313 );
@@ -316,17 +315,11 @@ async fn the_sweep_deletes_an_orphan_signup_instead_of_stranding_it() {
316315
317316 /// How many boards list `user` as a participant, read out of the store.
318317 async fn boards_listing(user: &str, db: &Database) -> i64 {
319- let mut result = db
320- .query("SELECT VALUE id FROM board WHERE type::record('user', $u) IN participants")
321- .bind(("u", user.to_string()))
318+ sqlx::query_scalar("SELECT count(*) FROM board WHERE $1 = ANY(participants)")
319+ .bind(uuid::Uuid::parse_str(user).expect("a uuid user id"))
320+ .fetch_one(db)
322321 .await
323322 .unwrap()
324- .check()
325- .unwrap();
326- result
327- .take::<Vec<surrealdb::types::RecordId>>(0)
328- .unwrap()
329- .len() as i64
330323 }
331324
332325 /// A `parent` is barred from the whiteboard outright, and invites already
@@ -386,7 +379,7 @@ async fn a_demotion_to_parent_leaves_every_board_roster_and_deletes_nothing() {
386379 );
387380 // Nothing was destroyed, and the board they created is untouched beyond
388381 // that: same creator, and its other participant still on it.
389- assert_eq!(rows("SELECT VALUE id FROM board", &db).await, 2);
382+ assert_eq!(rows("SELECT count(*) FROM board", &db).await, 2);
390383 let res = send(&app, "GET", &format!("/boards/{own_id}"), Some(&ali), None).await;
391384 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
392385 assert_eq!(res.body["creator"], veli_id);
@@ -441,34 +434,46 @@ async fn a_student_holding_every_grant(
441434
442435 /// `user`'s live role, read out of the store.
443436 async fn role_of(user: &str, db: &Database) -> String {
444- let mut result = db
445- .query("SELECT VALUE role FROM type::record('user', $u)")
446- .bind(("u", user.to_string()))
437+ sqlx::query_scalar("SELECT role FROM app_user WHERE id = $1")
438+ .bind(uuid::Uuid::parse_str(user).expect("a uuid user id"))
439+ .fetch_one(db)
447440 .await
448- .unwrap()
449- .check()
450- .unwrap();
451- result
452- .take::<Vec<String>>(0)
453- .unwrap()
454- .first()
455- .cloned()
456441 .expect("the user row must exist")
457442 }
458443
459444 /// Make the next write of `kind` on `table` fail, from inside whatever
460-/// transaction performs it: a `DEFINE EVENT` on the table under write fires
461-/// *within* that write, which is the only way to fail one statement of a
462-/// cascade deterministically (no sleeps, no racing tasks).
445+/// transaction performs it: a trigger that raises aborts that very write, and
446+/// with it the whole cascade's transaction — the only way to fail one statement
447+/// of a cascade deterministically (no sleeps, no racing tasks).
463448 async fn poison(table: &str, kind: &str, db: &Database) {
464- db.query(format!(
465- "DEFINE EVENT poison ON TABLE {table} WHEN $event = '{kind}' \
466- THEN {{ THROW 'poisoned' }}"
467- ))
449+ let firing = match kind {
450+ "CREATE" => "INSERT",
451+ "UPDATE" => "UPDATE",
452+ "DELETE" => "DELETE",
453+ other => panic!("unknown event kind {other}"),
454+ };
455+ let mut conn = db.acquire().await.expect("acquire for the trigger");
456+ sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
457+ "CREATE FUNCTION heztest_poison() RETURNS trigger AS $$
458+ BEGIN RAISE EXCEPTION 'poisoned'; END;
459+ $$ LANGUAGE plpgsql;
460+ CREATE TRIGGER heztest_poison BEFORE {firing} ON {table}
461+ FOR EACH ROW EXECUTE FUNCTION heztest_poison();"
462+ )))
463+ .execute(&mut *conn)
464+ .await
465+ .expect("define the poison trigger");
466+}
467+
468+/// Take the poison back, so the re-sent PATCH can land.
469+async fn unpoison(table: &str, db: &Database) {
470+ sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
471+ "DROP TRIGGER IF EXISTS heztest_poison ON {table};
472+ DROP FUNCTION IF EXISTS heztest_poison();"
473+ )))
474+ .execute(db)
468475 .await
469- .unwrap()
470- .check()
471- .unwrap();
476+ .expect("remove the poison trigger");
472477 }
473478
474479 /// Every grant of `ali_id` still standing, and the old role with them — what
@@ -480,27 +485,27 @@ async fn nothing_was_swept(ali_id: &str, db: &Database) {
480485 "the role write must roll back with the sweep that failed"
481486 );
482487 assert_eq!(
483- rows("SELECT VALUE id FROM enrollment", db).await,
488+ rows("SELECT count(*) FROM enrollment", db).await,
484489 1,
485490 "the enrollment must survive a failed cascade"
486491 );
487492 assert_eq!(
488- counter("SELECT VALUE enrollment_count ?? 0 FROM course", db).await,
493+ counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", db).await,
489494 1,
490495 "…and so must its seat, or the roster and the count disagree forever"
491496 );
492497 assert_eq!(
493- rows("SELECT VALUE id FROM parent_link", db).await,
498+ rows("SELECT count(*) FROM parent_link", db).await,
494499 1,
495500 "the parent link must survive a failed cascade"
496501 );
497502 assert_eq!(
498- rows("SELECT VALUE id FROM registration", db).await,
503+ rows("SELECT count(*) FROM registration", db).await,
499504 1,
500505 "the signup must survive a failed cascade"
501506 );
502507 assert_eq!(
503- counter("SELECT VALUE registration_count ?? 0 FROM event", db).await,
508+ counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", db).await,
504509 1,
505510 "…with its seat still claimed"
506511 );
@@ -533,18 +538,23 @@ async fn the_retry_takes_everything(
533538 assert_eq!(role_of(ali_id, db).await, "parent");
534539 for table in ["enrollment", "parent_link", "registration", "class_member"] {
535540 assert_eq!(
536- rows(&format!("SELECT VALUE id FROM {table}"), db).await,
541+ sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
542+ "SELECT count(*) FROM {table}"
543+ )))
544+ .fetch_one(db)
545+ .await
546+ .unwrap(),
537547 0,
538548 "{table} must be swept by the re-sent PATCH"
539549 );
540550 }
541551 assert_eq!(boards_listing(ali_id, db).await, 0);
542552 assert_eq!(
543- counter("SELECT VALUE enrollment_count ?? 0 FROM course", db).await,
553+ counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", db).await,
544554 0
545555 );
546556 assert_eq!(
547- counter("SELECT VALUE registration_count ?? 0 FROM event", db).await,
557+ counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", db).await,
548558 0
549559 );
550560 // The seat is usable, which is the whole point of freeing it: the one-seat
@@ -566,9 +576,9 @@ async fn the_retry_takes_everything(
566576 /// enrollment, the parent link and the event seat already gone, and nothing to
567577 /// ever put them back.
568578 ///
569-/// The failure is injected the way `regress_classes` does it: a `DEFINE EVENT`
570-/// on a table the cascade writes fires *inside* that write, so the abort is
571-/// deterministic instead of a race the in-memory engine would lie about. Both
579+/// The failure is injected the way `regress_classes` does it: a trigger on a
580+/// table the cascade writes raises inside that very write, so the abort is
581+/// deterministic instead of a race. Both
572582 /// ends of the cascade are poisoned, in two tests, because they fail different
573583 /// things: the board roster is the *last* statement of the parent arm (so every
574584 /// assertion below it is about a write that already succeeded and must be
@@ -596,11 +606,7 @@ async fn a_failure_late_in_the_cascade_leaves_the_old_role_and_every_grant_stand
596606 );
597607 nothing_was_swept(&ali_id, &db).await;
598608
599- db.query("REMOVE EVENT poison ON TABLE board")
600- .await
601- .unwrap()
602- .check()
603- .unwrap();
609+ unpoison("board", &db).await;
604610 the_retry_takes_everything(&app, &db, &admin, &teacher, &ali_id).await;
605611 }
606612
@@ -630,11 +636,7 @@ async fn a_failure_early_in_the_cascade_rolls_the_role_write_back_with_it() {
630636 );
631637 nothing_was_swept(&ali_id, &db).await;
632638
633- db.query("REMOVE EVENT poison ON TABLE enrollment")
634- .await
635- .unwrap()
636- .check()
637- .unwrap();
639+ unpoison("enrollment", &db).await;
638640 the_retry_takes_everything(&app, &db, &admin, &teacher, &ali_id).await;
639641 }
640642
@@ -661,7 +663,7 @@ async fn deleting_an_event_takes_its_children_with_it() {
661663 )
662664 .await;
663665 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
664- assert_eq!(rows("SELECT VALUE id FROM attendance", &db).await, 1);
666+ assert_eq!(rows("SELECT count(*) FROM attendance", &db).await, 1);
665667
666668 let res = send(
667669 &app,
@@ -673,14 +675,14 @@ async fn deleting_an_event_takes_its_children_with_it() {
673675 .await;
674676 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
675677
676- assert_eq!(rows("SELECT VALUE id FROM event", &db).await, 0);
678+ assert_eq!(rows("SELECT count(*) FROM event", &db).await, 0);
677679 assert_eq!(
678- rows("SELECT VALUE id FROM attendance", &db).await,
680+ rows("SELECT count(*) FROM attendance", &db).await,
679681 0,
680682 "no mark may outlive its event"
681683 );
682684 assert_eq!(
683- rows("SELECT VALUE id FROM registration", &db).await,
685+ rows("SELECT count(*) FROM registration", &db).await,
684686 0,
685687 "no signup may outlive its event"
686688 );
@@ -708,14 +710,14 @@ async fn deleting_a_note_takes_its_attachment_rows_with_it() {
708710
709711 let up = common::upload_file(&app, &ali, &note, "plan.txt", "text/plain", b"merhaba").await;
710712 assert_eq!(up.status, StatusCode::CREATED, "{}", up.body);
711- assert_eq!(rows("SELECT VALUE id FROM note_file", &db).await, 1);
713+ assert_eq!(rows("SELECT count(*) FROM note_file", &db).await, 1);
712714
713715 let res = send(&app, "DELETE", &format!("/notes/{note}"), Some(&ali), None).await;
714716 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
715717
716- assert_eq!(rows("SELECT VALUE id FROM note", &db).await, 0);
718+ assert_eq!(rows("SELECT count(*) FROM note", &db).await, 0);
717719 assert_eq!(
718- rows("SELECT VALUE id FROM note_file", &db).await,
720+ rows("SELECT count(*) FROM note_file", &db).await,
719721 0,
720722 "no attachment row may outlive its note"
721723 );