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() {
805 assert_eq!(total(&notes.body), 0, "old rows survived the drop");805 assert_eq!(total(&notes.body), 0, "old rows survived the drop");
806 }806 }
807 807
808-/// Claim 2, remote mode: `Tenants::create`/`drop` interpolate the slug into808+/// Claim 2, the school lifecycle: `Tenants::create`/`drop` interpolate the slug
809-/// `DEFINE DATABASE` / `REMOVE DATABASE`. Not injectable — but the statements809+/// into `CREATE DATABASE` / `DROP DATABASE`. Not injectable — but the statements
810-/// must at least *execute* for every slug `Slug::try_new` accepts. Run the exact810+/// must at least *execute* for every slug `Slug::try_new` accepts. Each slug is
811-/// production statements against a live SurrealDB parser.811+/// driven through the real lifecycle over HTTP, which is exactly those
812+/// statements against the live server.
812 #[tokio::test]813 #[tokio::test]
813 async fn probe_remote_mode_database_statements_execute_for_every_accepted_slug() {814 async fn probe_remote_mode_database_statements_execute_for_every_accepted_slug() {
814- let Some(deployment) = common::remote_deployment(&[]).await else {815+ let (app, _db, _tenants) = deployment().await;
815- return;816+ let builder = builder_login(&app).await;
816- };
817- let control = deployment.tenants.control();
818 let mut broken: Vec<String> = Vec::new();817 let mut broken: Vec<String> = Vec::new();
819 818
820 for raw in [819 for raw in [
@@ -827,32 +826,38 @@ async fn probe_remote_mode_database_statements_execute_for_every_accepted_slug()
827 "12345",826 "12345",
828 "a1",827 "a1",
829 ] {828 ] {
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 {
831 continue;832 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}"));
848 }833 }
849- if let Err(err) = remove {834+ // The exact statements `Tenants::create` / `drop` send, through the
850- broken.push(format!("REMOVE DATABASE {raw} -> {err}"));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+ ));
851 }856 }
852 }857 }
853 assert!(858 assert!(
854 broken.is_empty(),859 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{}",
856 broken.join("\n")861 broken.join("\n")
857 );862 );
858 }863 }
@@ -1220,14 +1225,12 @@ async fn probe_concurrent_creates_of_one_slug_leave_one_school() {
1220 assert_eq!(opens, 1, "{opens} of the two admin passwords open p6race");1225 assert_eq!(opens, 1, "{opens} of the two admin passwords open p6race");
1221 }1226 }
1222 1227
1223-/// Claim 1/2 driven against a **real remote deployment** — the mode every test1228+/// Claim 1/2 driven against a full deployment of its own, where the school
1224-/// above skips, and the only one where `DEFINE DATABASE` / `REMOVE DATABASE`1229+/// lifecycle's `CREATE DATABASE` / `DROP DATABASE` actually run.
1225-/// actually run. `ata-koleji` is the slug the OpenAPI schema advertises.1230+/// `ata-koleji` is the slug the OpenAPI schema advertises.
1226 #[tokio::test]1231 #[tokio::test]
1227 async fn probe_remote_deployment_creates_and_deletes_a_hyphenated_school() {1232 async fn probe_remote_deployment_creates_and_deletes_a_hyphenated_school() {
1228- let Some(deployment) = common::remote_deployment(&[]).await else {1233+ let deployment = common::deployment_with(&[]).await;
1229- return;
1230- };
1231 let app = deployment.app;1234 let app = deployment.app;
1232 builder::ensure(1235 builder::ensure(
1233 deployment.tenants.control(),1236 deployment.tenants.control(),
@@ -2005,18 +2008,11 @@ async fn probe_a_refused_batch_leaves_the_row_byte_identical() {
2005 let builder = builder_login(&app).await;2008 let builder = builder_login(&app).await;
2006 2009
2007 async fn raw_row(tenants: &Tenants) -> Vec<String> {2010 async fn raw_row(tenants: &Tenants) -> Vec<String> {
2008- tenants2011+ sqlx::query_scalar("SELECT modules FROM school WHERE slug = $1")
2009- .control()2012+ .bind(DEMO_SLUG)
2010- .query(format!(2013+ .fetch_one(tenants.control())
2011- "SELECT VALUE modules FROM type::record('school', '{DEMO_SLUG}')"
2012- ))
2013 .await2014 .await
2014 .expect("raw read")2015 .expect("raw read")
2015- .check()
2016- .expect("raw check")
2017- .take::<Vec<Vec<String>>>(0)
2018- .expect("modules column")
2019- .remove(0)
2020 }2016 }
2021 2017
2022 let before = raw_row(&tenants).await;2018 let before = raw_row(&tenants).await;
@@ -2048,13 +2044,11 @@ async fn probe_a_refused_batch_leaves_the_row_byte_identical() {
2048 /// a thread-local subscriber cannot measure this reliably: `tracing` caches a2044 /// a thread-local subscriber cannot measure this reliably: `tracing` caches a
2049 /// callsite's interest process-wide the first time any thread reaches it, and2045 /// callsite's interest process-wide the first time any thread reaches it, and
2050 /// with tests running in parallel that thread is usually a sibling with no2046 /// with tests running in parallel that thread is usually a sibling with no
2051-/// subscriber — the SurrealDB callsites are then disabled for the whole2047+/// subscriber — the sqlx callsites are then disabled for the whole process
2052-/// process before this test ever asks, and the count is 0 (measured: 0 in 7 of2048+/// before this test ever asks, and the count is 0. Global is safe here because
2053-/// 8 runs against noisy siblings; a global subscriber counted on 6 of 6).2049+/// this subscriber only counts: it stores nothing, prints nothing, and its
2054-/// Global is safe here because this subscriber only counts: it stores nothing,2050+/// `enabled` refuses every callsite that is not a sqlx one on *this* test's
2055-/// prints nothing, and its `enabled` refuses every callsite that is not a2051+/// thread, so a sibling test neither pays for it nor lands in the figure.
2056-/// SurrealDB one on *this* test's thread, so a sibling test neither pays for it
2057-/// nor lands in the figure.
2058 #[tokio::test]2052 #[tokio::test]
2059 async fn probe_registry_reads_per_request() {2053 async fn probe_registry_reads_per_request() {
2060 use std::sync::Arc;2054 use std::sync::Arc;
@@ -2072,7 +2066,7 @@ async fn probe_registry_reads_per_request() {
2072 tracing::subscriber::Interest::sometimes()2066 tracing::subscriber::Interest::sometimes()
2073 }2067 }
2074 fn enabled(&self, meta: &tracing::Metadata<'_>) -> bool {2068 fn enabled(&self, meta: &tracing::Metadata<'_>) -> bool {
2075- meta.target().starts_with("surrealdb") && std::thread::current().id() == self.thread2069+ meta.target().starts_with("sqlx") && std::thread::current().id() == self.thread
2076 }2070 }
2077 fn new_span(&self, _: &span::Attributes<'_>) -> span::Id {2071 fn new_span(&self, _: &span::Attributes<'_>) -> span::Id {
2078 self.count.fetch_add(1, Ordering::Relaxed);2072 self.count.fetch_add(1, Ordering::Relaxed);
@@ -2100,10 +2094,10 @@ async fn probe_registry_reads_per_request() {
2100 let res = send(&app, "GET", "/notes", Some(&cookie), None).await;2094 let res = send(&app, "GET", "/notes", Some(&cookie), None).await;
2101 assert_eq!(res.status, StatusCode::OK, "{:?}", res.body);2095 assert_eq!(res.status, StatusCode::OK, "{:?}", res.body);
2102 let seen = count.load(Ordering::Relaxed);2096 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}");
2104 assert!(2098 assert!(
2105 seen > 0,2099 seen > 0,
2106- "UNMEASURED: the surrealdb SDK emitted no tracing spans, so per-request \2100+ "UNMEASURED: sqlx emitted no tracing spans, so per-request \
2107 registry reads cannot be counted this way"2101 registry reads cannot be counted this way"
2108 );2102 );
2109 }2103 }
tests/regress_blueprints.rsmodified+181 -212
@@ -13,45 +13,47 @@
13 mod common;13 mod common;
14 14
15 use axum::http::StatusCode;15 use axum::http::StatusCode;
16-use common::{Res, app_and_db, create_course, login_as, me_id, send};16+use common::{GHOST_ID, Res, app_and_db, create_course, login_as, me_id, send};
17 use hezarfen_backend::database::Database;17 use hezarfen_backend::database::Database;
18 use hezarfen_backend::domain::class_blueprint::ClassBlueprint;18 use hezarfen_backend::domain::class_blueprint::ClassBlueprint;
19 use hezarfen_backend::domain::course::CourseId;19 use hezarfen_backend::domain::course::CourseId;
20+use hezarfen_backend::domain::timestamp::Timestamp;
20 use hezarfen_backend::domain::user::UserId;21 use hezarfen_backend::domain::user::UserId;
21 use hezarfen_backend::error::AppError;22 use hezarfen_backend::error::AppError;
22 use hezarfen_backend::service::class_blueprint;23 use hezarfen_backend::service::class_blueprint;
23 use serde_json::{Value, json};24 use serde_json::{Value, json};
24 25
25-/// One counter, re-read out of the store.26+/// One counter, re-read out of the store. `sql` is a whole scalar query.
26-async fn counter(sql: &str, db: &Database) -> i64 {27+async fn counter(sql: &'static str, db: &Database) -> i64 {
27- let mut result = db.query(sql).await.unwrap().check().unwrap();28+ sqlx::query_scalar(sql).fetch_one(db).await.unwrap()
28- result
29- .take::<Vec<i64>>(0)
30- .unwrap()
31- .first()
32- .copied()
33- .unwrap_or(0)
34 }29 }
35 30
36-/// How many rows `sql` selects ids for.31+/// How many rows `sql` counts.
37-async fn rows(sql: &str, db: &Database) -> i64 {32+async fn rows(sql: &'static str, db: &Database) -> i64 {
38- let mut result = db.query(sql).await.unwrap().check().unwrap();33+ counter(sql, db).await
39- result34+}
40- .take::<Vec<surrealdb::types::RecordId>>(0)35+
41- .unwrap()36+/// One row's counter column, re-read out of the store.
42- .len() as i6437+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()
43 }45 }
44 46
45 /// Is that course on that class, in the store?47 /// Is that course on that class, in the store?
46 async fn attached(class: &str, course: &str, db: &Database) -> bool {48 async fn attached(class: &str, course: &str, db: &Database) -> bool {
47- rows(49+ sqlx::query_scalar::<_, i64>(
48- &format!(50+ "SELECT count(*) FROM class_course WHERE class = $1 AND course = $2",
49- "SELECT VALUE id FROM class_course WHERE class = class_group:{class} \
50- AND course = course:{course}"
51- ),
52- db,
53 )51 )
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)
54 .await55 .await
56+ .unwrap()
55 == 157 == 1
56 }58 }
57 59
@@ -59,33 +61,26 @@ async fn attached(class: &str, course: &str, db: &Database) -> bool {
59 /// no such key at all — which is the whole provenance rule: absent means a61 /// no such key at all — which is the whole provenance rule: absent means a
60 /// human attached it.62 /// human attached it.
61 async fn source_of(class: &str, course: &str, db: &Database) -> Option<String> {63 async fn source_of(class: &str, course: &str, db: &Database) -> Option<String> {
62- let mut result = db64+ sqlx::query_scalar::<_, Option<String>>(
63- .query(format!(65+ "SELECT source FROM class_course WHERE class = $1 AND course = $2",
64- "SELECT VALUE (IF source != NONE THEN record::id(source) ELSE '' END) \66+ )
65- FROM class_course WHERE class = class_group:{class} AND course = course:{course}"67+ .bind(uuid::Uuid::parse_str(class).expect("a uuid class id"))
66- ))68+ .bind(uuid::Uuid::parse_str(course).expect("a uuid course id"))
67- .await69+ .fetch_one(db)
68- .unwrap()70+ .await
69- .check()71+ .unwrap()
70- .unwrap();
71- result
72- .take::<Vec<String>>(0)
73- .unwrap()
74- .into_iter()
75- .next()
76- .filter(|key| !key.is_empty())
77 }72 }
78 73
79 /// Does that grade's template still name that course, in the store?74 /// Does that grade's template still name that course, in the store?
80 async fn templated(grade: &str, course: &str, db: &Database) -> bool {75 async fn templated(grade: &str, course: &str, db: &Database) -> bool {
81- rows(76+ sqlx::query_scalar::<_, i64>(
82- &format!(77+ "SELECT count(*) FROM class_blueprint WHERE grade = $1 AND $2 = ANY(courses)",
83- "SELECT VALUE id FROM class_blueprint \
84- WHERE grade = '{grade}' AND course:{course} IN courses"
85- ),
86- db,
87 )78 )
79+ .bind(grade)
80+ .bind(CourseId::from_key(course))
81+ .fetch_one(db)
88 .await82 .await
83+ .unwrap()
89 == 184 == 1
90 }85 }
91 86
@@ -250,7 +245,7 @@ async fn a_blueprint_is_created_read_updated_and_deleted() {
250 )245 )
251 .await;246 .await;
252 assert_eq!(dropped.status, StatusCode::NO_CONTENT);247 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);
254 let gone = send(&app, "GET", "/classes/blueprints/9", Some(&manager), None).await;249 let gone = send(&app, "GET", "/classes/blueprints/9", Some(&manager), None).await;
255 assert_eq!(gone.status, StatusCode::NOT_FOUND);250 assert_eq!(gone.status, StatusCode::NOT_FOUND);
256 251
@@ -313,23 +308,20 @@ async fn a_fresh_class_takes_its_grades_blueprint() {
313 "the blueprint must own what it attached"308 "the blueprint must own what it attached"
314 );309 );
315 assert_eq!(310 assert_eq!(
316- rows(311+ sqlx::query_scalar::<_, i64>(
317- &format!(312+ "SELECT count(*) FROM enrollment WHERE course = $1 AND app_user = $2",
318- "SELECT VALUE id FROM enrollment WHERE course = course:{course} \
319- AND user = user:{student}"
320- ),
321- &db
322 )313 )
323- .await,314+ .bind(CourseId::from_key(course))
315+ .bind(UserId::from_key(&student))
316+ .fetch_one(&db)
317+ .await
318+ .unwrap(),
324 1,319 1,
325 "stocking a class enrolls its roster, in real rows"320 "stocking a class enrolls its roster, in real rows"
326 );321 );
327 }322 }
328 assert_eq!(323 assert_eq!(
329- counter(324+ count_on("class_course_count", "class_group", &class, &db)
330- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"),
331- &db
332- )
333 .await,325 .await,
334 2326 2
335 );327 );
@@ -345,7 +337,7 @@ async fn a_fresh_class_takes_its_grades_blueprint() {
345 .await;337 .await;
346 assert_eq!(twice.status, StatusCode::OK);338 assert_eq!(twice.status, StatusCode::OK);
347 assert!(skips(&twice).is_empty());339 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);
349 341
350 // A class whose grade no blueprint covers is a 404, not an empty success.342 // A class whose grade no blueprint covers is a 404, not an empty success.
351 let other = create_class(&app, &manager, "10-A", "10").await;343 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() {
411 );403 );
412 }404 }
413 assert_eq!(405 assert_eq!(
414- counter(406+ count_on("class_course_count", "class_group", &class, &db)
415- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"),
416- &db
417- )
418 .await,407 .await,
419 2408 2
420 );409 );
@@ -425,14 +414,14 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() {
425 let student = student_in(&app, &db, &class, &manager, "ali").await;414 let student = student_in(&app, &db, &class, &manager, "ali").await;
426 for course in [&algebra, &physics] {415 for course in [&algebra, &physics] {
427 assert_eq!(416 assert_eq!(
428- rows(417+ sqlx::query_scalar::<_, i64>(
429- &format!(418+ "SELECT count(*) FROM enrollment WHERE course = $1 AND app_user = $2",
430- "SELECT VALUE id FROM enrollment WHERE course = course:{course} \
431- AND user = user:{student}"
432- ),
433- &db
434 )419 )
435- .await,420+ .bind(CourseId::from_key(course))
421+ .bind(UserId::from_key(&student))
422+ .fetch_one(&db)
423+ .await
424+ .unwrap(),
436 1,425 1,
437 "a stocked class enrolls its roster like any other"426 "a stocked class enrolls its roster like any other"
438 );427 );
@@ -454,11 +443,13 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() {
454 assert!(skips(&res).is_empty(), "{:?}", res.body);443 assert!(skips(&res).is_empty(), "{:?}", res.body);
455 let bare = res.body["class"]["id"].as_str().unwrap();444 let bare = res.body["class"]["id"].as_str().unwrap();
456 assert_eq!(445 assert_eq!(
457- rows(446+ sqlx::query_scalar::<_, i64>(
458- &format!("SELECT VALUE id FROM class_course WHERE class = class_group:{bare}"),447+ "SELECT count(*) FROM class_course WHERE class = $1",
459- &db
460 )448 )
461- .await,449+ .bind(uuid::Uuid::parse_str(bare).expect("a uuid class id"))
450+ .fetch_one(&db)
451+ .await
452+ .unwrap(),
462 0,453 0,
463 "nothing may be attached to a section no template reached"454 "nothing may be attached to a section no template reached"
464 );455 );
@@ -496,10 +487,10 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() {
496 // meets when a course goes after it read the list. Nothing carries it yet487 // meets when a course goes after it read the list. Nothing carries it yet
497 // (no section exists at grade 9), so this is the pair that cannot fit when488 // (no section exists at grade 9), so this is the pair that cannot fit when
498 // the first one is created.489 // 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)
500 .await493 .await
501- .unwrap()
502- .check()
503 .unwrap();494 .unwrap();
504 assert!(495 assert!(
505 templated("9", &physics, &db).await,496 templated("9", &physics, &db).await,
@@ -531,11 +522,11 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() {
531 .expect("class id")522 .expect("class id")
532 .to_string();523 .to_string();
533 assert_eq!(524 assert_eq!(
534- rows(525+ sqlx::query_scalar::<_, i64>("SELECT count(*) FROM class_group WHERE id = $1")
535- &format!("SELECT VALUE id FROM class_group WHERE id = class_group:{class}"),526+ .bind(uuid::Uuid::parse_str(&class).expect("a uuid class id"))
536- &db527+ .fetch_one(&db)
537- )528+ .await
538- .await,529+ .unwrap(),
539 1,530 1,
540 "the class is really there — the skip is a report, not a rollback"531 "the class is really there — the skip is a report, not a rollback"
541 );532 );
@@ -544,11 +535,11 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() {
544 "…and the course that did fit is on it"535 "…and the course that did fit is on it"
545 );536 );
546 assert_eq!(537 assert_eq!(
547- rows(538+ sqlx::query_scalar::<_, i64>("SELECT count(*) FROM class_course WHERE class = $1")
548- &format!("SELECT VALUE id FROM class_course WHERE class = class_group:{class}"),539+ .bind(uuid::Uuid::parse_str(&class).expect("a uuid class id"))
549- &db540+ .fetch_one(&db)
550- )541+ .await
551- .await,542+ .unwrap(),
552 1543 1
553 );544 );
554 // The dangling id is pruned by the run that found it, here as anywhere.545 // 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() {
580 )571 )
581 .await;572 .await;
582 assert_eq!(made.status, StatusCode::CREATED);573 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);
584 575
585 // …and the edit is what has to reach the two classes standing there.576 // …and the edit is what has to reach the two classes standing there.
586 let patched = send(577 let patched = send(
@@ -605,37 +596,28 @@ async fn an_edit_retro_pumps_every_class_at_the_grade() {
605 // grade.596 // grade.
606 for class in [&a, &b] {597 for class in [&a, &b] {
607 assert_eq!(598 assert_eq!(
608- counter(599+ count_on("class_course_count", "class_group", class, &db)
609- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"),
610- &db
611- )
612 .await,600 .await,
613 1601 1
614 );602 );
615 }603 }
616 assert_eq!(604 assert_eq!(
617- counter(605+ count_on("class_course_count", "class_group", &ten, &db)
618- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{ten}"),
619- &db
620- )
621 .await,606 .await,
622 0607 0
623 );608 );
624 assert_eq!(609 assert_eq!(
625- counter(610+ count_on("enrollment_count", "course", &algebra, &db)
626- &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{algebra}"),
627- &db
628- )
629 .await,611 .await,
630 1,612 1,
631 "one student at the grade, one seat"613 "one student at the grade, one seat"
632 );614 );
633 assert_eq!(615 assert_eq!(
634- rows(616+ sqlx::query_scalar::<_, i64>("SELECT count(*) FROM enrollment WHERE app_user = $1")
635- &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali}"),617+ .bind(UserId::from_key(&ali))
636- &db618+ .fetch_one(&db)
637- )619+ .await
638- .await,620+ .unwrap(),
639 1621 1
640 );622 );
641 }623 }
@@ -687,23 +669,17 @@ async fn a_class_that_does_not_fit_is_reported_not_aborted() {
687 // Nothing moved on the skipped class: not its attachment counter, and not669 // Nothing moved on the skipped class: not its attachment counter, and not
688 // one of the seats the refused attach touched on its way to the refusal.670 // one of the seats the refused attach touched on its way to the refusal.
689 assert_eq!(671 assert_eq!(
690- counter(672+ count_on("class_course_count", "class_group", &full, &db)
691- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{full}"),
692- &db
693- )
694 .await,673 .await,
695 0674 0
696 );675 );
697 assert_eq!(676 assert_eq!(
698- counter(677+ count_on("enrollment_count", "course", &tight, &db)
699- &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{tight}"),
700- &db
701- )
702 .await,678 .await,
703 0,679 0,
704 "the empty class took no seat, and the refused one gave every seat back"680 "the empty class took no seat, and the refused one gave every seat back"
705 );681 );
706- assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 0);682+ assert_eq!(rows("SELECT count(*) FROM enrollment", &db).await, 0);
707 }683 }
708 684
709 /// One cause, one code, whichever door it came through: the `409` a manager's685 /// 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() {
848 "…and nothing else — a hand attach survives"824 "…and nothing else — a hand attach survives"
849 );825 );
850 assert_eq!(826 assert_eq!(
851- counter(827+ count_on("class_course_count", "class_group", &pumped, &db)
852- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{pumped}"),
853- &db
854- )
855 .await,828 .await,
856 0,829 0,
857 "the detach gives the class its count back"830 "the detach gives the class its count back"
858 );831 );
859 assert_eq!(832 assert_eq!(
860- counter(833+ count_on("class_course_count", "class_group", &byhand, &db)
861- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{byhand}"),
862- &db
863- )
864 .await,834 .await,
865 1835 1
866 );836 );
867 assert_eq!(837 assert_eq!(
868- rows(838+ sqlx::query_scalar::<_, i64>("SELECT count(*) FROM enrollment WHERE app_user = $1")
869- &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali}"),839+ .bind(UserId::from_key(&ali))
870- &db840+ .fetch_one(&db)
871- )841+ .await
872- .await,842+ .unwrap(),
873 0,843 0,
874 "the enrollments the blueprint pumped go with it"844 "the enrollments the blueprint pumped go with it"
875 );845 );
876 assert_eq!(846 assert_eq!(
877- counter(847+ count_on("enrollment_count", "course", &algebra, &db)
878- &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{algebra}"),
879- &db
880- )
881 .await,848 .await,
882 1,849 1,
883 "the hand-attached class keeps its student's seat"850 "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() {
907 )874 )
908 .await;875 .await;
909 assert_eq!(attached_by_hand.status, StatusCode::CREATED);876 assert_eq!(attached_by_hand.status, StatusCode::CREATED);
910- // Age the row to before the column existed. `UNSET`, not `= NONE`: an877+ // Age the row to before the column existed: a NULL `source` is what the
911- // absent key is what the store holds today, and it is what the rule reads.878+ // store holds for a hand attach, and it is what the rule reads.
912- db.query("UPDATE class_course UNSET source")879+ sqlx::query("UPDATE class_course SET source = NULL")
880+ .execute(&db)
913 .await881 .await
914- .unwrap()
915- .check()
916 .unwrap();882 .unwrap();
917 assert_eq!(source_of(&class, &algebra, &db).await, None);883 assert_eq!(source_of(&class, &algebra, &db).await, None);
918 884
@@ -961,10 +927,7 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() {
961 "a pre-migration row is hand-attached and unreachable by any blueprint sweep"927 "a pre-migration row is hand-attached and unreachable by any blueprint sweep"
962 );928 );
963 assert_eq!(929 assert_eq!(
964- counter(930+ count_on("enrollment_count", "course", &algebra, &db)
965- &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{algebra}"),
966- &db
967- )
968 .await,931 .await,
969 1932 1
970 );933 );
@@ -979,15 +942,14 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() {
979 /// `class_course` row tagged with a record nothing can reach, since the grade942 /// `class_course` row tagged with a record nothing can reach, since the grade
980 /// label *is* the id and no sweep will ever run for it again.943 /// label *is* the id and no sweep will ever run for it again.
981 ///944 ///
982-/// Racing two requests would be a coin flip the in-memory engine lies about, so945+/// Under Postgres the window itself is shut — `class_course.source` is a real
983-/// the delete is injected by the database itself: a `DEFINE EVENT` on946+/// foreign key, so a blueprint delete inside the attach's transaction takes the
984-/// `class_course` fires *inside* the pump's own transaction, the instant the947+/// attach down with it, and a crash between the delete and its sweep is one
985-/// link row lands — which is exactly "after the guard passed, before the948+/// transaction. What the store can no longer refuse is the residue an old
986-/// commit", every single time. This is a below-the-lock probe by construction949+/// volume can still carry, so the stranded row is forged the one way Postgres
987-/// (the store deletes the row, not `service::class_blueprint::delete`), so it does not950+/// allows (FK triggers suspended for the one transaction) and what is pinned is
988-/// test `BLUEPRINT_LOCK`; it pins the end state that lock prevents in-process,951+/// the recovery contract for it: a human detaches it one course at a time, and
989-/// and the recovery contract that covers the one residue it cannot — a process952+/// the counters come back exact.
990-/// crash between the delete and its sweep.
991 #[tokio::test]953 #[tokio::test]
992 async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() {954 async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() {
993 let (app, db) = app_and_db().await;955 let (app, db) = app_and_db().await;
@@ -1019,41 +981,46 @@ async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() {
1019 assert_eq!(moved.status, StatusCode::OK, "{:?}", moved.body);981 assert_eq!(moved.status, StatusCode::OK, "{:?}", moved.body);
1020 assert!(!attached(&class, &algebra, &db).await);982 assert!(!attached(&class, &algebra, &db).await);
1021 983
1022- // Delete the blueprint from inside the very write that attaches on its984+ // The stranded state: the link row committed, the blueprint it names did
1023- // behalf.985+ // not survive. Real FKs refuse that state, so it is written with FK
1024- db.query(986+ // triggers suspended — the manager id is real, the `source` FK is the one
1025- "DEFINE EVENT lose_blueprint ON TABLE class_course WHEN $event = 'CREATE' \987+ // the strand consists of.
1026- THEN { DELETE type::record('class_blueprint', '9'); };",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')",
1027 )1001 )
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)
1028 .await1007 .await
1029- .unwrap()
1030- .check()
1031 .unwrap();1008 .unwrap();
1032-1009+ sqlx::query("UPDATE class_group SET class_course_count = 1 WHERE id = $1")
1033- let pumped = send(1010+ .bind(uuid::Uuid::parse_str(&class).expect("a uuid class id"))
1034- &app,1011+ .execute(&mut *tx)
1035- "POST",1012+ .await
1036- &format!("/classes/{class}/blueprint"),1013+ .unwrap();
1037- Some(&manager),1014+ tx.commit().await.unwrap();
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- );
1048 1015
1049 assert_eq!(1016 assert_eq!(
1050- rows("SELECT VALUE id FROM class_blueprint", &db).await,1017+ rows("SELECT count(*) FROM class_blueprint", &db).await,
1051 0,1018 0,
1052 "the injected delete really landed"1019 "the injected delete really landed"
1053 );1020 );
1054 assert!(1021 assert!(
1055 attached(&class, &algebra, &db).await,1022 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 \
1057 row, tagged with a record no sweep can ever reach"1024 row, tagged with a record no sweep can ever reach"
1058 );1025 );
1059 assert_eq!(source_of(&class, &algebra, &db).await, Some("9".into()));1026 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() {
1076 );1043 );
1077 assert!(!attached(&class, &algebra, &db).await);1044 assert!(!attached(&class, &algebra, &db).await);
1078 assert_eq!(1045 assert_eq!(
1079- counter(1046+ count_on("class_course_count", "class_group", &class, &db)
1080- &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"),
1081- &db
1082- )
1083 .await,1047 .await,
1084 0,1048 0,
1085 "a stranded row still releases its counter when it is detached"1049 "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() {
1460 1424
1461 // The state a sweep that died half-way leaves: the list is stored without1425 // The state a sweep that died half-way leaves: the list is stored without
1462 // history, its attachment is not.1426 // history, its attachment is not.
1463- db.query(1427+ sqlx::query("UPDATE class_blueprint SET courses = $1 WHERE grade = '9'")
1464- "UPDATE type::record('class_blueprint', '9') SET courses = [type::record('course', $c)]",1428+ .bind(vec![CourseId::from_key(&algebra)])
1465- )1429+ .execute(&db)
1466- .bind(("c", algebra.clone()))1430+ .await
1467- .await1431+ .unwrap();
1468- .unwrap()
1469- .check()
1470- .unwrap();
1471 1432
1472 let courses = held(&app, &manager, "9").await;1433 let courses = held(&app, &manager, "9").await;
1473 assert_eq!(1434 assert_eq!(
@@ -1490,19 +1451,19 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() {
1490 "re-sending the stored list must finish the removal it stored"1451 "re-sending the stored list must finish the removal it stored"
1491 );1452 );
1492 assert_eq!(1453 assert_eq!(
1493- rows(1454+ sqlx::query_scalar::<_, i64>(
1494- &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali} AND course = course:{history}"),1455+ "SELECT count(*) FROM enrollment WHERE app_user = $1 AND course = $2",
1495- &db
1496 )1456 )
1497- .await,1457+ .bind(UserId::from_key(&ali))
1458+ .bind(CourseId::from_key(&history))
1459+ .fetch_one(&db)
1460+ .await
1461+ .unwrap(),
1498 0,1462 0,
1499 "…enrollments and all"1463 "…enrollments and all"
1500 );1464 );
1501 assert_eq!(1465 assert_eq!(
1502- counter(1466+ count_on("enrollment_count", "course", &history, &db)
1503- &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{history}"),
1504- &db
1505- )
1506 .await,1467 .await,
1507 0,1468 0,
1508 "…with the seat given back"1469 "…with the seat given back"
@@ -1512,11 +1473,14 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() {
1512 "and the course the template still holds is untouched"1473 "and the course the template still holds is untouched"
1513 );1474 );
1514 assert_eq!(1475 assert_eq!(
1515- rows(1476+ sqlx::query_scalar::<_, i64>(
1516- &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali} AND course = course:{algebra}"),1477+ "SELECT count(*) FROM enrollment WHERE app_user = $1 AND course = $2",
1517- &db
1518 )1478 )
1519- .await,1479+ .bind(UserId::from_key(&ali))
1480+ .bind(CourseId::from_key(&algebra))
1481+ .fetch_one(&db)
1482+ .await
1483+ .unwrap(),
1520 11484 1
1521 );1485 );
1522 }1486 }
@@ -1538,14 +1502,17 @@ async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() {
1538 let history = create_course(&app, &manager, "history").await;1502 let history = create_course(&app, &manager, "history").await;
1539 let class = create_class(&app, &manager, "9-A", "9").await;1503 let class = create_class(&app, &manager, "9-A", "9").await;
1540 1504
1541- db.query(format!(1505+ let mut conn = db.acquire().await.expect("acquire for the trigger");
1542- "DEFINE EVENT kill_on_create ON TABLE class_blueprint WHEN $event = 'CREATE' \1506+ sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
1543- THEN {{ DELETE type::record('course', '{algebra}'); }};"1507+ "CREATE FUNCTION heztest_kill_on_create() RETURNS trigger AS $$
1544- ))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)
1545 .await1514 .await
1546- .unwrap()1515+ .expect("define the kill-on-create trigger");
1547- .check()
1548- .unwrap();
1549 let made = send(1516 let made = send(
1550 &app,1517 &app,
1551 "POST",1518 "POST",
@@ -1571,14 +1538,16 @@ async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() {
1571 );1538 );
1572 1539
1573 // The same window on the edit route.1540 // The same window on the edit route.
1574- db.query(format!(1541+ sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
1575- "DEFINE EVENT kill_on_update ON TABLE class_blueprint WHEN $event = 'UPDATE' \1542+ "CREATE FUNCTION heztest_kill_on_update() RETURNS trigger AS $$
1576- THEN {{ DELETE type::record('course', '{history}'); }};"1543+ BEGIN DELETE FROM course WHERE id = '{history}'; RETURN NULL; END;
1577- ))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)
1578 .await1549 .await
1579- .unwrap()1550+ .expect("define the kill-on-update trigger");
1580- .check()
1581- .unwrap();
1582 let patched = send(1551 let patched = send(
1583 &app,1552 &app,
1584 "PATCH",1553 "PATCH",
@@ -1624,7 +1593,7 @@ async fn a_template_write_refuses_a_course_that_is_gone() {
1624 let manager = login_as(&app, &db, "mgr", "manager").await;1593 let manager = login_as(&app, &db, "mgr", "manager").await;
1625 let by = UserId::from_key(&me_id(&app, &manager).await);1594 let by = UserId::from_key(&me_id(&app, &manager).await);
1626 let algebra = CourseId::from_key(&create_course(&app, &manager, "algebra").await);1595 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);
1628 1597
1629 let refused = class_blueprint::create(1598 let refused = class_blueprint::create(
1630 &db,1599 &db,
@@ -1638,7 +1607,7 @@ async fn a_template_write_refuses_a_course_that_is_gone() {
1638 "a course that is gone is a 400, not a template naming it: {refused:?}"1607 "a course that is gone is a 400, not a template naming it: {refused:?}"
1639 );1608 );
1640 assert_eq!(1609 assert_eq!(
1641- rows("SELECT VALUE id FROM class_blueprint", &db).await,1610+ rows("SELECT count(*) FROM class_blueprint", &db).await,
1642 0,1611 0,
1643 "…and nothing may be stored"1612 "…and nothing may be stored"
1644 );1613 );
tests/regress_classes.rsmodified+200 -156
@@ -6,7 +6,7 @@
6 mod common;6 mod common;
7 7
8 use axum::http::StatusCode;8 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};
10 use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};10 use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
11 use hezarfen_backend::database::Database;11 use hezarfen_backend::database::Database;
12 use hezarfen_backend::domain::class_group::ClassName;12 use hezarfen_backend::domain::class_group::ClassName;
@@ -15,25 +15,62 @@ use hezarfen_backend::domain::user::UserId;
15 use hezarfen_backend::error::AppError;15 use hezarfen_backend::error::AppError;
16 use hezarfen_backend::service::{class_course, class_group, class_member};16 use hezarfen_backend::service::{class_course, class_group, class_member};
17 use serde_json::json;17 use serde_json::json;
18+use sqlx::Row as _;
18 19
19-/// One counter, re-read out of the store — never off a response body.20+/// One counter, re-read out of the store — never off a response body. `sql`
20-async fn counter(sql: &str, db: &Database) -> i64 {21+/// is a whole scalar query; each call spells the aggregate it asserts on.
21- let mut result = db.query(sql).await.unwrap().check().unwrap();22+async fn counter(sql: &'static str, db: &Database) -> i64 {
22- result23+ sqlx::query_scalar(sql).fetch_one(db).await.unwrap()
23- .take::<Vec<i64>>(0)24+}
24- .unwrap()25+
25- .first()26+/// How many rows `sql` counts.
26- .copied()27+async fn rows(sql: &'static str, db: &Database) -> i64 {
27- .unwrap_or(0)28+ counter(sql, db).await
28 }29 }
29 30
30-/// How many rows `sql` selects ids for.31+/// A real `app_user` row for the fixture actor or member a domain call must
31-async fn rows(sql: &str, db: &Database) -> i64 {32+/// name: the actor and member columns are foreign keys now, so they are rows,
32- let mut result = db.query(sql).await.unwrap().check().unwrap();33+/// not fabricated ids. The username is unique, so every call for the same name
33- result34+/// shares one row, whichever call minted it. These rows never log in, so the
34- .take::<Vec<surrealdb::types::RecordId>>(0)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
35 .unwrap()50 .unwrap()
36- .len() as i6451+ .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();
37 }74 }
38 75
39 /// Delete a course row the way a *concurrent* `DELETE /courses/{id}` racing an76 /// 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 {
42 /// the state from a test — and the state the pump's in-transaction claim exists79 /// the state from a test — and the state the pump's in-transaction claim exists
43 /// to make unreachable in the first place.80 /// to make unreachable in the first place.
44 async fn wipe_course_row(course: &str, db: &Database) {81 async fn wipe_course_row(course: &str, db: &Database) {
45- db.query("DELETE type::record('course', $key)")82+ wipe_row(
46- .bind(("key", course.to_string()))83+ "course",
47- .await84+ uuid::Uuid::parse_str(course).expect("a uuid course id"),
48- .unwrap()85+ db,
49- .check()86+ )
50- .unwrap();87+ .await;
51 }88 }
52 89
53 /// B1(a). A class with *zero* members makes the pump's pair loop empty, so the90 /// 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) {
57 #[tokio::test]94 #[tokio::test]
58 async fn an_attach_onto_a_deleted_course_writes_no_link() {95 async fn an_attach_onto_a_deleted_course_writes_no_link() {
59 let (_app, db) = app_and_db().await;96 let (_app, db) = app_and_db().await;
60- let manager = UserId::from_key("manager");97+ let manager = fixture_user(&db, "manager").await;
61 let class = class_group::create(98 let class = class_group::create(
62 &db,99 &db,
63 &manager,100 &manager,
@@ -70,7 +107,7 @@ async fn an_attach_onto_a_deleted_course_writes_no_link() {
70 .unwrap();107 .unwrap();
71 // A course id nothing ever created: the same row a delete that won the race108 // A course id nothing ever created: the same row a delete that won the race
72 // leaves behind.109 // leaves behind.
73- let ghost = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");110+ let ghost = CourseId::from_key(GHOST_ID);
74 111
75 let refused = class_course::attach(&db, class.get_id(), &ghost, &manager).await;112 let refused = class_course::attach(&db, class.get_id(), &ghost, &manager).await;
76 assert!(113 assert!(
@@ -78,12 +115,12 @@ async fn an_attach_onto_a_deleted_course_writes_no_link() {
78 "attaching a course that is gone must be refused: {refused:?}"115 "attaching a course that is gone must be refused: {refused:?}"
79 );116 );
80 assert_eq!(117 assert_eq!(
81- rows("SELECT VALUE id FROM class_course", &db).await,118+ rows("SELECT count(*) FROM class_course", &db).await,
82 0,119 0,
83 "no link row may point at a course that does not exist"120 "no link row may point at a course that does not exist"
84 );121 );
85 assert_eq!(122 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,
87 0,124 0,
88 "…and the class must not count one either, or it is undeletable forever"125 "…and the class must not count one either, or it is undeletable forever"
89 );126 );
@@ -222,7 +259,7 @@ async fn a_member_add_names_a_stale_link_rather_than_calling_it_full() {
222 refused.body259 refused.body
223 );260 );
224 assert_eq!(261 assert_eq!(
225- rows("SELECT VALUE id FROM class_member", &db).await,262+ rows("SELECT count(*) FROM class_member", &db).await,
226 0,263 0,
227 "a refused add writes nothing"264 "a refused add writes nothing"
228 );265 );
@@ -294,7 +331,7 @@ async fn a_hand_enroll_takes_the_row_off_the_class() {
294 "a hand enroll must take the row off the class"331 "a hand enroll must take the row off the class"
295 );332 );
296 assert_eq!(333 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,
298 0,335 0,
299 "…in the stored row, not just the response"336 "…in the stored row, not just the response"
300 );337 );
@@ -311,12 +348,12 @@ async fn a_hand_enroll_takes_the_row_off_the_class() {
311 .await;348 .await;
312 assert_eq!(removed.status, StatusCode::NO_CONTENT);349 assert_eq!(removed.status, StatusCode::NO_CONTENT);
313 assert_eq!(350 assert_eq!(
314- rows("SELECT VALUE id FROM enrollment", &db).await,351+ rows("SELECT count(*) FROM enrollment", &db).await,
315 1,352 1,
316 "the class may not unenroll a student an operator enrolled by hand"353 "the class may not unenroll a student an operator enrolled by hand"
317 );354 );
318 assert_eq!(355 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,
320 1,357 1,
321 "…and the seat it never paid for may not be released"358 "…and the seat it never paid for may not be released"
322 );359 );
@@ -362,7 +399,7 @@ async fn a_role_change_sweeps_memberships_and_enrollments_together() {
362 Some(json!({ "user_id": student_id })),399 Some(json!({ "user_id": student_id })),
363 )400 )
364 .await;401 .await;
365- assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 1);402+ assert_eq!(rows("SELECT count(*) FROM enrollment", &db).await, 1);
366 403
367 let promoted = send(404 let promoted = send(
368 &app,405 &app,
@@ -374,19 +411,19 @@ async fn a_role_change_sweeps_memberships_and_enrollments_together() {
374 .await;411 .await;
375 assert_eq!(promoted.status, StatusCode::OK);412 assert_eq!(promoted.status, StatusCode::OK);
376 413
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);
378 assert_eq!(415 assert_eq!(
379- rows("SELECT VALUE id FROM enrollment", &db).await,416+ rows("SELECT count(*) FROM enrollment", &db).await,
380 0,417 0,
381 "a non-student holds no roster row, whoever wrote it"418 "a non-student holds no roster row, whoever wrote it"
382 );419 );
383 assert_eq!(420 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,
385 0,422 0,
386 "the seat comes back exactly once"423 "the seat comes back exactly once"
387 );424 );
388 assert_eq!(425 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,
390 0427 0
391 );428 );
392 // Nothing is left tagged with the class, so letting it go strands nothing.429 // 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() {
463 // off the (full) counter, and costs no seat.500 // off the (full) counter, and costs no seat.
464 assert_eq!(enroll(first_id.clone()).await.status, StatusCode::OK);501 assert_eq!(enroll(first_id.clone()).await.status, StatusCode::OK);
465 assert_eq!(502 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,
467 1504 1
468 );505 );
469 506
@@ -480,7 +517,7 @@ async fn the_roster_cap_is_claimed_off_the_live_capacity_column() {
480 assert_eq!(raised.status, StatusCode::OK);517 assert_eq!(raised.status, StatusCode::OK);
481 assert_eq!(enroll(second_id.clone()).await.status, StatusCode::OK);518 assert_eq!(enroll(second_id.clone()).await.status, StatusCode::OK);
482 assert_eq!(519 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,
484 2521 2
485 );522 );
486 523
@@ -488,10 +525,9 @@ async fn the_roster_cap_is_claimed_off_the_live_capacity_column() {
488 // conditional write matches nothing either way, and only that path pays for525 // conditional write matches nothing either way, and only that path pays for
489 // the read that tells them apart.526 // the read that tells them apart.
490 wipe_course_row(&course, &db).await;527 wipe_course_row(&course, &db).await;
491- db.query("DELETE enrollment")528+ sqlx::query("DELETE FROM enrollment")
529+ .execute(&db)
492 .await530 .await
493- .unwrap()
494- .check()
495 .unwrap();531 .unwrap();
496 assert_eq!(enroll(first_id).await.status, StatusCode::NOT_FOUND);532 assert_eq!(enroll(first_id).await.status, StatusCode::NOT_FOUND);
497 }533 }
@@ -504,7 +540,7 @@ async fn the_roster_cap_is_claimed_off_the_live_capacity_column() {
504 #[tokio::test]540 #[tokio::test]
505 async fn a_roster_is_ordered_by_when_a_student_was_added() {541 async fn a_roster_is_ordered_by_when_a_student_was_added() {
506 let (_app, db) = app_and_db().await;542 let (_app, db) = app_and_db().await;
507- let manager = UserId::from_key("manager");543+ let manager = fixture_user(&db, "manager").await;
508 let class = class_group::create(544 let class = class_group::create(
509 &db,545 &db,
510 &manager,546 &manager,
@@ -518,25 +554,27 @@ async fn a_roster_is_ordered_by_when_a_student_was_added() {
518 .get_id()554 .get_id()
519 .clone();555 .clone();
520 556
521- // Keys chosen so `id DESC` (c, b, a) is not the reverse of the insertion557+ // Members added in an order no id ordering reproduces: only a real stamp
522- // order (a, c, b): only a real stamp can tell the two apart. The waits are558+ // can tell the two apart. The waits are what keep the stamps distinct —
523- // what keep the millisecond stamps distinct — a tie falls back to the id,559+ // a tie falls back to the id, which is the very order under test. The
524- // which is the very order under test.560+ // minted rows carry uuid ids, so the assertions read back through the
525- let added = ["a", "c", "b"];561+ // name -> id map.
526- for key in added {562+ let mut names: Vec<(&str, UserId)> = Vec::new();
527- class_member::add(&db, &class, &UserId::from_key(key), &manager)563+ for key in ["a", "c", "b"] {
564+ let member = fixture_user(&db, key).await;
565+ class_member::add(&db, &class, &member, &manager)
528 .await566 .await
529 .unwrap();567 .unwrap();
568+ names.push((key, member));
530 tokio::time::sleep(std::time::Duration::from_millis(2)).await;569 tokio::time::sleep(std::time::Duration::from_millis(2)).await;
531 }570 }
571+ let name_of =
572+ |id: &UserId| names.iter().find(|(_, mid)| mid == id).map(|(k, _)| *k).unwrap();
532 573
533 let (roster, _) = class_member::list_for_class(&db, &class, None, 0)574 let (roster, _) = class_member::list_for_class(&db, &class, None, 0)
534 .await575 .await
535 .unwrap();576 .unwrap();
536- let order: Vec<&str> = roster577+ let order: Vec<&str> = roster.iter().map(|member| name_of(member.get_user())).collect();
537- .iter()
538- .map(|member| member.get_user().key())
539- .collect();
540 assert_eq!(578 assert_eq!(
541 order,579 order,
542 vec!["b", "c", "a"],580 vec!["b", "c", "a"],
@@ -547,19 +585,20 @@ async fn a_roster_is_ordered_by_when_a_student_was_added() {
547 // all — the state a real volume is in. It is of unknown age, and NONE585 // all — the state a real volume is in. It is of unknown age, and NONE
548 // sorting last under DESC is what makes that the oldest, rather than an586 // sorting last under DESC is what makes that the oldest, rather than an
549 // invented number putting it anywhere else.587 // invented number putting it anywhere else.
550- db.query("UPDATE class_member SET added_at = NONE WHERE user = $usr")588+ sqlx::query(
551- .bind(("usr", UserId::from_key("c").record()))589+ "UPDATE class_member SET added_at = NULL
552- .await590+ WHERE app_user = (SELECT id FROM app_user WHERE username = 'c')",
553- .unwrap()591+ )
554- .check()592+ .execute(&db)
555- .unwrap();593+ .await
594+ .unwrap();
556 let (roster, _) = class_member::list_for_class(&db, &class, None, 0)595 let (roster, _) = class_member::list_for_class(&db, &class, None, 0)
557 .await596 .await
558 .unwrap();597 .unwrap();
559 assert_eq!(598 assert_eq!(
560 roster599 roster
561 .iter()600 .iter()
562- .map(|member| member.get_user().key())601+ .map(|member| name_of(member.get_user()))
563 .collect::<Vec<_>>(),602 .collect::<Vec<_>>(),
564 vec!["b", "a", "c"],603 vec!["b", "a", "c"],
565 "a stamp-less row must sort oldest, not first"604 "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() {
586 .get_id()625 .get_id()
587 .clone();626 .clone();
588 627
589- // Courses are ULID-keyed, so their ids rise with creation; attaching them628+ // Course ids rise with creation (monotonic mint); attaching them
590 // back-to-front makes id order and attach order disagree.629 // back-to-front makes id order and attach order disagree.
591 let mut courses = Vec::new();630 let mut courses = Vec::new();
592 for title in ["first", "second", "third"] {631 for title in ["first", "second", "third"] {
@@ -604,7 +643,7 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() {
604 let (attached, _) = class_course::list_for_class(&db, &class, None, 0)643 let (attached, _) = class_course::list_for_class(&db, &class, None, 0)
605 .await644 .await
606 .unwrap();645 .unwrap();
607- let order: Vec<&str> = attached646+ let order: Vec<String> = attached
608 .iter()647 .iter()
609 .map(|link| link.get_course().key())648 .map(|link| link.get_course().key())
610 .collect();649 .collect();
@@ -626,7 +665,7 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() {
626 #[tokio::test]665 #[tokio::test]
627 async fn a_class_refuses_the_member_past_its_ceiling() {666 async fn a_class_refuses_the_member_past_its_ceiling() {
628 let (_app, db) = app_and_db().await;667 let (_app, db) = app_and_db().await;
629- let manager = UserId::from_key("manager");668+ let manager = fixture_user(&db, "manager").await;
630 let class = class_group::create(669 let class = class_group::create(
631 &db,670 &db,
632 &manager,671 &manager,
@@ -639,18 +678,19 @@ async fn a_class_refuses_the_member_past_its_ceiling() {
639 .unwrap()678 .unwrap()
640 .get_id()679 .get_id()
641 .clone();680 .clone();
642- db.query("UPDATE $class SET class_member_count = $at")681+ sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2")
643- .bind(("class", class.record()))682+ .bind(MAX_CLASS_MEMBERS - 1)
644- .bind(("at", MAX_CLASS_MEMBERS - 1))683+ .bind(class.clone())
684+ .execute(&db)
645 .await685 .await
646- .unwrap()
647- .check()
648 .unwrap();686 .unwrap();
649 687
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)
651 .await690 .await
652 .expect("the place under the ceiling is still free");691 .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;
654 assert!(694 assert!(
655 matches!(refused, Err(AppError::ConflictCoded { code, ref message })695 matches!(refused, Err(AppError::ConflictCoded { code, ref message })
656 if code == "class_at_roster_ceiling"696 if code == "class_at_roster_ceiling"
@@ -659,22 +699,18 @@ async fn a_class_refuses_the_member_past_its_ceiling() {
659 must name the ceiling the prose does — the roster, not the course list: {refused:?}"699 must name the ceiling the prose does — the roster, not the course list: {refused:?}"
660 );700 );
661 assert_eq!(701 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,
663 MAX_CLASS_MEMBERS,703 MAX_CLASS_MEMBERS,
664 "a refused add may not tick the counter past the cap"704 "a refused add may not tick the counter past the cap"
665 );705 );
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);
667 707
668 // And the refusal a *deleted* class earns must stay a 404: both come out of708 // And the refusal a *deleted* class earns must stay a 404: both come out of
669 // the same counter claim matching nothing, and only one of them is a709 // the same counter claim matching nothing, and only one of them is a
670 // ceiling anybody can make room under.710 // ceiling anybody can make room under.
671- db.query("DELETE $class")711+ wipe_row("class_group", class.uuid(), &db).await;
672- .bind(("class", class.record()))712+ let ghost = fixture_user(&db, "ghost").await;
673- .await713+ let gone = class_member::add(&db, &class, &ghost, &manager).await;
674- .unwrap()
675- .check()
676- .unwrap();
677- let gone = class_member::add(&db, &class, &UserId::from_key("ghost"), &manager).await;
678 assert!(714 assert!(
679 matches!(gone, Err(AppError::NotFound)),715 matches!(gone, Err(AppError::NotFound)),
680 "a class that is gone is a 404: {gone:?}"716 "a class that is gone is a 404: {gone:?}"
@@ -709,12 +745,11 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() {
709 .get_id()745 .get_id()
710 .clone();746 .clone();
711 let algebra = CourseId::from_key(&create_course(&app, &cookie, "algebra").await);747 let algebra = CourseId::from_key(&create_course(&app, &cookie, "algebra").await);
712- db.query("UPDATE $class SET class_member_count = $over")748+ sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2")
713- .bind(("class", class.record()))749+ .bind(MAX_CLASS_MEMBERS + 1)
714- .bind(("over", MAX_CLASS_MEMBERS + 1))750+ .bind(class.clone())
751+ .execute(&db)
715 .await752 .await
716- .unwrap()
717- .check()
718 .unwrap();753 .unwrap();
719 754
720 let refused = class_course::attach(&db, &class, &algebra, &manager).await;755 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() {
725 "the refusal must name the axis that is over, not the one with room: {refused:?}"760 "the refusal must name the axis that is over, not the one with room: {refused:?}"
726 );761 );
727 assert_eq!(762 assert_eq!(
728- rows("SELECT VALUE id FROM class_course", &db).await,763+ rows("SELECT count(*) FROM class_course", &db).await,
729 0,764 0,
730 "a refused attach may not leave the link behind"765 "a refused attach may not leave the link behind"
731 );766 );
732 assert_eq!(767 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,
734 0,769 0,
735 "…nor tick the axis it was refused on"770 "…nor tick the axis it was refused on"
736 );771 );
737 772
738 // Back under the ceiling, the very same attach goes through: the refusal is773 // Back under the ceiling, the very same attach goes through: the refusal is
739 // the standing count, not the class.774 // the standing count, not the class.
740- db.query("UPDATE $class SET class_member_count = $at")775+ sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2")
741- .bind(("class", class.record()))776+ .bind(MAX_CLASS_MEMBERS)
742- .bind(("at", MAX_CLASS_MEMBERS))777+ .bind(class.clone())
778+ .execute(&db)
743 .await779 .await
744- .unwrap()
745- .check()
746 .unwrap();780 .unwrap();
747 class_course::attach(&db, &class, &algebra, &manager)781 class_course::attach(&db, &class, &algebra, &manager)
748 .await782 .await
@@ -754,7 +788,7 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() {
754 #[tokio::test]788 #[tokio::test]
755 async fn a_class_over_the_course_ceiling_takes_no_member() {789 async fn a_class_over_the_course_ceiling_takes_no_member() {
756 let (_app, db) = app_and_db().await;790 let (_app, db) = app_and_db().await;
757- let manager = UserId::from_key("manager");791+ let manager = fixture_user(&db, "manager").await;
758 let class = class_group::create(792 let class = class_group::create(
759 &db,793 &db,
760 &manager,794 &manager,
@@ -767,15 +801,15 @@ async fn a_class_over_the_course_ceiling_takes_no_member() {
767 .unwrap()801 .unwrap()
768 .get_id()802 .get_id()
769 .clone();803 .clone();
770- db.query("UPDATE $class SET class_course_count = $over")804+ sqlx::query("UPDATE class_group SET class_course_count = $1 WHERE id = $2")
771- .bind(("class", class.record()))805+ .bind(MAX_CLASS_COURSES + 1)
772- .bind(("over", MAX_CLASS_COURSES + 1))806+ .bind(class.clone())
807+ .execute(&db)
773 .await808 .await
774- .unwrap()
775- .check()
776 .unwrap();809 .unwrap();
777 810
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;
779 assert!(813 assert!(
780 matches!(refused, Err(AppError::ConflictCoded { code, ref message })814 matches!(refused, Err(AppError::ConflictCoded { code, ref message })
781 if code == "class_course_list_too_large"815 if code == "class_course_list_too_large"
@@ -783,9 +817,9 @@ async fn a_class_over_the_course_ceiling_takes_no_member() {
783 "the refusal must name the courses, not the roster — in its code as well as \817 "the refusal must name the courses, not the roster — in its code as well as \
784 its prose: {refused:?}"818 its prose: {refused:?}"
785 );819 );
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);
787 assert_eq!(821 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,
789 0823 0
790 );824 );
791 }825 }
@@ -908,7 +942,7 @@ async fn a_student_or_a_ghost_cannot_be_the_homeroom_teacher() {
908 let manager = login_as(&app, &db, "manager", "manager").await;942 let manager = login_as(&app, &db, "manager", "manager").await;
909 let student = login_as(&app, &db, "ali", "student").await;943 let student = login_as(&app, &db, "ali", "student").await;
910 let student_id = me_id(&app, &student).await;944 let student_id = me_id(&app, &student).await;
911- let ghost = "01J8XZ0K3Q8G7X2M4N5P6R7S8T";945+ let ghost = GHOST_ID;
912 946
913 for bad in [student_id.as_str(), ghost] {947 for bad in [student_id.as_str(), ghost] {
914 let refused = send(948 let refused = send(
@@ -922,7 +956,7 @@ async fn a_student_or_a_ghost_cannot_be_the_homeroom_teacher() {
922 assert_eq!(refused.status, StatusCode::BAD_REQUEST, "create with {bad}");956 assert_eq!(refused.status, StatusCode::BAD_REQUEST, "create with {bad}");
923 }957 }
924 assert_eq!(958 assert_eq!(
925- rows("SELECT VALUE id FROM class_group", &db).await,959+ rows("SELECT count(*) FROM class_group", &db).await,
926 0,960 0,
927 "a refused create may write no class"961 "a refused create may write no class"
928 );962 );
@@ -1249,7 +1283,7 @@ async fn only_staff_and_a_linked_parent_read_another_users_classes() {
1249 let ghost = send(1283 let ghost = send(
1250 &app,1284 &app,
1251 "GET",1285 "GET",
1252- "/classes/user/01J8XZ0K3Q8G7X2M4N5P6R7S8T",1286+ &format!("/classes/user/{ABSENT_ID}"),
1253 Some(&teacher),1287 Some(&teacher),
1254 None,1288 None,
1255 )1289 )
@@ -1292,12 +1326,12 @@ async fn a_membership_whose_class_is_gone_is_counted_but_skipped() {
1292 }1326 }
1293 // The guard would refuse this, so it is spelled as the raw row loss it1327 // The guard would refuse this, so it is spelled as the raw row loss it
1294 // stands in for; the membership row is deliberately left behind.1328 // stands in for; the membership row is deliberately left behind.
1295- db.query("DELETE type::record('class_group', $key)")1329+ wipe_row(
1296- .bind(("key", classes[0].clone()))1330+ "class_group",
1297- .await1331+ uuid::Uuid::parse_str(&classes[0]).expect("a uuid class id"),
1298- .unwrap()1332+ &db,
1299- .check()1333+ )
1300- .unwrap();1334+ .await;
1301 1335
1302 let res = send(&app, "GET", "/classes/me", Some(&student), None).await;1336 let res = send(&app, "GET", "/classes/me", Some(&student), None).await;
1303 assert_eq!(1337 assert_eq!(
@@ -1339,28 +1373,38 @@ async fn a_membership_whose_class_is_gone_is_counted_but_skipped() {
1339 // single time. Nothing in `src/` knows about it — the seam is the schema, and1373 // single time. Nothing in `src/` knows about it — the seam is the schema, and
1340 // these tests are what stop the three `undo_if_demoted` calls being deleted.1374 // these tests are what stop the three `undo_if_demoted` calls being deleted.
1341 1375
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.
1343 async fn demote_during_writes_to(table: &str, event: &str, user: &str, db: &Database) {1379 async fn demote_during_writes_to(table: &str, event: &str, user: &str, db: &Database) {
1344- db.query(format!(1380+ let firing = match event {
1345- "DEFINE EVENT demote_mid_write ON TABLE {table} WHEN $event = '{event}' THEN {{ \1381+ "CREATE" => "INSERT",
1346- UPDATE type::record('user', '{user}') SET role = 'student'; }};"1382+ "UPDATE" => "UPDATE",
1347- ))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)
1348 .await1397 .await
1349- .unwrap()1398+ .expect("define the demote trigger");
1350- .check()
1351- .unwrap();
1352 }1399 }
1353 1400
1354 /// The homeroom teacher's live role, straight out of the store.1401 /// The homeroom teacher's live role, straight out of the store.
1355 async fn role_of(user: &str, db: &Database) -> String {1402 async fn role_of(user: &str, db: &Database) -> String {
1356- let mut result = db1403+ sqlx::query_scalar("SELECT role FROM app_user WHERE id = $1")
1357- .query("SELECT VALUE role FROM user WHERE id = type::record('user', $k)")1404+ .bind(UserId::from_key(user))
1358- .bind(("k", user.to_string()))1405+ .fetch_one(db)
1359 .await1406 .await
1360 .unwrap()1407 .unwrap()
1361- .check()
1362- .unwrap();
1363- result.take::<Vec<String>>(0).unwrap().pop().unwrap()
1364 }1408 }
1365 1409
1366 /// `POST /classes` naming a teacher who is demoted while the row is being1410 /// `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() {
1407 );1451 );
1408 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");1452 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");
1409 assert_eq!(1453 assert_eq!(
1410- rows("SELECT VALUE id FROM class_group", &db).await,1454+ rows("SELECT count(*) FROM class_group", &db).await,
1411 0,1455 0,
1412 "the 409 promises nothing was created — so nothing may be there"1456 "the 409 promises nothing was created — so nothing may be there"
1413 );1457 );
1414 assert_eq!(1458 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,
1416 0,1460 0,
1417 "…and least of all a reference stranded on the term"1461 "…and least of all a reference stranded on the term"
1418 );1462 );
@@ -1471,12 +1515,12 @@ async fn a_rolled_back_create_at_a_blueprinted_grade_leaves_nothing_behind() {
1471 res.body1515 res.body
1472 );1516 );
1473 assert_eq!(1517 assert_eq!(
1474- rows("SELECT VALUE id FROM class_group", &db).await,1518+ rows("SELECT count(*) FROM class_group", &db).await,
1475 0,1519 0,
1476 "the rollback must still have been able to delete the class"1520 "the rollback must still have been able to delete the class"
1477 );1521 );
1478 assert_eq!(1522 assert_eq!(
1479- rows("SELECT VALUE id FROM class_course", &db).await,1523+ rows("SELECT count(*) FROM class_course", &db).await,
1480 0,1524 0,
1481 "…which it only can because nothing was stocked onto it first"1525 "…which it only can because nothing was stocked onto it first"
1482 );1526 );
@@ -1516,8 +1560,8 @@ async fn a_patch_whose_teacher_is_demoted_mid_write_undoes_the_column() {
1516 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");1560 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");
1517 assert_eq!(1561 assert_eq!(
1518 counter(1562 counter(
1519- "SELECT VALUE (IF teacher = NONE { 0 } ELSE { 1 }) FROM class_group",1563+ "SELECT count(*) FROM class_group WHERE teacher IS NOT NULL",
1520- &db1564+ &db,
1521 )1565 )
1522 .await,1566 .await,
1523 0,1567 0,
@@ -1566,7 +1610,7 @@ async fn a_course_assignment_whose_teacher_is_demoted_mid_write_is_undone() {
1566 );1610 );
1567 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");1611 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");
1568 assert_eq!(1612 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,
1570 0,1614 0,
1571 "the assignment must be dropped again, not left granting nothing"1615 "the assignment must be dropped again, not left granting nothing"
1572 );1616 );
@@ -1589,15 +1633,21 @@ async fn a_rollback_the_guard_refuses_is_a_500_not_a_lying_409() {
1589 let teacher = login_as(&app, &db, "teacher", "teacher").await;1633 let teacher = login_as(&app, &db, "teacher", "teacher").await;
1590 let teacher_id = me_id(&app, &teacher).await;1634 let teacher_id = me_id(&app, &teacher).await;
1591 1635
1592- db.query(format!(1636+ let mut conn = db.acquire().await.expect("acquire for the trigger");
1593- "DEFINE EVENT demote_and_occupy ON TABLE class_group WHEN $event = 'CREATE' THEN {{ \1637+ sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
1594- UPDATE type::record('user', '{teacher_id}') SET role = 'student'; \1638+ "CREATE FUNCTION heztest_demote_and_occupy() RETURNS trigger AS $$
1595- UPDATE $after.id SET class_member_count = 1; }};"1639+ BEGIN
1596- ))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)
1597 .await1649 .await
1598- .unwrap()1650+ .expect("define the demote-and-occupy trigger");
1599- .check()
1600- .unwrap();
1601 1651
1602 let res = send(1652 let res = send(
1603 &app,1653 &app,
@@ -1615,14 +1665,14 @@ async fn a_rollback_the_guard_refuses_is_a_500_not_a_lying_409() {
1615 res.body1665 res.body
1616 );1666 );
1617 assert_eq!(1667 assert_eq!(
1618- rows("SELECT VALUE id FROM class_group", &db).await,1668+ rows("SELECT count(*) FROM class_group", &db).await,
1619 1,1669 1,
1620 "the class really is still there — which is why the 409 would have lied"1670 "the class really is still there — which is why the 409 would have lied"
1621 );1671 );
1622 assert_eq!(1672 assert_eq!(
1623 counter(1673 counter(
1624- "SELECT VALUE (IF teacher = NONE { 0 } ELSE { 1 }) FROM class_group",1674+ "SELECT count(*) FROM class_group WHERE teacher IS NOT NULL",
1625- &db1675+ &db,
1626 )1676 )
1627 .await,1677 .await,
1628 0,1678 0,
@@ -1759,7 +1809,7 @@ async fn a_detach_never_hands_a_row_to_a_class_that_is_gone() {
1759 let (app, db) = app_and_db().await;1809 let (app, db) = app_and_db().await;
1760 let staff = login_as(&app, &db, "manager", "manager").await;1810 let staff = login_as(&app, &db, "manager", "manager").await;
1761 let manager = UserId::from_key(&me_id(&app, &staff).await);1811 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;
1763 let algebra = CourseId::from_key(&create_course(&app, &staff, "algebra").await);1813 let algebra = CourseId::from_key(&create_course(&app, &staff, "algebra").await);
1764 let mut made = Vec::new();1814 let mut made = Vec::new();
1765 for name in ["9-B", "9-A"] {1815 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() {
1784 }1834 }
1785 let (owner, heir) = (made[0].clone(), made[1].clone());1835 let (owner, heir) = (made[0].clone(), made[1].clone());
1786 assert_eq!(1836 assert_eq!(
1787- rows(1837+ sqlx::query_scalar::<_, i64>(
1788- &format!(1838+ "SELECT count(*) FROM enrollment WHERE source = $1",
1789- "SELECT VALUE id FROM enrollment WHERE source = class_group:{}",
1790- owner.key()
1791- ),
1792- &db
1793 )1839 )
1794- .await,1840+ .bind(owner.clone())
1841+ .fetch_one(&db)
1842+ .await
1843+ .unwrap(),
1795 1,1844 1,
1796 "the second attach skips the row the first wrote, so the first owns it"1845 "the second attach skips the row the first wrote, so the first owns it"
1797 );1846 );
1798 1847
1799 // The heir's class row goes while both of its link rows stay: the state a1848 // The heir's class row goes while both of its link rows stay: the state a
1800 // class deleted out from under its own links leaves.1849 // class deleted out from under its own links leaves.
1801- db.query("DELETE $c")1850+ wipe_row("class_group", heir.uuid(), &db).await;
1802- .bind(("c", heir.record()))
1803- .await
1804- .unwrap()
1805- .check()
1806- .unwrap();
1807 1851
1808 class_course::detach(&db, &owner, &algebra).await.unwrap();1852 class_course::detach(&db, &owner, &algebra).await.unwrap();
1809 assert_eq!(1853 assert_eq!(
1810- rows("SELECT VALUE id FROM enrollment", &db).await,1854+ rows("SELECT count(*) FROM enrollment", &db).await,
1811 0,1855 0,
1812 "a row handed to a class that is not there is one nothing can ever sweep"1856 "a row handed to a class that is not there is one nothing can ever sweep"
1813 );1857 );
1814 assert_eq!(1858 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,
1816 0,1860 0,
1817 "…and its seat must come back with it"1861 "…and its seat must come back with it"
1818 );1862 );
tests/regress_course_child_orphans.rsmodified+79 -86
@@ -15,33 +15,23 @@
15 //! `must_exist` still accepts its id, so a bank template can be15 //! `must_exist` still accepts its id, so a bank template can be
16 //! tagged with a subject nobody can reach.16 //! tagged with a subject nobody can reach.
17 //!17 //!
18-//! All three creates now go through `cap::touch_and_create`, which *moves* the18+//! All three creates now go through a claim that locks the course row inside
19-//! course's roster counter (bumped, gated, put back by captured value) inside19+//! the create's own transaction: the write lands on the very row the delete
20-//! the create's own transaction: the write lands on the very record the delete20+//! removes, so the store refuses one of the two.
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.
24 //!21 //!
25 //! Two halves, and they are not interchangeable. **This file is the sequential22 //! 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 existence23+//! one**: it pins the existence contract (a create against a course that is
27-//! contract (a create against a course that is already gone must be a 404, not24+//! already gone must be a 404, not an orphan) plus the restore (the borrowed
28-//! an orphan) plus the restore (the borrowed counter comes back exactly as it25+//! counter comes back exactly as it was, or the course is undeletable forever —
29-//! was, or the course is undeletable forever — a worse bug than the one being26+//! a worse bug than the one being fixed).
30-//! fixed).
31 //!27 //!
32 //! The **race** half drives the real interleaving and lives in-crate, one pin28 //! The **race** half drives the real interleaving and lives in-crate, one pin
33 //! per child beside the create it pins —29 //! per child beside the create it pins —
34 //! `db::exam::tests::an_exam_never_outlives_its_course`,30 //! `db::exam::tests::an_exam_never_outlives_its_course`,
35 //! `db::course_session::tests::a_session_never_outlives_its_course`,31 //! `db::course_session::tests::a_session_never_outlives_its_course`,
36 //! `db::subject::tests::a_subject_never_outlives_its_course` — over the32 //! `db::subject::tests::a_subject_never_outlives_its_course` — over the
37-//! shared harness `db::course::assert_no_child_outlives_a_course_delete`.33+//! 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*34+//! against the same per-test Postgres this file runs on.
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.
45 35
46 mod common;36 mod common;
47 37
@@ -63,16 +53,34 @@ use hezarfen_backend::domain::timestamp::Timestamp;
63 use hezarfen_backend::domain::user::UserId;53 use hezarfen_backend::domain::user::UserId;
64 use hezarfen_backend::error::AppError;54 use hezarfen_backend::error::AppError;
65 use serde_json::json;55 use serde_json::json;
56+use sqlx::Row as _;
66 use tokio::task::JoinHandle;57 use tokio::task::JoinHandle;
67 58
68-fn teacher() -> UserId {59+async fn teacher(db: &Database) -> UserId {
69- UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA")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())
70 }77 }
71 78
72 async fn a_course(db: &Database) -> CourseId {79 async fn a_course(db: &Database) -> CourseId {
80+ let teacher = teacher(db).await;
73 course::create(81 course::create(
74 db,82 db,
75- &teacher(),83+ &teacher,
76 CourseTitle::try_new("Fizik").unwrap(),84 CourseTitle::try_new("Fizik").unwrap(),
77 CourseDescription::try_new("").unwrap(),85 CourseDescription::try_new("").unwrap(),
78 CourseKind::course(),86 CourseKind::course(),
@@ -102,10 +110,11 @@ async fn drop_course(course: &CourseId, db: &Database) -> Result<bool, AppError>
102 110
103 fn make_exam(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {111 fn make_exam(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {
104 tokio::spawn(async move {112 tokio::spawn(async move {
113+ let teacher = teacher(&db).await;
105 let kinds = Settings::defaults().get_exam_kinds().to_vec();114 let kinds = Settings::defaults().get_exam_kinds().to_vec();
106 hezarfen_backend::db::exam::create(115 hezarfen_backend::db::exam::create(
107 &db,116 &db,
108- &teacher(),117+ &teacher,
109 &course,118 &course,
110 ExamTitle::try_new("quiz").unwrap(),119 ExamTitle::try_new("quiz").unwrap(),
111 ExamDescription::try_new("").unwrap(),120 ExamDescription::try_new("").unwrap(),
@@ -123,10 +132,11 @@ fn make_exam(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>>
123 132
124 fn make_session(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {133 fn make_session(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {
125 tokio::spawn(async move {134 tokio::spawn(async move {
135+ let teacher = teacher(&db).await;
126 db_course_session::create(136 db_course_session::create(
127 &db,137 &db,
128 &course,138 &course,
129- &teacher(),139+ &teacher,
130 SessionTopic::try_new("limits").unwrap(),140 SessionTopic::try_new("limits").unwrap(),
131 Timestamp::from_millis(1),141 Timestamp::from_millis(1),
132 None,142 None,
@@ -151,10 +161,11 @@ fn make_subject(course: CourseId, db: Database) -> JoinHandle<Result<(), AppErro
151 161
152 fn make_note(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {162 fn make_note(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {
153 tokio::spawn(async move {163 tokio::spawn(async move {
164+ let teacher = teacher(&db).await;
154 hezarfen_backend::db::course_note::create(165 hezarfen_backend::db::course_note::create(
155 &db,166 &db,
156 &course,167 &course,
157- &teacher(),168+ &teacher,
158 CourseNoteTitle::try_new("plan").unwrap(),169 CourseNoteTitle::try_new("plan").unwrap(),
159 CourseNoteContent::try_new("").unwrap(),170 CourseNoteContent::try_new("").unwrap(),
160 )171 )
@@ -166,19 +177,13 @@ fn make_note(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>>
166 /// How many rows of `table` name `course`. Stored state, never a return value:177 /// How many rows of `table` name `course`. Stored state, never a return value:
167 /// the whole point is what the store kept.178 /// the whole point is what the store kept.
168 async fn children(table: &str, course: &CourseId, db: &Database) -> usize {179 async fn children(table: &str, course: &CourseId, db: &Database) -> usize {
169- let mut result = db180+ sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
170- .query(format!(181+ "SELECT count(*) FROM {table} WHERE course = $1"
171- "SELECT VALUE id FROM {table} WHERE course = $course"182+ )))
172- ))183+ .bind(course.clone())
173- .bind(("course", course.record()))184+ .fetch_one(db)
174- .await185+ .await
175- .unwrap()186+ .unwrap() as usize
176- .check()
177- .unwrap();
178- result
179- .take::<Vec<surrealdb::types::RecordId>>(0)
180- .unwrap()
181- .len()
182 }187 }
183 188
184 // --- the sequential half: the existence contract ---------------------------189 // --- the sequential half: the existence contract ---------------------------
@@ -191,7 +196,7 @@ async fn a_create_against_a_deleted_course_refuses(
191 table: &str,196 table: &str,
192 make: fn(CourseId, Database) -> JoinHandle<Result<(), AppError>>,197 make: fn(CourseId, Database) -> JoinHandle<Result<(), AppError>>,
193 ) {198 ) {
194- let db = database::init_mem().await.unwrap();199+ let (db, _dbs) = database::init_test_db().await;
195 let course = a_course(&db).await;200 let course = a_course(&db).await;
196 assert!(drop_course(&course, &db).await.unwrap(), "the course goes");201 assert!(drop_course(&course, &db).await.unwrap(), "the course goes");
197 202
@@ -227,28 +232,27 @@ async fn a_course_note_under_a_deleted_course_is_refused() {
227 a_create_against_a_deleted_course_refuses("course_note", make_note).await;232 a_create_against_a_deleted_course_refuses("course_note", make_note).await;
228 }233 }
229 234
230-/// The counter the three creates borrow is *given back* — absent stays absent.235+/// The counter the three creates borrow is *given back*. A bump left behind is
231-/// A bump left behind is not a smaller bug than the orphan it prevents: the236+/// not a smaller bug than the orphan it prevents: the course's delete guard
232-/// course's delete guard is `WHERE (enrollment_count ?? 0) = 0`, so a course237+/// reads `enrollment_count`, so a course that once had an exam created under it
233-/// that once had an exam created under it would be undeletable forever, and the238+/// would be undeletable forever.
234-/// boot backfill keys on the column being `NONE`.
235 #[tokio::test]239 #[tokio::test]
236 async fn the_creates_give_the_courses_roster_counter_back_untouched() {240 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;
238 let course = a_course(&db).await;242 let course = a_course(&db).await;
239- let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE";
240 243
241 for make in [make_exam, make_session, make_subject, make_note] {244 for make in [make_exam, make_session, make_subject, make_note] {
242 make(course.clone(), db.clone()).await.unwrap().unwrap();245 make(course.clone(), db.clone()).await.unwrap().unwrap();
243 }246 }
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();
245 assert_eq!(253 assert_eq!(
246- result254+ bumped, 0,
247- .take::<Vec<surrealdb::types::RecordId>>(0)255+ "the borrowed counter must be restored to 0, not left bumped"
248- .unwrap()
249- .len(),
250- 1,
251- "the borrowed counter must be restored to absent, not to 0"
252 );256 );
253 // The proof that matters to a user: the course is still deletable.257 // The proof that matters to a user: the course is still deletable.
254 assert!(258 assert!(
@@ -262,12 +266,13 @@ async fn the_creates_give_the_courses_roster_counter_back_untouched() {
262 /// `course_note_file` children with it too, not just itself.266 /// `course_note_file` children with it too, not just itself.
263 #[tokio::test]267 #[tokio::test]
264 async fn a_course_note_and_its_files_never_outlive_a_course_delete() {268 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;
266 let course = a_course(&db).await;270 let course = a_course(&db).await;
271+ let teacher = teacher(&db).await;
267 let note = hezarfen_backend::db::course_note::create(272 let note = hezarfen_backend::db::course_note::create(
268 &db,273 &db,
269 &course,274 &course,
270- &teacher(),275+ &teacher,
271 CourseNoteTitle::try_new("plan").unwrap(),276 CourseNoteTitle::try_new("plan").unwrap(),
272 CourseNoteContent::try_new("body").unwrap(),277 CourseNoteContent::try_new("body").unwrap(),
273 )278 )
@@ -292,18 +297,15 @@ async fn a_course_note_and_its_files_never_outlive_a_course_delete() {
292 0,297 0,
293 "a course_note survived its course's delete"298 "a course_note survived its course's delete"
294 );299 );
295- let mut result = db300+ let files = sqlx::query_as::<_, (uuid::Uuid,)>(
296- .query("SELECT VALUE id FROM course_note_file WHERE course_note = $note")301+ "SELECT id FROM course_note_file WHERE course_note = $1",
297- .bind(("note", note.get_id().record()))302+ )
298- .await303+ .bind(note.get_id().clone())
299- .unwrap()304+ .fetch_all(&db)
300- .check()305+ .await
301- .unwrap();306+ .unwrap();
302 assert_eq!(307 assert_eq!(
303- result308+ files.len(),
304- .take::<Vec<surrealdb::types::RecordId>>(0)
305- .unwrap()
306- .len(),
307 0,309 0,
308 "a course_note_file survived its note's course's delete"310 "a course_note_file survived its note's course's delete"
309 );311 );
@@ -316,12 +318,13 @@ async fn a_course_note_and_its_files_never_outlive_a_course_delete() {
316 /// three creates above.318 /// three creates above.
317 #[tokio::test]319 #[tokio::test]
318 async fn a_course_note_file_under_a_deleted_note_is_refused() {320 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;
320 let course = a_course(&db).await;322 let course = a_course(&db).await;
323+ let teacher = teacher(&db).await;
321 let note = hezarfen_backend::db::course_note::create(324 let note = hezarfen_backend::db::course_note::create(
322 &db,325 &db,
323 &course,326 &course,
324- &teacher(),327+ &teacher,
325 CourseNoteTitle::try_new("plan").unwrap(),328 CourseNoteTitle::try_new("plan").unwrap(),
326 CourseNoteContent::try_new("").unwrap(),329 CourseNoteContent::try_new("").unwrap(),
327 )330 )
@@ -348,29 +351,19 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() {
348 matches!(file, Err(AppError::Conflict(_))),351 matches!(file, Err(AppError::Conflict(_))),
349 "a file upload under a deleted note must refuse, not {file:?}"352 "a file upload under a deleted note must refuse, not {file:?}"
350 );353 );
351- let mut result = db354+ let files = sqlx::query_as::<_, (uuid::Uuid,)>(
352- .query("SELECT VALUE id FROM course_note_file WHERE course_note = $note")355+ "SELECT id FROM course_note_file WHERE course_note = $1",
353- .bind(("note", note.get_id().record()))356+ )
354- .await357+ .bind(note.get_id().clone())
355- .unwrap()358+ .fetch_all(&db)
356- .check()359+ .await
357- .unwrap();360+ .unwrap();
358 assert_eq!(361 assert_eq!(
359- result362+ files.len(),
360- .take::<Vec<surrealdb::types::RecordId>>(0)
361- .unwrap()
362- .len(),
363 0,363 0,
364 "a refused upload left a row naming a note that is gone"364 "a refused upload left a row naming a note that is gone"
365 );365 );
366 }366 }
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.
374 #[tokio::test]367 #[tokio::test]
375 async fn an_archived_term_freezes_a_course_s_subjects_and_notes() {368 async fn an_archived_term_freezes_a_course_s_subjects_and_notes() {
376 let (app, db) = app_and_db().await;369 let (app, db) = app_and_db().await;
tests/regress_homework_orphans.rsmodified+69 -75
@@ -13,10 +13,10 @@
13 //! The lock-level races pin the handlers.13 //! The lock-level races pin the handlers.
14 //!14 //!
15 //! Every race here is judged on the *store*, never on what a request answered:15 //! 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 a16+//! under concurrency a 404 or a 204 is evidence of nothing. The windows are
17-//! 404 or a 204 is evidence of nothing. The windows are opened by the database17+//! opened by the database itself — an AFTER trigger on the table under write
18-//! itself — a `DEFINE EVENT` on the table under write fires *inside* the18+//! sleeps *inside* the writing transaction — rather than by a lucky
19-//! writing transaction — rather than by a lucky interleaving.19+//! interleaving.
20 20
21 mod common;21 mod common;
22 22
@@ -26,44 +26,32 @@ use common::{
26 id_of, items, login_as, me_id, multipart_file, send, send_raw, unenroll, upload_file_at,26 id_of, items, login_as, me_id, multipart_file, send, send_raw, unenroll, upload_file_at,
27 };27 };
28 use hezarfen_backend::database::Database;28 use hezarfen_backend::database::Database;
29+use hezarfen_backend::domain::user::UserId;
29 use serde_json::{Value, json};30 use serde_json::{Value, json};
30-use surrealdb::types::RecordId;31+use sqlx::Row as _;
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(());
38 32
39 /// A due date comfortably clear of the 60s past-scheduling grace.33 /// A due date comfortably clear of the 60s past-scheduling grace.
40 fn far_future() -> i64 {34 fn far_future() -> i64 {
41 hezarfen_backend::domain::timestamp::Timestamp::now().as_millis() + 7_200_00035 hezarfen_backend::domain::timestamp::Timestamp::now().as_millis() + 7_200_000
42 }36 }
43 37
44-/// How many rows `sql` selects ids for — the stored state, out of the store.38+/// How many rows `sql` counts — the stored state, out of the store.
45-async fn rows(db: &Database, sql: &str) -> usize {39+async fn rows(db: &Database, sql: &'static str) -> usize {
46- let mut result = db.query(sql).await.unwrap().check().unwrap();40+ sqlx::query_scalar::<_, i64>(sql)
47- result.take::<Vec<RecordId>>(0).unwrap().len()41+ .fetch_one(db)
42+ .await
43+ .unwrap() as usize
48 }44 }
49 45
50 /// One integer field off one user row, absent counting as zero.46 /// One integer field off one user row, absent counting as zero.
51 async fn counter(db: &Database, user: &str, field: &str) -> i64 {47 async fn counter(db: &Database, user: &str, field: &str) -> i64 {
52- let mut result = db48+ sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
53- .query(format!(49+ "SELECT COALESCE({field}, 0) FROM app_user WHERE id = $1"
54- "SELECT VALUE ({field} ?? 0) FROM type::record('user', $key)"50+ )))
55- ))51+ .bind(UserId::from_key(user))
56- .bind(("key", user.to_string()))52+ .fetch_one(db)
57- .await53+ .await
58- .unwrap()54+ .unwrap()
59- .check()
60- .unwrap();
61- result
62- .take::<Vec<i64>>(0)
63- .unwrap()
64- .first()
65- .copied()
66- .unwrap_or(0)
67 }55 }
68 56
69 /// Upload `bytes` onto the caller's submission to `hw` — no assertion.57 /// Upload `bytes` onto the caller's submission to `hw` — no assertion.
@@ -114,22 +102,25 @@ async fn course_with_student(
114 /// green over the hole.102 /// green over the hole.
115 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]103 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
116 async fn an_upload_inside_a_homework_delete_never_orphans() {104 async fn an_upload_inside_a_homework_delete_never_orphans() {
117- let _serial = ONE_RACE_AT_A_TIME.lock().await;
118 let (app, db) = app_and_db().await;105 let (app, db) = app_and_db().await;
119 let teacher = login_as(&app, &db, "ogretmen_odev", "teacher").await;106 let teacher = login_as(&app, &db, "ogretmen_odev", "teacher").await;
120 let (course, subject, student, student_id) =107 let (course, subject, student, student_id) =
121 course_with_student(&app, &db, &teacher, "fizik").await;108 course_with_student(&app, &db, &teacher, "fizik").await;
122 let hw = create_homework(&app, &teacher, &course, &subject, "deneme", far_future()).await;109 let hw = create_homework(&app, &teacher, &course, &subject, "deneme", far_future()).await;
123 110
124- // Hold the delete open once the cascade has run but before it commits.111+ // Hold the delete open once the cascade has run but before it commits: an
125- db.query(112+ // AFTER DELETE trigger sleeping inside the delete's own transaction.
126- "DEFINE EVENT hold_the_window ON TABLE homework WHEN $event = 'DELETE' \113+ let mut conn = db.acquire().await.expect("acquire for the trigger");
127- THEN { SLEEP 3s; };",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();",
128 )120 )
121+ .execute(&mut *conn)
129 .await122 .await
130- .expect("define the window event")123+ .expect("define the window trigger");
131- .check()
132- .expect("check the window event");
133 124
134 let drop_it = {125 let drop_it = {
135 let (app, teacher, hw) = (app.clone(), teacher.clone(), hw.clone());126 let (app, teacher, hw) = (app.clone(), teacher.clone(), hw.clone());
@@ -176,12 +167,12 @@ async fn an_upload_inside_a_homework_delete_never_orphans() {
176 167
177 // Stored state is the whole verdict.168 // Stored state is the whole verdict.
178 assert_eq!(169 assert_eq!(
179- rows(&db, "SELECT VALUE id FROM homework_submission").await,170+ rows(&db, "SELECT count(*) FROM homework_submission").await,
180 0,171 0,
181 "a submission outlived its homework"172 "a submission outlived its homework"
182 );173 );
183 assert_eq!(174 assert_eq!(
184- rows(&db, "SELECT VALUE id FROM homework_file").await,175+ rows(&db, "SELECT count(*) FROM homework_file").await,
185 0,176 0,
186 "a file outlived its homework"177 "a file outlived its homework"
187 );178 );
@@ -211,7 +202,6 @@ async fn an_upload_inside_a_homework_delete_never_orphans() {
211 /// is committed.202 /// is committed.
212 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]203 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
213 async fn an_upload_inside_an_audience_patch_is_refused() {204 async fn an_upload_inside_an_audience_patch_is_refused() {
214- let _serial = ONE_RACE_AT_A_TIME.lock().await;
215 let (app, db) = app_and_db().await;205 let (app, db) = app_and_db().await;
216 let teacher = login_as(&app, &db, "ogretmen_kapsam", "teacher").await;206 let teacher = login_as(&app, &db, "ogretmen_kapsam", "teacher").await;
217 let course = create_course(&app, &teacher, "Coğrafya").await;207 let course = create_course(&app, &teacher, "Coğrafya").await;
@@ -241,14 +231,17 @@ async fn an_upload_inside_an_audience_patch_is_refused() {
241 );231 );
242 let hw = id_of(&res.body);232 let hw = id_of(&res.body);
243 233
244- db.query(234+ let mut conn = db.acquire().await.expect("acquire for the trigger");
245- "DEFINE EVENT hold_the_patch ON TABLE homework WHEN $event = 'UPDATE' \235+ sqlx::raw_sql(
246- THEN { SLEEP 3s; };",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();",
247 )241 )
242+ .execute(&mut *conn)
248 .await243 .await
249- .expect("define the window event")244+ .expect("define the window trigger");
250- .check()
251- .expect("check the window event");
252 245
253 let narrowing = {246 let narrowing = {
254 let (app, teacher, hw, kept_id) =247 let (app, teacher, hw, kept_id) =
@@ -291,12 +284,12 @@ async fn an_upload_inside_an_audience_patch_is_refused() {
291 "a student the homework no longer names must be answered 404"284 "a student the homework no longer names must be answered 404"
292 );285 );
293 assert_eq!(286 assert_eq!(
294- rows(&db, "SELECT VALUE id FROM homework_submission").await,287+ rows(&db, "SELECT count(*) FROM homework_submission").await,
295 0,288 0,
296 "a submission landed for a student outside the audience"289 "a submission landed for a student outside the audience"
297 );290 );
298 assert_eq!(291 assert_eq!(
299- rows(&db, "SELECT VALUE id FROM homework_file").await,292+ rows(&db, "SELECT count(*) FROM homework_file").await,
300 0,293 0,
301 "... with a file on it"294 "... with a file on it"
302 );295 );
@@ -347,13 +340,13 @@ async fn a_submission_under_a_vanished_homework_is_refused() {
347 "delete the homework"340 "delete the homework"
348 );341 );
349 342
350- let refused = upsert(&db, &stale, &user, None).await;343+ let refused = upsert(&db, &stale, &user, None, false).await;
351 assert!(344 assert!(
352 refused.is_err(),345 refused.is_err(),
353 "a submission to a homework that is gone must be refused, got {refused:?}"346 "a submission to a homework that is gone must be refused, got {refused:?}"
354 );347 );
355 assert_eq!(348 assert_eq!(
356- rows(&db, "SELECT VALUE id FROM homework_submission").await,349+ rows(&db, "SELECT count(*) FROM homework_submission").await,
357 0,350 0,
358 "the refused write must leave no row"351 "the refused write must leave no row"
359 );352 );
@@ -427,7 +420,7 @@ async fn a_grade_under_a_vanished_homework_is_refused() {
427 "a grade on a homework that is gone must be refused, got {refused:?}"420 "a grade on a homework that is gone must be refused, got {refused:?}"
428 );421 );
429 assert_eq!(422 assert_eq!(
430- rows(&db, "SELECT VALUE id FROM homework_result").await,423+ rows(&db, "SELECT count(*) FROM homework_result").await,
431 0,424 0,
432 "the refused write must leave no row"425 "the refused write must leave no row"
433 );426 );
@@ -479,7 +472,6 @@ async fn a_grade_under_a_vanished_homework_is_refused() {
479 /// why it is kept and documented rather than trusted to a red test.472 /// why it is kept and documented rather than trusted to a red test.
480 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]473 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
481 async fn a_grade_inside_a_course_delete_never_orphans() {474 async fn a_grade_inside_a_course_delete_never_orphans() {
482- let _serial = ONE_RACE_AT_A_TIME.lock().await;
483 let (app, db) = app_and_db().await;475 let (app, db) = app_and_db().await;
484 let teacher = login_as(&app, &db, "ogretmen_ders", "teacher").await;476 let teacher = login_as(&app, &db, "ogretmen_ders", "teacher").await;
485 let (course, subject, _student, student_id) =477 let (course, subject, _student, student_id) =
@@ -490,14 +482,17 @@ async fn a_grade_inside_a_course_delete_never_orphans() {
490 // seconds against a one-second wait below: under a loaded test binary the482 // seconds against a one-second wait below: under a loaded test binary the
491 // spawned request can take a while to be polled at all, and the window has483 // spawned request can take a while to be polled at all, and the window has
492 // to still be open when it gets there.484 // to still be open when it gets there.
493- db.query(485+ let mut conn = db.acquire().await.expect("acquire for the trigger");
494- "DEFINE EVENT hold_the_grade ON TABLE homework_result WHEN $event = 'CREATE' \486+ sqlx::raw_sql(
495- THEN { SLEEP 3s; };",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();",
496 )492 )
493+ .execute(&mut *conn)
497 .await494 .await
498- .expect("define the window event")495+ .expect("define the window trigger");
499- .check()
500- .expect("check the window event");
501 496
502 let grading = {497 let grading = {
503 let (app, teacher, hw, target) =498 let (app, teacher, hw, target) =
@@ -550,12 +545,12 @@ async fn a_grade_inside_a_course_delete_never_orphans() {
550 545
551 // Stored state is the whole verdict.546 // Stored state is the whole verdict.
552 assert_eq!(547 assert_eq!(
553- rows(&db, "SELECT VALUE id FROM homework").await,548+ rows(&db, "SELECT count(*) FROM homework").await,
554 0,549 0,
555 "the homework survived its course"550 "the homework survived its course"
556 );551 );
557 assert_eq!(552 assert_eq!(
558- rows(&db, "SELECT VALUE id FROM homework_result").await,553+ rows(&db, "SELECT count(*) FROM homework_result").await,
559 0,554 0,
560 "a grade outlived the homework it was written against"555 "a grade outlived the homework it was written against"
561 );556 );
@@ -667,7 +662,6 @@ async fn a_student_sees_only_themselves_in_an_assigned_subset() {
667 /// would fail a *correct* implementation too.662 /// would fail a *correct* implementation too.
668 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]663 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
669 async fn a_file_add_racing_a_file_delete_never_500s() {664 async fn a_file_add_racing_a_file_delete_never_500s() {
670- let _serial = ONE_RACE_AT_A_TIME.lock().await;
671 let (app, db) = app_and_db().await;665 let (app, db) = app_and_db().await;
672 let teacher = login_as(&app, &db, "ogretmen_dosya", "teacher").await;666 let teacher = login_as(&app, &db, "ogretmen_dosya", "teacher").await;
673 let (course, subject, student, _student_id) =667 let (course, subject, student, _student_id) =
@@ -688,14 +682,17 @@ async fn a_file_add_racing_a_file_delete_never_500s() {
688 .await;682 .await;
689 let first = listed.body["files"][0]["id"].as_str().unwrap().to_string();683 let first = listed.body["files"][0]["id"].as_str().unwrap().to_string();
690 684
691- db.query(685+ let mut conn = db.acquire().await.expect("acquire for the trigger");
692- "DEFINE EVENT hold_the_delete ON TABLE homework_file WHEN $event = 'DELETE' \686+ sqlx::raw_sql(
693- THEN { SLEEP 150ms; };",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();",
694 )692 )
693+ .execute(&mut *conn)
695 .await694 .await
696- .expect("define the window event")695+ .expect("define the window trigger");
697- .check()
698- .expect("check the window event");
699 696
700 let removing = {697 let removing = {
701 let (app, student, hw, first) = (app.clone(), student.clone(), hw.clone(), first.clone());698 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() {
730 );727 );
731 // Whatever the order, the stored count matches the stored rows: the728 // Whatever the order, the stored count matches the stored rows: the
732 // submission's seat counter is what the cap reads next time.729 // submission's seat counter is what the cap reads next time.
733- let files = rows(&db, "SELECT VALUE id FROM homework_file").await;730+ let files = rows(&db, "SELECT count(*) FROM homework_file").await;
734- let mut result = db731+ let counted: Vec<i64> = sqlx::query_scalar("SELECT file_count FROM homework_submission")
735- .query("SELECT VALUE (file_count ?? 0) FROM homework_submission")732+ .fetch_all(&db)
736 .await733 .await
737- .unwrap()
738- .check()
739 .unwrap();734 .unwrap();
740- let counted: Vec<i64> = result.take(0).unwrap();
741 assert_eq!(735 assert_eq!(
742 counted.first().copied().unwrap_or(0),736 counted.first().copied().unwrap_or(0),
743 files as i64,737 files as i64,
tests/regress_roles.rsmodified+98 -96
@@ -2,8 +2,7 @@
2 //! 2026-08-02 sweep: an event seat a demotion left claimed forever, and the2 //! 2026-08-02 sweep: an event seat a demotion left claimed forever, and the
3 //! two-query deletes that could orphan a child row.3 //! two-query deletes that could orphan a child row.
4 //!4 //!
5-//! Every assertion re-reads the *store*. The in-memory engine forges wins under5+//! Every assertion re-reads the *store*: nothing below is judged on a response
6-//! concurrency (src/domain/cap.rs), so nothing below is judged on a response
7 //! body or asked who won a race — the cascade tests drive the reachable half6 //! body or asked who won a race — the cascade tests drive the reachable half
8 //! and pin what the store holds once the transaction is done.7 //! and pin what the store holds once the transaction is done.
9 8
@@ -14,25 +13,17 @@ use common::{app_and_db, id_of, login, login_as, me_id, send};
14 use hezarfen_backend::database::Database;13 use hezarfen_backend::database::Database;
15 use hezarfen_backend::domain::timestamp::Timestamp;14 use hezarfen_backend::domain::timestamp::Timestamp;
16 use serde_json::json;15 use serde_json::json;
16+use sqlx::Row as _;
17 17
18-/// One counter, re-read out of the store — never off a response body.18+/// One counter, re-read out of the store — never off a response body. `sql`
19-async fn counter(sql: &str, db: &Database) -> i64 {19+/// is a whole scalar query.
20- let mut result = db.query(sql).await.unwrap().check().unwrap();20+async fn counter(sql: &'static str, db: &Database) -> i64 {
21- result21+ sqlx::query_scalar(sql).fetch_one(db).await.unwrap()
22- .take::<Vec<i64>>(0)
23- .unwrap()
24- .first()
25- .copied()
26- .unwrap_or(0)
27 }22 }
28 23
29-/// How many rows `sql` selects ids for.24+/// How many rows `sql` counts.
30-async fn rows(sql: &str, db: &Database) -> i64 {25+async fn rows(sql: &'static str, db: &Database) -> i64 {
31- let mut result = db.query(sql).await.unwrap().check().unwrap();26+ counter(sql, db).await
32- result
33- .take::<Vec<surrealdb::types::RecordId>>(0)
34- .unwrap()
35- .len() as i64
36 }27 }
37 28
38 /// Put `user` on `event`'s signup list as `cookie`.29 /// 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) ->
81 /// The API refuses to *schedule* one there (60s grace), so the row is aged in72 /// The API refuses to *schedule* one there (60s grace), so the row is aged in
82 /// the store — the state a real event reaches by the clock simply running on.73 /// the store — the state a real event reaches by the clock simply running on.
83 async fn age_event(event: &str, db: &Database) {74 async fn age_event(event: &str, db: &Database) {
84- db.query("UPDATE type::record('event', $key) SET starts_at = 1")75+ sqlx::query("UPDATE event SET starts_at = 1 WHERE id = $1")
85- .bind(("key", event.to_string()))76+ .bind(uuid::Uuid::parse_str(event).expect("a uuid event id"))
77+ .execute(db)
86 .await78 .await
87- .unwrap()
88- .check()
89 .unwrap();79 .unwrap();
90 }80 }
91 81
@@ -109,7 +99,7 @@ async fn a_demotion_frees_the_event_seat_nothing_else_could_free() {
109 let res = seat(&app, &teacher, &event, &ali_id).await;99 let res = seat(&app, &teacher, &event, &ali_id).await;
110 assert_eq!(res.status, StatusCode::OK, "{}", res.body);100 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
111 assert_eq!(101 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,
113 1103 1
114 );104 );
115 105
@@ -126,12 +116,12 @@ async fn a_demotion_frees_the_event_seat_nothing_else_could_free() {
126 // The row goes and the seat comes back with it — one is worthless without116 // The row goes and the seat comes back with it — one is worthless without
127 // the other.117 // the other.
128 assert_eq!(118 assert_eq!(
129- rows("SELECT VALUE id FROM registration", &db).await,119+ rows("SELECT count(*) FROM registration", &db).await,
130 0,120 0,
131 "a non-student may hold no signup row"121 "a non-student may hold no signup row"
132 );122 );
133 assert_eq!(123 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,
135 0,125 0,
136 "the seat must be handed back, or the event is full forever"126 "the seat must be handed back, or the event is full forever"
137 );127 );
@@ -179,12 +169,12 @@ async fn a_promotion_keeps_the_signup_the_promoted_user_can_still_free() {
179 assert_eq!(res.status, StatusCode::OK, "{}", res.body);169 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
180 170
181 assert_eq!(171 assert_eq!(
182- rows("SELECT VALUE id FROM registration", &db).await,172+ rows("SELECT count(*) FROM registration", &db).await,
183 1,173 1,
184 "a promotion must not destroy a signup its holder can still free"174 "a promotion must not destroy a signup its holder can still free"
185 );175 );
186 assert_eq!(176 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,
188 1,178 1,
189 "…and the seat it holds stays claimed with it"179 "…and the seat it holds stays claimed with it"
190 );180 );
@@ -205,9 +195,9 @@ async fn a_promotion_keeps_the_signup_the_promoted_user_can_still_free() {
205 .expect("re-login");195 .expect("re-login");
206 let res = free_seat(&app, &promoted, &event, &ali_id).await;196 let res = free_seat(&app, &promoted, &event, &ali_id).await;
207 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);197 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);
209 assert_eq!(199 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,
211 0201 0
212 );202 );
213 }203 }
@@ -247,12 +237,12 @@ async fn a_demotion_leaves_a_frozen_signup_list_exactly_as_it_stands() {
247 assert_eq!(res.status, StatusCode::OK, "{}", res.body);237 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
248 238
249 assert_eq!(239 assert_eq!(
250- rows("SELECT VALUE id FROM registration", &db).await,240+ rows("SELECT count(*) FROM registration", &db).await,
251 1,241 1,
252 "a closed roster must not be rewritten by a role change"242 "a closed roster must not be rewritten by a role change"
253 );243 );
254 assert_eq!(244 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,
256 1,246 1,
257 "…and its seat stays claimed with it — the row is the seat"247 "…and its seat stays claimed with it — the row is the seat"
258 );248 );
@@ -285,12 +275,21 @@ async fn the_sweep_deletes_an_orphan_signup_instead_of_stranding_it() {
285 // The state a delete that raced a register used to leave: the row outlives275 // The state a delete that raced a register used to leave: the row outlives
286 // its event. Written straight into the store, since the cascade now makes276 // its event. Written straight into the store, since the cascade now makes
287 // it unreachable through the API.277 // it unreachable through the API.
288- db.query("DELETE type::record('event', $key)")278+ // The state a delete that raced a register used to leave: the row outlives
289- .bind(("key", doomed.clone()))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)
290 .await285 .await
291- .unwrap()
292- .check()
293 .unwrap();286 .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();
294 293
295 let res = send(294 let res = send(
296 &app,295 &app,
@@ -303,12 +302,12 @@ async fn the_sweep_deletes_an_orphan_signup_instead_of_stranding_it() {
303 assert_eq!(res.status, StatusCode::OK, "{}", res.body);302 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
304 303
305 assert_eq!(304 assert_eq!(
306- rows("SELECT VALUE id FROM registration", &db).await,305+ rows("SELECT count(*) FROM registration", &db).await,
307 0,306 0,
308 "an orphan signup must go with the rest — nothing else can ever remove it"307 "an orphan signup must go with the rest — nothing else can ever remove it"
309 );308 );
310 assert_eq!(309 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,
312 0,311 0,
313 "and the surviving event still gets its seat back"312 "and the surviving event still gets its seat back"
314 );313 );
@@ -316,17 +315,11 @@ async fn the_sweep_deletes_an_orphan_signup_instead_of_stranding_it() {
316 315
317 /// How many boards list `user` as a participant, read out of the store.316 /// How many boards list `user` as a participant, read out of the store.
318 async fn boards_listing(user: &str, db: &Database) -> i64 {317 async fn boards_listing(user: &str, db: &Database) -> i64 {
319- let mut result = db318+ sqlx::query_scalar("SELECT count(*) FROM board WHERE $1 = ANY(participants)")
320- .query("SELECT VALUE id FROM board WHERE type::record('user', $u) IN participants")319+ .bind(uuid::Uuid::parse_str(user).expect("a uuid user id"))
321- .bind(("u", user.to_string()))320+ .fetch_one(db)
322 .await321 .await
323 .unwrap()322 .unwrap()
324- .check()
325- .unwrap();
326- result
327- .take::<Vec<surrealdb::types::RecordId>>(0)
328- .unwrap()
329- .len() as i64
330 }323 }
331 324
332 /// A `parent` is barred from the whiteboard outright, and invites already325 /// 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() {
386 );379 );
387 // Nothing was destroyed, and the board they created is untouched beyond380 // Nothing was destroyed, and the board they created is untouched beyond
388 // that: same creator, and its other participant still on it.381 // 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);
390 let res = send(&app, "GET", &format!("/boards/{own_id}"), Some(&ali), None).await;383 let res = send(&app, "GET", &format!("/boards/{own_id}"), Some(&ali), None).await;
391 assert_eq!(res.status, StatusCode::OK, "{}", res.body);384 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
392 assert_eq!(res.body["creator"], veli_id);385 assert_eq!(res.body["creator"], veli_id);
@@ -441,34 +434,46 @@ async fn a_student_holding_every_grant(
441 434
442 /// `user`'s live role, read out of the store.435 /// `user`'s live role, read out of the store.
443 async fn role_of(user: &str, db: &Database) -> String {436 async fn role_of(user: &str, db: &Database) -> String {
444- let mut result = db437+ sqlx::query_scalar("SELECT role FROM app_user WHERE id = $1")
445- .query("SELECT VALUE role FROM type::record('user', $u)")438+ .bind(uuid::Uuid::parse_str(user).expect("a uuid user id"))
446- .bind(("u", user.to_string()))439+ .fetch_one(db)
447 .await440 .await
448- .unwrap()
449- .check()
450- .unwrap();
451- result
452- .take::<Vec<String>>(0)
453- .unwrap()
454- .first()
455- .cloned()
456 .expect("the user row must exist")441 .expect("the user row must exist")
457 }442 }
458 443
459 /// Make the next write of `kind` on `table` fail, from inside whatever444 /// Make the next write of `kind` on `table` fail, from inside whatever
460-/// transaction performs it: a `DEFINE EVENT` on the table under write fires445+/// transaction performs it: a trigger that raises aborts that very write, and
461-/// *within* that write, which is the only way to fail one statement of a446+/// with it the whole cascade's transaction — the only way to fail one statement
462-/// cascade deterministically (no sleeps, no racing tasks).447+/// of a cascade deterministically (no sleeps, no racing tasks).
463 async fn poison(table: &str, kind: &str, db: &Database) {448 async fn poison(table: &str, kind: &str, db: &Database) {
464- db.query(format!(449+ let firing = match kind {
465- "DEFINE EVENT poison ON TABLE {table} WHEN $event = '{kind}' \450+ "CREATE" => "INSERT",
466- THEN {{ THROW 'poisoned' }}"451+ "UPDATE" => "UPDATE",
467- ))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)
468 .await475 .await
469- .unwrap()476+ .expect("remove the poison trigger");
470- .check()
471- .unwrap();
472 }477 }
473 478
474 /// Every grant of `ali_id` still standing, and the old role with them — what479 /// 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) {
480 "the role write must roll back with the sweep that failed"485 "the role write must roll back with the sweep that failed"
481 );486 );
482 assert_eq!(487 assert_eq!(
483- rows("SELECT VALUE id FROM enrollment", db).await,488+ rows("SELECT count(*) FROM enrollment", db).await,
484 1,489 1,
485 "the enrollment must survive a failed cascade"490 "the enrollment must survive a failed cascade"
486 );491 );
487 assert_eq!(492 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,
489 1,494 1,
490 "…and so must its seat, or the roster and the count disagree forever"495 "…and so must its seat, or the roster and the count disagree forever"
491 );496 );
492 assert_eq!(497 assert_eq!(
493- rows("SELECT VALUE id FROM parent_link", db).await,498+ rows("SELECT count(*) FROM parent_link", db).await,
494 1,499 1,
495 "the parent link must survive a failed cascade"500 "the parent link must survive a failed cascade"
496 );501 );
497 assert_eq!(502 assert_eq!(
498- rows("SELECT VALUE id FROM registration", db).await,503+ rows("SELECT count(*) FROM registration", db).await,
499 1,504 1,
500 "the signup must survive a failed cascade"505 "the signup must survive a failed cascade"
501 );506 );
502 assert_eq!(507 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,
504 1,509 1,
505 "…with its seat still claimed"510 "…with its seat still claimed"
506 );511 );
@@ -533,18 +538,23 @@ async fn the_retry_takes_everything(
533 assert_eq!(role_of(ali_id, db).await, "parent");538 assert_eq!(role_of(ali_id, db).await, "parent");
534 for table in ["enrollment", "parent_link", "registration", "class_member"] {539 for table in ["enrollment", "parent_link", "registration", "class_member"] {
535 assert_eq!(540 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(),
537 0,547 0,
538 "{table} must be swept by the re-sent PATCH"548 "{table} must be swept by the re-sent PATCH"
539 );549 );
540 }550 }
541 assert_eq!(boards_listing(ali_id, db).await, 0);551 assert_eq!(boards_listing(ali_id, db).await, 0);
542 assert_eq!(552 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,
544 0554 0
545 );555 );
546 assert_eq!(556 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,
548 0558 0
549 );559 );
550 // The seat is usable, which is the whole point of freeing it: the one-seat560 // 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(
566 /// enrollment, the parent link and the event seat already gone, and nothing to576 /// enrollment, the parent link and the event seat already gone, and nothing to
567 /// ever put them back.577 /// ever put them back.
568 ///578 ///
569-/// The failure is injected the way `regress_classes` does it: a `DEFINE EVENT`579+/// The failure is injected the way `regress_classes` does it: a trigger on a
570-/// on a table the cascade writes fires *inside* that write, so the abort is580+/// table the cascade writes raises inside that very write, so the abort is
571-/// deterministic instead of a race the in-memory engine would lie about. Both581+/// deterministic instead of a race. Both
572 /// ends of the cascade are poisoned, in two tests, because they fail different582 /// ends of the cascade are poisoned, in two tests, because they fail different
573 /// things: the board roster is the *last* statement of the parent arm (so every583 /// things: the board roster is the *last* statement of the parent arm (so every
574 /// assertion below it is about a write that already succeeded and must be584 /// 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
596 );606 );
597 nothing_was_swept(&ali_id, &db).await;607 nothing_was_swept(&ali_id, &db).await;
598 608
599- db.query("REMOVE EVENT poison ON TABLE board")609+ unpoison("board", &db).await;
600- .await
601- .unwrap()
602- .check()
603- .unwrap();
604 the_retry_takes_everything(&app, &db, &admin, &teacher, &ali_id).await;610 the_retry_takes_everything(&app, &db, &admin, &teacher, &ali_id).await;
605 }611 }
606 612
@@ -630,11 +636,7 @@ async fn a_failure_early_in_the_cascade_rolls_the_role_write_back_with_it() {
630 );636 );
631 nothing_was_swept(&ali_id, &db).await;637 nothing_was_swept(&ali_id, &db).await;
632 638
633- db.query("REMOVE EVENT poison ON TABLE enrollment")639+ unpoison("enrollment", &db).await;
634- .await
635- .unwrap()
636- .check()
637- .unwrap();
638 the_retry_takes_everything(&app, &db, &admin, &teacher, &ali_id).await;640 the_retry_takes_everything(&app, &db, &admin, &teacher, &ali_id).await;
639 }641 }
640 642
@@ -661,7 +663,7 @@ async fn deleting_an_event_takes_its_children_with_it() {
661 )663 )
662 .await;664 .await;
663 assert_eq!(res.status, StatusCode::OK, "{}", res.body);665 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);
665 667
666 let res = send(668 let res = send(
667 &app,669 &app,
@@ -673,14 +675,14 @@ async fn deleting_an_event_takes_its_children_with_it() {
673 .await;675 .await;
674 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);676 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
675 677
676- assert_eq!(rows("SELECT VALUE id FROM event", &db).await, 0);678+ assert_eq!(rows("SELECT count(*) FROM event", &db).await, 0);
677 assert_eq!(679 assert_eq!(
678- rows("SELECT VALUE id FROM attendance", &db).await,680+ rows("SELECT count(*) FROM attendance", &db).await,
679 0,681 0,
680 "no mark may outlive its event"682 "no mark may outlive its event"
681 );683 );
682 assert_eq!(684 assert_eq!(
683- rows("SELECT VALUE id FROM registration", &db).await,685+ rows("SELECT count(*) FROM registration", &db).await,
684 0,686 0,
685 "no signup may outlive its event"687 "no signup may outlive its event"
686 );688 );
@@ -708,14 +710,14 @@ async fn deleting_a_note_takes_its_attachment_rows_with_it() {
708 710
709 let up = common::upload_file(&app, &ali, &note, "plan.txt", "text/plain", b"merhaba").await;711 let up = common::upload_file(&app, &ali, &note, "plan.txt", "text/plain", b"merhaba").await;
710 assert_eq!(up.status, StatusCode::CREATED, "{}", up.body);712 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);
712 714
713 let res = send(&app, "DELETE", &format!("/notes/{note}"), Some(&ali), None).await;715 let res = send(&app, "DELETE", &format!("/notes/{note}"), Some(&ali), None).await;
714 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);716 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
715 717
716- assert_eq!(rows("SELECT VALUE id FROM note", &db).await, 0);718+ assert_eq!(rows("SELECT count(*) FROM note", &db).await, 0);
717 assert_eq!(719 assert_eq!(
718- rows("SELECT VALUE id FROM note_file", &db).await,720+ rows("SELECT count(*) FROM note_file", &db).await,
719 0,721 0,
720 "no attachment row may outlive its note"722 "no attachment row may outlive its note"
721 );723 );