diff --git a/tests/builder_api.rs b/tests/builder_api.rs index 2496646..36488bd 100644 --- a/tests/builder_api.rs +++ b/tests/builder_api.rs @@ -805,16 +805,15 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() { assert_eq!(total(¬es.body), 0, "old rows survived the drop"); } -/// Claim 2, remote mode: `Tenants::create`/`drop` interpolate the slug into -/// `DEFINE DATABASE` / `REMOVE DATABASE`. Not injectable — but the statements -/// must at least *execute* for every slug `Slug::try_new` accepts. Run the exact -/// production statements against a live SurrealDB parser. +/// Claim 2, the school lifecycle: `Tenants::create`/`drop` interpolate the slug +/// into `CREATE DATABASE` / `DROP DATABASE`. Not injectable — but the statements +/// must at least *execute* for every slug `Slug::try_new` accepts. Each slug is +/// driven through the real lifecycle over HTTP, which is exactly those +/// statements against the live server. #[tokio::test] async fn probe_remote_mode_database_statements_execute_for_every_accepted_slug() { - let Some(deployment) = common::remote_deployment(&[]).await else { - return; - }; - let control = deployment.tenants.control(); + let (app, _db, _tenants) = deployment().await; + let builder = builder_login(&app).await; let mut broken: Vec = Vec::new(); for raw in [ @@ -827,32 +826,38 @@ async fn probe_remote_mode_database_statements_execute_for_every_accepted_slug() "12345", "a1", ] { - let Ok(slug) = Slug::try_new(raw) else { + // The demo school this deployment already carries is the one slug the + // create would refuse as taken; the rest are free. + if Slug::try_new(raw).is_err() || raw == DEMO_SLUG { continue; - }; - // The exact statements `Tenants::create` / `drop` send, via the same - // identifier quoting they use. - let ident = hezarfen_backend::tenant::quoted_ident(&slug); - let define = control - .query(format!("DEFINE DATABASE IF NOT EXISTS {ident}")) - .await - .map_err(|e| e.to_string()) - .and_then(|r| r.check().map(|_| ()).map_err(|e| e.to_string())); - let remove = control - .query(format!("REMOVE DATABASE IF EXISTS {ident}")) - .await - .map_err(|e| e.to_string()) - .and_then(|r| r.check().map(|_| ()).map_err(|e| e.to_string())); - if let Err(err) = define { - broken.push(format!("DEFINE DATABASE {raw} -> {err}")); } - if let Err(err) = remove { - broken.push(format!("REMOVE DATABASE {raw} -> {err}")); + // The exact statements `Tenants::create` / `drop` send, through the + // routes that send them. + let made = create_school(&app, &builder, raw, "secret1").await; + if made.status != StatusCode::CREATED { + broken.push(format!( + "CREATE DATABASE {raw} -> {} {:?}", + made.status, made.body + )); + } + let dropped = send( + &app, + "DELETE", + &format!("/schools/{raw}"), + Some(&builder), + None, + ) + .await; + if dropped.status != StatusCode::NO_CONTENT { + broken.push(format!( + "DROP DATABASE {raw} -> {} {:?}", + dropped.status, dropped.body + )); } } assert!( broken.is_empty(), - "slugs accepted by Slug::try_new whose remote-mode statements do not execute:\n{}", + "slugs accepted by Slug::try_new whose school statements do not execute:\n{}", broken.join("\n") ); } @@ -1220,14 +1225,12 @@ async fn probe_concurrent_creates_of_one_slug_leave_one_school() { assert_eq!(opens, 1, "{opens} of the two admin passwords open p6race"); } -/// Claim 1/2 driven against a **real remote deployment** — the mode every test -/// above skips, and the only one where `DEFINE DATABASE` / `REMOVE DATABASE` -/// actually run. `ata-koleji` is the slug the OpenAPI schema advertises. +/// Claim 1/2 driven against a full deployment of its own, where the school +/// lifecycle's `CREATE DATABASE` / `DROP DATABASE` actually run. +/// `ata-koleji` is the slug the OpenAPI schema advertises. #[tokio::test] async fn probe_remote_deployment_creates_and_deletes_a_hyphenated_school() { - let Some(deployment) = common::remote_deployment(&[]).await else { - return; - }; + let deployment = common::deployment_with(&[]).await; let app = deployment.app; builder::ensure( deployment.tenants.control(), @@ -2005,18 +2008,11 @@ async fn probe_a_refused_batch_leaves_the_row_byte_identical() { let builder = builder_login(&app).await; async fn raw_row(tenants: &Tenants) -> Vec { - tenants - .control() - .query(format!( - "SELECT VALUE modules FROM type::record('school', '{DEMO_SLUG}')" - )) + sqlx::query_scalar("SELECT modules FROM school WHERE slug = $1") + .bind(DEMO_SLUG) + .fetch_one(tenants.control()) .await .expect("raw read") - .check() - .expect("raw check") - .take::>>(0) - .expect("modules column") - .remove(0) } let before = raw_row(&tenants).await; @@ -2048,13 +2044,11 @@ async fn probe_a_refused_batch_leaves_the_row_byte_identical() { /// a thread-local subscriber cannot measure this reliably: `tracing` caches a /// callsite's interest process-wide the first time any thread reaches it, and /// with tests running in parallel that thread is usually a sibling with no -/// subscriber — the SurrealDB callsites are then disabled for the whole -/// process before this test ever asks, and the count is 0 (measured: 0 in 7 of -/// 8 runs against noisy siblings; a global subscriber counted on 6 of 6). -/// Global is safe here because this subscriber only counts: it stores nothing, -/// prints nothing, and its `enabled` refuses every callsite that is not a -/// SurrealDB one on *this* test's thread, so a sibling test neither pays for it -/// nor lands in the figure. +/// subscriber — the sqlx callsites are then disabled for the whole process +/// before this test ever asks, and the count is 0. Global is safe here because +/// this subscriber only counts: it stores nothing, prints nothing, and its +/// `enabled` refuses every callsite that is not a sqlx one on *this* test's +/// thread, so a sibling test neither pays for it nor lands in the figure. #[tokio::test] async fn probe_registry_reads_per_request() { use std::sync::Arc; @@ -2072,7 +2066,7 @@ async fn probe_registry_reads_per_request() { tracing::subscriber::Interest::sometimes() } fn enabled(&self, meta: &tracing::Metadata<'_>) -> bool { - meta.target().starts_with("surrealdb") && std::thread::current().id() == self.thread + meta.target().starts_with("sqlx") && std::thread::current().id() == self.thread } fn new_span(&self, _: &span::Attributes<'_>) -> span::Id { self.count.fetch_add(1, Ordering::Relaxed); @@ -2100,10 +2094,10 @@ async fn probe_registry_reads_per_request() { let res = send(&app, "GET", "/notes", Some(&cookie), None).await; assert_eq!(res.status, StatusCode::OK, "{:?}", res.body); let seen = count.load(Ordering::Relaxed); - println!("PROBE surrealdb spans/events for GET /notes = {seen}"); + println!("PROBE sqlx spans/events for GET /notes = {seen}"); assert!( seen > 0, - "UNMEASURED: the surrealdb SDK emitted no tracing spans, so per-request \ + "UNMEASURED: sqlx emitted no tracing spans, so per-request \ registry reads cannot be counted this way" ); } diff --git a/tests/regress_blueprints.rs b/tests/regress_blueprints.rs index 6aa989b..b34ec5e 100644 --- a/tests/regress_blueprints.rs +++ b/tests/regress_blueprints.rs @@ -13,45 +13,47 @@ mod common; use axum::http::StatusCode; -use common::{Res, app_and_db, create_course, login_as, me_id, send}; +use common::{GHOST_ID, Res, app_and_db, create_course, login_as, me_id, send}; use hezarfen_backend::database::Database; use hezarfen_backend::domain::class_blueprint::ClassBlueprint; use hezarfen_backend::domain::course::CourseId; +use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::UserId; use hezarfen_backend::error::AppError; use hezarfen_backend::service::class_blueprint; use serde_json::{Value, json}; -/// One counter, re-read out of the store. -async fn counter(sql: &str, db: &Database) -> i64 { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) +/// One counter, re-read out of the store. `sql` is a whole scalar query. +async fn counter(sql: &'static str, db: &Database) -> i64 { + sqlx::query_scalar(sql).fetch_one(db).await.unwrap() } -/// How many rows `sql` selects ids for. -async fn rows(sql: &str, db: &Database) -> i64 { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result - .take::>(0) - .unwrap() - .len() as i64 +/// How many rows `sql` counts. +async fn rows(sql: &'static str, db: &Database) -> i64 { + counter(sql, db).await +} + +/// One row's counter column, re-read out of the store. +async fn count_on(column: &'static str, table: &'static str, id: &str, db: &Database) -> i64 { + sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT {column} FROM {table} WHERE id = $1" + ))) + .bind(uuid::Uuid::parse_str(id).expect("a uuid row id")) + .fetch_one(db) + .await + .unwrap() } /// Is that course on that class, in the store? async fn attached(class: &str, course: &str, db: &Database) -> bool { - rows( - &format!( - "SELECT VALUE id FROM class_course WHERE class = class_group:{class} \ - AND course = course:{course}" - ), - db, + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM class_course WHERE class = $1 AND course = $2", ) + .bind(uuid::Uuid::parse_str(class).expect("a uuid class id")) + .bind(uuid::Uuid::parse_str(course).expect("a uuid course id")) + .fetch_one(db) .await + .unwrap() == 1 } @@ -59,33 +61,26 @@ async fn attached(class: &str, course: &str, db: &Database) -> bool { /// no such key at all — which is the whole provenance rule: absent means a /// human attached it. async fn source_of(class: &str, course: &str, db: &Database) -> Option { - let mut result = db - .query(format!( - "SELECT VALUE (IF source != NONE THEN record::id(source) ELSE '' END) \ - FROM class_course WHERE class = class_group:{class} AND course = course:{course}" - )) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .into_iter() - .next() - .filter(|key| !key.is_empty()) + sqlx::query_scalar::<_, Option>( + "SELECT source FROM class_course WHERE class = $1 AND course = $2", + ) + .bind(uuid::Uuid::parse_str(class).expect("a uuid class id")) + .bind(uuid::Uuid::parse_str(course).expect("a uuid course id")) + .fetch_one(db) + .await + .unwrap() } /// Does that grade's template still name that course, in the store? async fn templated(grade: &str, course: &str, db: &Database) -> bool { - rows( - &format!( - "SELECT VALUE id FROM class_blueprint \ - WHERE grade = '{grade}' AND course:{course} IN courses" - ), - db, + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM class_blueprint WHERE grade = $1 AND $2 = ANY(courses)", ) + .bind(grade) + .bind(CourseId::from_key(course)) + .fetch_one(db) .await + .unwrap() == 1 } @@ -250,7 +245,7 @@ async fn a_blueprint_is_created_read_updated_and_deleted() { ) .await; assert_eq!(dropped.status, StatusCode::NO_CONTENT); - assert_eq!(rows("SELECT VALUE id FROM class_blueprint", &db).await, 0); + assert_eq!(rows("SELECT count(*) FROM class_blueprint", &db).await, 0); let gone = send(&app, "GET", "/classes/blueprints/9", Some(&manager), None).await; assert_eq!(gone.status, StatusCode::NOT_FOUND); @@ -313,23 +308,20 @@ async fn a_fresh_class_takes_its_grades_blueprint() { "the blueprint must own what it attached" ); assert_eq!( - rows( - &format!( - "SELECT VALUE id FROM enrollment WHERE course = course:{course} \ - AND user = user:{student}" - ), - &db + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM enrollment WHERE course = $1 AND app_user = $2", ) - .await, + .bind(CourseId::from_key(course)) + .bind(UserId::from_key(&student)) + .fetch_one(&db) + .await + .unwrap(), 1, "stocking a class enrolls its roster, in real rows" ); } assert_eq!( - counter( - &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"), - &db - ) + count_on("class_course_count", "class_group", &class, &db) .await, 2 ); @@ -345,7 +337,7 @@ async fn a_fresh_class_takes_its_grades_blueprint() { .await; assert_eq!(twice.status, StatusCode::OK); assert!(skips(&twice).is_empty()); - assert_eq!(rows("SELECT VALUE id FROM class_course", &db).await, 2); + assert_eq!(rows("SELECT count(*) FROM class_course", &db).await, 2); // A class whose grade no blueprint covers is a 404, not an empty success. 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() { ); } assert_eq!( - counter( - &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"), - &db - ) + count_on("class_course_count", "class_group", &class, &db) .await, 2 ); @@ -425,14 +414,14 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() { let student = student_in(&app, &db, &class, &manager, "ali").await; for course in [&algebra, &physics] { assert_eq!( - rows( - &format!( - "SELECT VALUE id FROM enrollment WHERE course = course:{course} \ - AND user = user:{student}" - ), - &db + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM enrollment WHERE course = $1 AND app_user = $2", ) - .await, + .bind(CourseId::from_key(course)) + .bind(UserId::from_key(&student)) + .fetch_one(&db) + .await + .unwrap(), 1, "a stocked class enrolls its roster like any other" ); @@ -454,11 +443,13 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() { assert!(skips(&res).is_empty(), "{:?}", res.body); let bare = res.body["class"]["id"].as_str().unwrap(); assert_eq!( - rows( - &format!("SELECT VALUE id FROM class_course WHERE class = class_group:{bare}"), - &db + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM class_course WHERE class = $1", ) - .await, + .bind(uuid::Uuid::parse_str(bare).expect("a uuid class id")) + .fetch_one(&db) + .await + .unwrap(), 0, "nothing may be attached to a section no template reached" ); @@ -496,10 +487,10 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() { // meets when a course goes after it read the list. Nothing carries it yet // (no section exists at grade 9), so this is the pair that cannot fit when // the first one is created. - db.query(format!("DELETE course:{physics}")) + sqlx::query("DELETE FROM course WHERE id = $1") + .bind(CourseId::from_key(&physics)) + .execute(&db) .await - .unwrap() - .check() .unwrap(); assert!( templated("9", &physics, &db).await, @@ -531,11 +522,11 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() { .expect("class id") .to_string(); assert_eq!( - rows( - &format!("SELECT VALUE id FROM class_group WHERE id = class_group:{class}"), - &db - ) - .await, + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM class_group WHERE id = $1") + .bind(uuid::Uuid::parse_str(&class).expect("a uuid class id")) + .fetch_one(&db) + .await + .unwrap(), 1, "the class is really there — the skip is a report, not a rollback" ); @@ -544,11 +535,11 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() { "…and the course that did fit is on it" ); assert_eq!( - rows( - &format!("SELECT VALUE id FROM class_course WHERE class = class_group:{class}"), - &db - ) - .await, + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM class_course WHERE class = $1") + .bind(uuid::Uuid::parse_str(&class).expect("a uuid class id")) + .fetch_one(&db) + .await + .unwrap(), 1 ); // 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() { ) .await; assert_eq!(made.status, StatusCode::CREATED); - assert_eq!(rows("SELECT VALUE id FROM class_course", &db).await, 0); + assert_eq!(rows("SELECT count(*) FROM class_course", &db).await, 0); // …and the edit is what has to reach the two classes standing there. let patched = send( @@ -605,37 +596,28 @@ async fn an_edit_retro_pumps_every_class_at_the_grade() { // grade. for class in [&a, &b] { assert_eq!( - counter( - &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"), - &db - ) + count_on("class_course_count", "class_group", class, &db) .await, 1 ); } assert_eq!( - counter( - &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{ten}"), - &db - ) + count_on("class_course_count", "class_group", &ten, &db) .await, 0 ); assert_eq!( - counter( - &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{algebra}"), - &db - ) + count_on("enrollment_count", "course", &algebra, &db) .await, 1, "one student at the grade, one seat" ); assert_eq!( - rows( - &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali}"), - &db - ) - .await, + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM enrollment WHERE app_user = $1") + .bind(UserId::from_key(&ali)) + .fetch_one(&db) + .await + .unwrap(), 1 ); } @@ -687,23 +669,17 @@ async fn a_class_that_does_not_fit_is_reported_not_aborted() { // Nothing moved on the skipped class: not its attachment counter, and not // one of the seats the refused attach touched on its way to the refusal. assert_eq!( - counter( - &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{full}"), - &db - ) + count_on("class_course_count", "class_group", &full, &db) .await, 0 ); assert_eq!( - counter( - &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{tight}"), - &db - ) + count_on("enrollment_count", "course", &tight, &db) .await, 0, "the empty class took no seat, and the refused one gave every seat back" ); - assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 0); + assert_eq!(rows("SELECT count(*) FROM enrollment", &db).await, 0); } /// 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() { "…and nothing else — a hand attach survives" ); assert_eq!( - counter( - &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{pumped}"), - &db - ) + count_on("class_course_count", "class_group", &pumped, &db) .await, 0, "the detach gives the class its count back" ); assert_eq!( - counter( - &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{byhand}"), - &db - ) + count_on("class_course_count", "class_group", &byhand, &db) .await, 1 ); assert_eq!( - rows( - &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali}"), - &db - ) - .await, + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM enrollment WHERE app_user = $1") + .bind(UserId::from_key(&ali)) + .fetch_one(&db) + .await + .unwrap(), 0, "the enrollments the blueprint pumped go with it" ); assert_eq!( - counter( - &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{algebra}"), - &db - ) + count_on("enrollment_count", "course", &algebra, &db) .await, 1, "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() { ) .await; assert_eq!(attached_by_hand.status, StatusCode::CREATED); - // Age the row to before the column existed. `UNSET`, not `= NONE`: an - // absent key is what the store holds today, and it is what the rule reads. - db.query("UPDATE class_course UNSET source") + // Age the row to before the column existed: a NULL `source` is what the + // store holds for a hand attach, and it is what the rule reads. + sqlx::query("UPDATE class_course SET source = NULL") + .execute(&db) .await - .unwrap() - .check() .unwrap(); assert_eq!(source_of(&class, &algebra, &db).await, None); @@ -961,10 +927,7 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() { "a pre-migration row is hand-attached and unreachable by any blueprint sweep" ); assert_eq!( - counter( - &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{algebra}"), - &db - ) + count_on("enrollment_count", "course", &algebra, &db) .await, 1 ); @@ -979,15 +942,14 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() { /// `class_course` row tagged with a record nothing can reach, since the grade /// label *is* the id and no sweep will ever run for it again. /// -/// Racing two requests would be a coin flip the in-memory engine lies about, so -/// the delete is injected by the database itself: a `DEFINE EVENT` on -/// `class_course` fires *inside* the pump's own transaction, the instant the -/// link row lands — which is exactly "after the guard passed, before the -/// commit", every single time. This is a below-the-lock probe by construction -/// (the store deletes the row, not `service::class_blueprint::delete`), so it does not -/// test `BLUEPRINT_LOCK`; it pins the end state that lock prevents in-process, -/// and the recovery contract that covers the one residue it cannot — a process -/// crash between the delete and its sweep. +/// Under Postgres the window itself is shut — `class_course.source` is a real +/// foreign key, so a blueprint delete inside the attach's transaction takes the +/// attach down with it, and a crash between the delete and its sweep is one +/// transaction. What the store can no longer refuse is the residue an old +/// volume can still carry, so the stranded row is forged the one way Postgres +/// allows (FK triggers suspended for the one transaction) and what is pinned is +/// the recovery contract for it: a human detaches it one course at a time, and +/// the counters come back exact. #[tokio::test] async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() { let (app, db) = app_and_db().await; @@ -1019,41 +981,46 @@ async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() { assert_eq!(moved.status, StatusCode::OK, "{:?}", moved.body); assert!(!attached(&class, &algebra, &db).await); - // Delete the blueprint from inside the very write that attaches on its - // behalf. - db.query( - "DEFINE EVENT lose_blueprint ON TABLE class_course WHEN $event = 'CREATE' \ - THEN { DELETE type::record('class_blueprint', '9'); };", + // The stranded state: the link row committed, the blueprint it names did + // not survive. Real FKs refuse that state, so it is written with FK + // triggers suspended — the manager id is real, the `source` FK is the one + // the strand consists of. + let manager_id = UserId::from_key(&me_id(&app, &manager).await); + let mut tx = db.begin().await.unwrap(); + sqlx::query("SET LOCAL session_replication_role = replica") + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query("DELETE FROM class_blueprint WHERE grade = '9'") + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query( + "INSERT INTO class_course (class, course, attached_by, attached_at, source) \ + VALUES ($1, $2, $3, $4, '9')", ) + .bind(uuid::Uuid::parse_str(&class).expect("a uuid class id")) + .bind(CourseId::from_key(&algebra)) + .bind(manager_id) + .bind(Timestamp::now().as_millis()) + .execute(&mut *tx) .await - .unwrap() - .check() .unwrap(); - - let pumped = send( - &app, - "POST", - &format!("/classes/{class}/blueprint"), - Some(&manager), - None, - ) - .await; - assert_eq!(pumped.status, StatusCode::OK, "{:?}", pumped.body); - assert!( - skips(&pumped).is_empty(), - "the pump was told it succeeded — which is what makes the row below \ - invisible to the caller: {:?}", - pumped.body - ); + sqlx::query("UPDATE class_group SET class_course_count = 1 WHERE id = $1") + .bind(uuid::Uuid::parse_str(&class).expect("a uuid class id")) + .execute(&mut *tx) + .await + .unwrap(); + tx.commit().await.unwrap(); assert_eq!( - rows("SELECT VALUE id FROM class_blueprint", &db).await, + rows("SELECT count(*) FROM class_blueprint", &db).await, 0, "the injected delete really landed" ); assert!( attached(&class, &algebra, &db).await, - "the link committed after its blueprint was gone: this is the stranded \ + "the link stands after its blueprint was gone: this is the stranded \ row, tagged with a record no sweep can ever reach" ); 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() { ); assert!(!attached(&class, &algebra, &db).await); assert_eq!( - counter( - &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"), - &db - ) + count_on("class_course_count", "class_group", &class, &db) .await, 0, "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() { // The state a sweep that died half-way leaves: the list is stored without // history, its attachment is not. - db.query( - "UPDATE type::record('class_blueprint', '9') SET courses = [type::record('course', $c)]", - ) - .bind(("c", algebra.clone())) - .await - .unwrap() - .check() - .unwrap(); + sqlx::query("UPDATE class_blueprint SET courses = $1 WHERE grade = '9'") + .bind(vec![CourseId::from_key(&algebra)]) + .execute(&db) + .await + .unwrap(); let courses = held(&app, &manager, "9").await; assert_eq!( @@ -1490,19 +1451,19 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() { "re-sending the stored list must finish the removal it stored" ); assert_eq!( - rows( - &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali} AND course = course:{history}"), - &db + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM enrollment WHERE app_user = $1 AND course = $2", ) - .await, + .bind(UserId::from_key(&ali)) + .bind(CourseId::from_key(&history)) + .fetch_one(&db) + .await + .unwrap(), 0, "…enrollments and all" ); assert_eq!( - counter( - &format!("SELECT VALUE (enrollment_count ?? 0) FROM course:{history}"), - &db - ) + count_on("enrollment_count", "course", &history, &db) .await, 0, "…with the seat given back" @@ -1512,11 +1473,14 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() { "and the course the template still holds is untouched" ); assert_eq!( - rows( - &format!("SELECT VALUE id FROM enrollment WHERE user = user:{ali} AND course = course:{algebra}"), - &db + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM enrollment WHERE app_user = $1 AND course = $2", ) - .await, + .bind(UserId::from_key(&ali)) + .bind(CourseId::from_key(&algebra)) + .fetch_one(&db) + .await + .unwrap(), 1 ); } @@ -1538,14 +1502,17 @@ async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() { let history = create_course(&app, &manager, "history").await; let class = create_class(&app, &manager, "9-A", "9").await; - db.query(format!( - "DEFINE EVENT kill_on_create ON TABLE class_blueprint WHEN $event = 'CREATE' \ - THEN {{ DELETE type::record('course', '{algebra}'); }};" - )) + let mut conn = db.acquire().await.expect("acquire for the trigger"); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!( + "CREATE FUNCTION heztest_kill_on_create() RETURNS trigger AS $$ + BEGIN DELETE FROM course WHERE id = '{algebra}'; RETURN NULL; END; + $$ LANGUAGE plpgsql; + CREATE TRIGGER heztest_kill_on_create AFTER INSERT ON class_blueprint + FOR EACH ROW EXECUTE FUNCTION heztest_kill_on_create();" + ))) + .execute(&mut *conn) .await - .unwrap() - .check() - .unwrap(); + .expect("define the kill-on-create trigger"); let made = send( &app, "POST", @@ -1571,14 +1538,16 @@ async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() { ); // The same window on the edit route. - db.query(format!( - "DEFINE EVENT kill_on_update ON TABLE class_blueprint WHEN $event = 'UPDATE' \ - THEN {{ DELETE type::record('course', '{history}'); }};" - )) + sqlx::raw_sql(sqlx::AssertSqlSafe(format!( + "CREATE FUNCTION heztest_kill_on_update() RETURNS trigger AS $$ + BEGIN DELETE FROM course WHERE id = '{history}'; RETURN NULL; END; + $$ LANGUAGE plpgsql; + CREATE TRIGGER heztest_kill_on_update AFTER UPDATE ON class_blueprint + FOR EACH ROW EXECUTE FUNCTION heztest_kill_on_update();" + ))) + .execute(&mut *conn) .await - .unwrap() - .check() - .unwrap(); + .expect("define the kill-on-update trigger"); let patched = send( &app, "PATCH", @@ -1624,7 +1593,7 @@ async fn a_template_write_refuses_a_course_that_is_gone() { let manager = login_as(&app, &db, "mgr", "manager").await; let by = UserId::from_key(&me_id(&app, &manager).await); let algebra = CourseId::from_key(&create_course(&app, &manager, "algebra").await); - let ghost = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); + let ghost = CourseId::from_key(GHOST_ID); let refused = class_blueprint::create( &db, @@ -1638,7 +1607,7 @@ async fn a_template_write_refuses_a_course_that_is_gone() { "a course that is gone is a 400, not a template naming it: {refused:?}" ); assert_eq!( - rows("SELECT VALUE id FROM class_blueprint", &db).await, + rows("SELECT count(*) FROM class_blueprint", &db).await, 0, "…and nothing may be stored" ); diff --git a/tests/regress_classes.rs b/tests/regress_classes.rs index 174dcd3..768911b 100644 --- a/tests/regress_classes.rs +++ b/tests/regress_classes.rs @@ -6,7 +6,7 @@ mod common; use axum::http::StatusCode; -use common::{Res, app_and_db, create_course, login_as, me_id, send, total}; +use common::{ABSENT_ID, GHOST_ID, Res, app_and_db, create_course, login_as, me_id, send, total}; use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; use hezarfen_backend::database::Database; use hezarfen_backend::domain::class_group::ClassName; @@ -15,25 +15,62 @@ use hezarfen_backend::domain::user::UserId; use hezarfen_backend::error::AppError; use hezarfen_backend::service::{class_course, class_group, class_member}; use serde_json::json; +use sqlx::Row as _; -/// One counter, re-read out of the store — never off a response body. -async fn counter(sql: &str, db: &Database) -> i64 { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) +/// One counter, re-read out of the store — never off a response body. `sql` +/// is a whole scalar query; each call spells the aggregate it asserts on. +async fn counter(sql: &'static str, db: &Database) -> i64 { + sqlx::query_scalar(sql).fetch_one(db).await.unwrap() +} + +/// How many rows `sql` counts. +async fn rows(sql: &'static str, db: &Database) -> i64 { + counter(sql, db).await } -/// How many rows `sql` selects ids for. -async fn rows(sql: &str, db: &Database) -> i64 { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result - .take::>(0) +/// A real `app_user` row for the fixture actor or member a domain call must +/// name: the actor and member columns are foreign keys now, so they are rows, +/// not fabricated ids. The username is unique, so every call for the same name +/// shares one row, whichever call minted it. These rows never log in, so the +/// hash is a stub. +async fn fixture_user(db: &Database, username: &str) -> UserId { + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING", + ) + .bind(UserId::generate().uuid()) + .bind(username) + .execute(db) + .await + .unwrap(); + let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1") + .bind(username) + .fetch_one(db) + .await .unwrap() - .len() as i64 + .try_get(0) + .unwrap(); + UserId::from_key(&id.to_string()) +} + +/// Delete a row the way a racing write that lost would have left it: the row +/// gone, its referring rows untouched. Real FKs refuse that state, so the +/// delete is forced the one way Postgres allows: FK triggers suspended for the +/// one transaction. +async fn wipe_row(table: &str, id: uuid::Uuid, db: &Database) { + let mut tx = db.begin().await.unwrap(); + sqlx::query("SET LOCAL session_replication_role = replica") + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query(sqlx::AssertSqlSafe(format!( + "DELETE FROM {table} WHERE id = $1" + ))) + .bind(id) + .execute(&mut *tx) + .await + .unwrap(); + tx.commit().await.unwrap(); } /// 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 { /// the state from a test — and the state the pump's in-transaction claim exists /// to make unreachable in the first place. async fn wipe_course_row(course: &str, db: &Database) { - db.query("DELETE type::record('course', $key)") - .bind(("key", course.to_string())) - .await - .unwrap() - .check() - .unwrap(); + wipe_row( + "course", + uuid::Uuid::parse_str(course).expect("a uuid course id"), + db, + ) + .await; } /// 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) { #[tokio::test] async fn an_attach_onto_a_deleted_course_writes_no_link() { let (_app, db) = app_and_db().await; - let manager = UserId::from_key("manager"); + let manager = fixture_user(&db, "manager").await; let class = class_group::create( &db, &manager, @@ -70,7 +107,7 @@ async fn an_attach_onto_a_deleted_course_writes_no_link() { .unwrap(); // A course id nothing ever created: the same row a delete that won the race // leaves behind. - let ghost = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); + let ghost = CourseId::from_key(GHOST_ID); let refused = class_course::attach(&db, class.get_id(), &ghost, &manager).await; assert!( @@ -78,12 +115,12 @@ async fn an_attach_onto_a_deleted_course_writes_no_link() { "attaching a course that is gone must be refused: {refused:?}" ); assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, + rows("SELECT count(*) FROM class_course", &db).await, 0, "no link row may point at a course that does not exist" ); assert_eq!( - counter("SELECT VALUE class_course_count ?? 0 FROM class_group", &db).await, + counter("SELECT COALESCE(sum(class_course_count), 0)::bigint FROM class_group", &db).await, 0, "…and the class must not count one either, or it is undeletable forever" ); @@ -222,7 +259,7 @@ async fn a_member_add_names_a_stale_link_rather_than_calling_it_full() { refused.body ); assert_eq!( - rows("SELECT VALUE id FROM class_member", &db).await, + rows("SELECT count(*) FROM class_member", &db).await, 0, "a refused add writes nothing" ); @@ -294,7 +331,7 @@ async fn a_hand_enroll_takes_the_row_off_the_class() { "a hand enroll must take the row off the class" ); assert_eq!( - rows("SELECT VALUE id FROM enrollment WHERE source != NONE", &db).await, + rows("SELECT count(*) FROM enrollment WHERE source IS NOT NULL", &db).await, 0, "…in the stored row, not just the response" ); @@ -311,12 +348,12 @@ async fn a_hand_enroll_takes_the_row_off_the_class() { .await; assert_eq!(removed.status, StatusCode::NO_CONTENT); assert_eq!( - rows("SELECT VALUE id FROM enrollment", &db).await, + rows("SELECT count(*) FROM enrollment", &db).await, 1, "the class may not unenroll a student an operator enrolled by hand" ); assert_eq!( - counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await, + counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", &db).await, 1, "…and the seat it never paid for may not be released" ); @@ -362,7 +399,7 @@ async fn a_role_change_sweeps_memberships_and_enrollments_together() { Some(json!({ "user_id": student_id })), ) .await; - assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 1); + assert_eq!(rows("SELECT count(*) FROM enrollment", &db).await, 1); let promoted = send( &app, @@ -374,19 +411,19 @@ async fn a_role_change_sweeps_memberships_and_enrollments_together() { .await; assert_eq!(promoted.status, StatusCode::OK); - assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); + assert_eq!(rows("SELECT count(*) FROM class_member", &db).await, 0); assert_eq!( - rows("SELECT VALUE id FROM enrollment", &db).await, + rows("SELECT count(*) FROM enrollment", &db).await, 0, "a non-student holds no roster row, whoever wrote it" ); assert_eq!( - counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await, + counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", &db).await, 0, "the seat comes back exactly once" ); assert_eq!( - counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await, + counter("SELECT COALESCE(sum(class_member_count), 0)::bigint FROM class_group", &db).await, 0 ); // 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() { // off the (full) counter, and costs no seat. assert_eq!(enroll(first_id.clone()).await.status, StatusCode::OK); assert_eq!( - counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await, + counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", &db).await, 1 ); @@ -480,7 +517,7 @@ async fn the_roster_cap_is_claimed_off_the_live_capacity_column() { assert_eq!(raised.status, StatusCode::OK); assert_eq!(enroll(second_id.clone()).await.status, StatusCode::OK); assert_eq!( - counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await, + counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", &db).await, 2 ); @@ -488,10 +525,9 @@ async fn the_roster_cap_is_claimed_off_the_live_capacity_column() { // conditional write matches nothing either way, and only that path pays for // the read that tells them apart. wipe_course_row(&course, &db).await; - db.query("DELETE enrollment") + sqlx::query("DELETE FROM enrollment") + .execute(&db) .await - .unwrap() - .check() .unwrap(); assert_eq!(enroll(first_id).await.status, StatusCode::NOT_FOUND); } @@ -504,7 +540,7 @@ async fn the_roster_cap_is_claimed_off_the_live_capacity_column() { #[tokio::test] async fn a_roster_is_ordered_by_when_a_student_was_added() { let (_app, db) = app_and_db().await; - let manager = UserId::from_key("manager"); + let manager = fixture_user(&db, "manager").await; let class = class_group::create( &db, &manager, @@ -518,25 +554,27 @@ async fn a_roster_is_ordered_by_when_a_student_was_added() { .get_id() .clone(); - // Keys chosen so `id DESC` (c, b, a) is not the reverse of the insertion - // order (a, c, b): only a real stamp can tell the two apart. The waits are - // what keep the millisecond stamps distinct — a tie falls back to the id, - // which is the very order under test. - let added = ["a", "c", "b"]; - for key in added { - class_member::add(&db, &class, &UserId::from_key(key), &manager) + // Members added in an order no id ordering reproduces: only a real stamp + // can tell the two apart. The waits are what keep the stamps distinct — + // a tie falls back to the id, which is the very order under test. The + // minted rows carry uuid ids, so the assertions read back through the + // name -> id map. + let mut names: Vec<(&str, UserId)> = Vec::new(); + for key in ["a", "c", "b"] { + let member = fixture_user(&db, key).await; + class_member::add(&db, &class, &member, &manager) .await .unwrap(); + names.push((key, member)); tokio::time::sleep(std::time::Duration::from_millis(2)).await; } + let name_of = + |id: &UserId| names.iter().find(|(_, mid)| mid == id).map(|(k, _)| *k).unwrap(); let (roster, _) = class_member::list_for_class(&db, &class, None, 0) .await .unwrap(); - let order: Vec<&str> = roster - .iter() - .map(|member| member.get_user().key()) - .collect(); + let order: Vec<&str> = roster.iter().map(|member| name_of(member.get_user())).collect(); assert_eq!( order, vec!["b", "c", "a"], @@ -547,19 +585,20 @@ async fn a_roster_is_ordered_by_when_a_student_was_added() { // all — the state a real volume is in. It is of unknown age, and NONE // sorting last under DESC is what makes that the oldest, rather than an // invented number putting it anywhere else. - db.query("UPDATE class_member SET added_at = NONE WHERE user = $usr") - .bind(("usr", UserId::from_key("c").record())) - .await - .unwrap() - .check() - .unwrap(); + sqlx::query( + "UPDATE class_member SET added_at = NULL + WHERE app_user = (SELECT id FROM app_user WHERE username = 'c')", + ) + .execute(&db) + .await + .unwrap(); let (roster, _) = class_member::list_for_class(&db, &class, None, 0) .await .unwrap(); assert_eq!( roster .iter() - .map(|member| member.get_user().key()) + .map(|member| name_of(member.get_user())) .collect::>(), vec!["b", "a", "c"], "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() { .get_id() .clone(); - // Courses are ULID-keyed, so their ids rise with creation; attaching them + // Course ids rise with creation (monotonic mint); attaching them // back-to-front makes id order and attach order disagree. let mut courses = Vec::new(); for title in ["first", "second", "third"] { @@ -604,7 +643,7 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() { let (attached, _) = class_course::list_for_class(&db, &class, None, 0) .await .unwrap(); - let order: Vec<&str> = attached + let order: Vec = attached .iter() .map(|link| link.get_course().key()) .collect(); @@ -626,7 +665,7 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() { #[tokio::test] async fn a_class_refuses_the_member_past_its_ceiling() { let (_app, db) = app_and_db().await; - let manager = UserId::from_key("manager"); + let manager = fixture_user(&db, "manager").await; let class = class_group::create( &db, &manager, @@ -639,18 +678,19 @@ async fn a_class_refuses_the_member_past_its_ceiling() { .unwrap() .get_id() .clone(); - db.query("UPDATE $class SET class_member_count = $at") - .bind(("class", class.record())) - .bind(("at", MAX_CLASS_MEMBERS - 1)) + sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2") + .bind(MAX_CLASS_MEMBERS - 1) + .bind(class.clone()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); - class_member::add(&db, &class, &UserId::from_key("last"), &manager) + let last = fixture_user(&db, "last").await; + class_member::add(&db, &class, &last, &manager) .await .expect("the place under the ceiling is still free"); - let refused = class_member::add(&db, &class, &UserId::from_key("over"), &manager).await; + let over = fixture_user(&db, "over").await; + let refused = class_member::add(&db, &class, &over, &manager).await; assert!( matches!(refused, Err(AppError::ConflictCoded { code, ref message }) if code == "class_at_roster_ceiling" @@ -659,22 +699,18 @@ async fn a_class_refuses_the_member_past_its_ceiling() { must name the ceiling the prose does — the roster, not the course list: {refused:?}" ); assert_eq!( - counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await, + counter("SELECT COALESCE(sum(class_member_count), 0)::bigint FROM class_group", &db).await, MAX_CLASS_MEMBERS, "a refused add may not tick the counter past the cap" ); - assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 1); + assert_eq!(rows("SELECT count(*) FROM class_member", &db).await, 1); // And the refusal a *deleted* class earns must stay a 404: both come out of // the same counter claim matching nothing, and only one of them is a // ceiling anybody can make room under. - db.query("DELETE $class") - .bind(("class", class.record())) - .await - .unwrap() - .check() - .unwrap(); - let gone = class_member::add(&db, &class, &UserId::from_key("ghost"), &manager).await; + wipe_row("class_group", class.uuid(), &db).await; + let ghost = fixture_user(&db, "ghost").await; + let gone = class_member::add(&db, &class, &ghost, &manager).await; assert!( matches!(gone, Err(AppError::NotFound)), "a class that is gone is a 404: {gone:?}" @@ -709,12 +745,11 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() { .get_id() .clone(); let algebra = CourseId::from_key(&create_course(&app, &cookie, "algebra").await); - db.query("UPDATE $class SET class_member_count = $over") - .bind(("class", class.record())) - .bind(("over", MAX_CLASS_MEMBERS + 1)) + sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2") + .bind(MAX_CLASS_MEMBERS + 1) + .bind(class.clone()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); 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() { "the refusal must name the axis that is over, not the one with room: {refused:?}" ); assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, + rows("SELECT count(*) FROM class_course", &db).await, 0, "a refused attach may not leave the link behind" ); assert_eq!( - counter("SELECT VALUE class_course_count ?? 0 FROM class_group", &db).await, + counter("SELECT COALESCE(sum(class_course_count), 0)::bigint FROM class_group", &db).await, 0, "…nor tick the axis it was refused on" ); // Back under the ceiling, the very same attach goes through: the refusal is // the standing count, not the class. - db.query("UPDATE $class SET class_member_count = $at") - .bind(("class", class.record())) - .bind(("at", MAX_CLASS_MEMBERS)) + sqlx::query("UPDATE class_group SET class_member_count = $1 WHERE id = $2") + .bind(MAX_CLASS_MEMBERS) + .bind(class.clone()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); class_course::attach(&db, &class, &algebra, &manager) .await @@ -754,7 +788,7 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() { #[tokio::test] async fn a_class_over_the_course_ceiling_takes_no_member() { let (_app, db) = app_and_db().await; - let manager = UserId::from_key("manager"); + let manager = fixture_user(&db, "manager").await; let class = class_group::create( &db, &manager, @@ -767,15 +801,15 @@ async fn a_class_over_the_course_ceiling_takes_no_member() { .unwrap() .get_id() .clone(); - db.query("UPDATE $class SET class_course_count = $over") - .bind(("class", class.record())) - .bind(("over", MAX_CLASS_COURSES + 1)) + sqlx::query("UPDATE class_group SET class_course_count = $1 WHERE id = $2") + .bind(MAX_CLASS_COURSES + 1) + .bind(class.clone()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); - let refused = class_member::add(&db, &class, &UserId::from_key("ali"), &manager).await; + let ali = fixture_user(&db, "ali").await; + let refused = class_member::add(&db, &class, &ali, &manager).await; assert!( matches!(refused, Err(AppError::ConflictCoded { code, ref message }) if code == "class_course_list_too_large" @@ -783,9 +817,9 @@ async fn a_class_over_the_course_ceiling_takes_no_member() { "the refusal must name the courses, not the roster — in its code as well as \ its prose: {refused:?}" ); - assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); + assert_eq!(rows("SELECT count(*) FROM class_member", &db).await, 0); assert_eq!( - counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await, + counter("SELECT COALESCE(sum(class_member_count), 0)::bigint FROM class_group", &db).await, 0 ); } @@ -908,7 +942,7 @@ async fn a_student_or_a_ghost_cannot_be_the_homeroom_teacher() { let manager = login_as(&app, &db, "manager", "manager").await; let student = login_as(&app, &db, "ali", "student").await; let student_id = me_id(&app, &student).await; - let ghost = "01J8XZ0K3Q8G7X2M4N5P6R7S8T"; + let ghost = GHOST_ID; for bad in [student_id.as_str(), ghost] { let refused = send( @@ -922,7 +956,7 @@ async fn a_student_or_a_ghost_cannot_be_the_homeroom_teacher() { assert_eq!(refused.status, StatusCode::BAD_REQUEST, "create with {bad}"); } assert_eq!( - rows("SELECT VALUE id FROM class_group", &db).await, + rows("SELECT count(*) FROM class_group", &db).await, 0, "a refused create may write no class" ); @@ -1249,7 +1283,7 @@ async fn only_staff_and_a_linked_parent_read_another_users_classes() { let ghost = send( &app, "GET", - "/classes/user/01J8XZ0K3Q8G7X2M4N5P6R7S8T", + &format!("/classes/user/{ABSENT_ID}"), Some(&teacher), None, ) @@ -1292,12 +1326,12 @@ async fn a_membership_whose_class_is_gone_is_counted_but_skipped() { } // The guard would refuse this, so it is spelled as the raw row loss it // stands in for; the membership row is deliberately left behind. - db.query("DELETE type::record('class_group', $key)") - .bind(("key", classes[0].clone())) - .await - .unwrap() - .check() - .unwrap(); + wipe_row( + "class_group", + uuid::Uuid::parse_str(&classes[0]).expect("a uuid class id"), + &db, + ) + .await; let res = send(&app, "GET", "/classes/me", Some(&student), None).await; assert_eq!( @@ -1339,28 +1373,38 @@ async fn a_membership_whose_class_is_gone_is_counted_but_skipped() { // single time. Nothing in `src/` knows about it — the seam is the schema, and // these tests are what stop the three `undo_if_demoted` calls being deleted. -/// Demote `user` from inside the next write to `table`, the instant it lands. +/// Demote `user` from inside the next write to `table`, the instant it lands: +/// an AFTER trigger fires inside the write's own transaction, between the +/// handler's role check and its post-write re-read. async fn demote_during_writes_to(table: &str, event: &str, user: &str, db: &Database) { - db.query(format!( - "DEFINE EVENT demote_mid_write ON TABLE {table} WHEN $event = '{event}' THEN {{ \ - UPDATE type::record('user', '{user}') SET role = 'student'; }};" - )) + let firing = match event { + "CREATE" => "INSERT", + "UPDATE" => "UPDATE", + other => panic!("unknown event kind {other}"), + }; + let mut conn = db.acquire().await.expect("acquire for the trigger"); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!( + "CREATE FUNCTION heztest_demote_mid_write() RETURNS trigger AS $$ + BEGIN + UPDATE app_user SET role = 'student' WHERE id = '{user}'; + RETURN NULL; + END; + $$ LANGUAGE plpgsql; + CREATE TRIGGER heztest_demote_mid_write AFTER {firing} ON {table} + FOR EACH ROW EXECUTE FUNCTION heztest_demote_mid_write();" + ))) + .execute(&mut *conn) .await - .unwrap() - .check() - .unwrap(); + .expect("define the demote trigger"); } /// The homeroom teacher's live role, straight out of the store. async fn role_of(user: &str, db: &Database) -> String { - let mut result = db - .query("SELECT VALUE role FROM user WHERE id = type::record('user', $k)") - .bind(("k", user.to_string())) + sqlx::query_scalar("SELECT role FROM app_user WHERE id = $1") + .bind(UserId::from_key(user)) + .fetch_one(db) .await .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap().pop().unwrap() } /// `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() { ); assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired"); assert_eq!( - rows("SELECT VALUE id FROM class_group", &db).await, + rows("SELECT count(*) FROM class_group", &db).await, 0, "the 409 promises nothing was created — so nothing may be there" ); assert_eq!( - counter("SELECT VALUE class_count ?? 0 FROM term", &db).await, + counter("SELECT COALESCE(sum(class_count), 0)::bigint FROM term", &db).await, 0, "…and least of all a reference stranded on the term" ); @@ -1471,12 +1515,12 @@ async fn a_rolled_back_create_at_a_blueprinted_grade_leaves_nothing_behind() { res.body ); assert_eq!( - rows("SELECT VALUE id FROM class_group", &db).await, + rows("SELECT count(*) FROM class_group", &db).await, 0, "the rollback must still have been able to delete the class" ); assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, + rows("SELECT count(*) FROM class_course", &db).await, 0, "…which it only can because nothing was stocked onto it first" ); @@ -1516,8 +1560,8 @@ async fn a_patch_whose_teacher_is_demoted_mid_write_undoes_the_column() { assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired"); assert_eq!( counter( - "SELECT VALUE (IF teacher = NONE { 0 } ELSE { 1 }) FROM class_group", - &db + "SELECT count(*) FROM class_group WHERE teacher IS NOT NULL", + &db, ) .await, 0, @@ -1566,7 +1610,7 @@ async fn a_course_assignment_whose_teacher_is_demoted_mid_write_is_undone() { ); assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired"); assert_eq!( - counter("SELECT VALUE array::len(teachers ?? []) FROM course", &db).await, + counter("SELECT COALESCE(sum(cardinality(teachers)), 0)::bigint FROM course", &db).await, 0, "the assignment must be dropped again, not left granting nothing" ); @@ -1589,15 +1633,21 @@ async fn a_rollback_the_guard_refuses_is_a_500_not_a_lying_409() { let teacher = login_as(&app, &db, "teacher", "teacher").await; let teacher_id = me_id(&app, &teacher).await; - db.query(format!( - "DEFINE EVENT demote_and_occupy ON TABLE class_group WHEN $event = 'CREATE' THEN {{ \ - UPDATE type::record('user', '{teacher_id}') SET role = 'student'; \ - UPDATE $after.id SET class_member_count = 1; }};" - )) + let mut conn = db.acquire().await.expect("acquire for the trigger"); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!( + "CREATE FUNCTION heztest_demote_and_occupy() RETURNS trigger AS $$ + BEGIN + UPDATE app_user SET role = 'student' WHERE id = '{teacher_id}'; + UPDATE class_group SET class_member_count = 1 WHERE id = NEW.id; + RETURN NULL; + END; + $$ LANGUAGE plpgsql; + CREATE TRIGGER heztest_demote_and_occupy AFTER INSERT ON class_group + FOR EACH ROW EXECUTE FUNCTION heztest_demote_and_occupy();" + ))) + .execute(&mut *conn) .await - .unwrap() - .check() - .unwrap(); + .expect("define the demote-and-occupy trigger"); let res = send( &app, @@ -1615,14 +1665,14 @@ async fn a_rollback_the_guard_refuses_is_a_500_not_a_lying_409() { res.body ); assert_eq!( - rows("SELECT VALUE id FROM class_group", &db).await, + rows("SELECT count(*) FROM class_group", &db).await, 1, "the class really is still there — which is why the 409 would have lied" ); assert_eq!( counter( - "SELECT VALUE (IF teacher = NONE { 0 } ELSE { 1 }) FROM class_group", - &db + "SELECT count(*) FROM class_group WHERE teacher IS NOT NULL", + &db, ) .await, 0, @@ -1759,7 +1809,7 @@ async fn a_detach_never_hands_a_row_to_a_class_that_is_gone() { let (app, db) = app_and_db().await; let staff = login_as(&app, &db, "manager", "manager").await; let manager = UserId::from_key(&me_id(&app, &staff).await); - let student = UserId::from_key("student"); + let student = fixture_user(&db, "heir_ogrenci").await; let algebra = CourseId::from_key(&create_course(&app, &staff, "algebra").await); let mut made = Vec::new(); 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() { } let (owner, heir) = (made[0].clone(), made[1].clone()); assert_eq!( - rows( - &format!( - "SELECT VALUE id FROM enrollment WHERE source = class_group:{}", - owner.key() - ), - &db + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM enrollment WHERE source = $1", ) - .await, + .bind(owner.clone()) + .fetch_one(&db) + .await + .unwrap(), 1, "the second attach skips the row the first wrote, so the first owns it" ); // The heir's class row goes while both of its link rows stay: the state a // class deleted out from under its own links leaves. - db.query("DELETE $c") - .bind(("c", heir.record())) - .await - .unwrap() - .check() - .unwrap(); + wipe_row("class_group", heir.uuid(), &db).await; class_course::detach(&db, &owner, &algebra).await.unwrap(); assert_eq!( - rows("SELECT VALUE id FROM enrollment", &db).await, + rows("SELECT count(*) FROM enrollment", &db).await, 0, "a row handed to a class that is not there is one nothing can ever sweep" ); assert_eq!( - counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await, + counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", &db).await, 0, "…and its seat must come back with it" ); diff --git a/tests/regress_course_child_orphans.rs b/tests/regress_course_child_orphans.rs index 45c6080..6b149b2 100644 --- a/tests/regress_course_child_orphans.rs +++ b/tests/regress_course_child_orphans.rs @@ -15,33 +15,23 @@ //! `must_exist` still accepts its id, so a bank template can be //! tagged with a subject nobody can reach. //! -//! All three creates now go through `cap::touch_and_create`, which *moves* the -//! course's roster counter (bumped, gated, put back by captured value) inside -//! the create's own transaction: the write lands on the very record the delete -//! removes, so the store refuses one of the two. `SET x = x` would not do — -//! SurrealDB elides an `UPDATE` that leaves the document unchanged, and an -//! elided write sits in no write set at all. +//! All three creates now go through a claim that locks the course row inside +//! the create's own transaction: the write lands on the very row the delete +//! removes, so the store refuses one of the two. //! //! Two halves, and they are not interchangeable. **This file is the sequential -//! one**: it runs anywhere, on the in-memory engine, and pins the existence -//! contract (a create against a course that is already gone must be a 404, not -//! an orphan) plus the restore (the borrowed counter comes back exactly as it -//! was, or the course is undeletable forever — a worse bug than the one being -//! fixed). +//! one**: it pins the existence contract (a create against a course that is +//! already gone must be a 404, not an orphan) plus the restore (the borrowed +//! counter comes back exactly as it was, or the course is undeletable forever — +//! a worse bug than the one being fixed). //! //! The **race** half drives the real interleaving and lives in-crate, one pin //! per child beside the create it pins — //! `db::exam::tests::an_exam_never_outlives_its_course`, //! `db::course_session::tests::a_session_never_outlives_its_course`, //! `db::subject::tests::a_subject_never_outlives_its_course` — over the -//! shared harness `db::course::assert_no_child_outlives_a_course_delete`. -//! It is `#[ignore]`d and needs a real server, because the subject there *is* -//! the store's conflict detection, which the embedded engine does not have: it -//! commits both sides and answers `Ok` to each, so a race test on `memory` -//! passes over the hole (same reason `domain::class_course`'s twin is ignored). -//! Only in-crate tests can reach `database::init_test_server` and the -//! `RACE_LOCK` that serializes them, and a hand-copied bootstrap here would -//! drift out of the real one silently. +//! shared harness `db::course::assert_no_child_outlives_a_course_delete`, +//! against the same per-test Postgres this file runs on. mod common; @@ -63,16 +53,34 @@ use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::UserId; use hezarfen_backend::error::AppError; use serde_json::json; +use sqlx::Row as _; use tokio::task::JoinHandle; -fn teacher() -> UserId { - UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA") +async fn teacher(db: &Database) -> UserId { + // Creator columns are foreign keys now, so the fixture teacher is a row, + // not a fabricated id. It never logs in, so the hash is a stub. + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, 'doktor', 'x', 'teacher') ON CONFLICT DO NOTHING", + ) + .bind(UserId::generate().uuid()) + .execute(db) + .await + .unwrap(); + let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = 'doktor'") + .fetch_one(db) + .await + .unwrap() + .try_get(0) + .unwrap(); + UserId::from_key(&id.to_string()) } async fn a_course(db: &Database) -> CourseId { + let teacher = teacher(db).await; course::create( db, - &teacher(), + &teacher, CourseTitle::try_new("Fizik").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), @@ -102,10 +110,11 @@ async fn drop_course(course: &CourseId, db: &Database) -> Result fn make_exam(course: CourseId, db: Database) -> JoinHandle> { tokio::spawn(async move { + let teacher = teacher(&db).await; let kinds = Settings::defaults().get_exam_kinds().to_vec(); hezarfen_backend::db::exam::create( &db, - &teacher(), + &teacher, &course, ExamTitle::try_new("quiz").unwrap(), ExamDescription::try_new("").unwrap(), @@ -123,10 +132,11 @@ fn make_exam(course: CourseId, db: Database) -> JoinHandle> fn make_session(course: CourseId, db: Database) -> JoinHandle> { tokio::spawn(async move { + let teacher = teacher(&db).await; db_course_session::create( &db, &course, - &teacher(), + &teacher, SessionTopic::try_new("limits").unwrap(), Timestamp::from_millis(1), None, @@ -151,10 +161,11 @@ fn make_subject(course: CourseId, db: Database) -> JoinHandle JoinHandle> { tokio::spawn(async move { + let teacher = teacher(&db).await; hezarfen_backend::db::course_note::create( &db, &course, - &teacher(), + &teacher, CourseNoteTitle::try_new("plan").unwrap(), CourseNoteContent::try_new("").unwrap(), ) @@ -166,19 +177,13 @@ fn make_note(course: CourseId, db: Database) -> JoinHandle> /// How many rows of `table` name `course`. Stored state, never a return value: /// the whole point is what the store kept. async fn children(table: &str, course: &CourseId, db: &Database) -> usize { - let mut result = db - .query(format!( - "SELECT VALUE id FROM {table} WHERE course = $course" - )) - .bind(("course", course.record())) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .len() + sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!( + "SELECT count(*) FROM {table} WHERE course = $1" + ))) + .bind(course.clone()) + .fetch_one(db) + .await + .unwrap() as usize } // --- the sequential half: the existence contract --------------------------- @@ -191,7 +196,7 @@ async fn a_create_against_a_deleted_course_refuses( table: &str, make: fn(CourseId, Database) -> JoinHandle>, ) { - let db = database::init_mem().await.unwrap(); + let (db, _dbs) = database::init_test_db().await; let course = a_course(&db).await; assert!(drop_course(&course, &db).await.unwrap(), "the course goes"); @@ -227,28 +232,27 @@ async fn a_course_note_under_a_deleted_course_is_refused() { a_create_against_a_deleted_course_refuses("course_note", make_note).await; } -/// The counter the three creates borrow is *given back* — absent stays absent. -/// A bump left behind is not a smaller bug than the orphan it prevents: the -/// course's delete guard is `WHERE (enrollment_count ?? 0) = 0`, so a course -/// that once had an exam created under it would be undeletable forever, and the -/// boot backfill keys on the column being `NONE`. +/// The counter the three creates borrow is *given back*. A bump left behind is +/// not a smaller bug than the orphan it prevents: the course's delete guard +/// reads `enrollment_count`, so a course that once had an exam created under it +/// would be undeletable forever. #[tokio::test] async fn the_creates_give_the_courses_roster_counter_back_untouched() { - let db = database::init_mem().await.unwrap(); + let (db, _dbs) = database::init_test_db().await; let course = a_course(&db).await; - let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE"; for make in [make_exam, make_session, make_subject, make_note] { make(course.clone(), db.clone()).await.unwrap().unwrap(); } - let mut result = db.query(absent).await.unwrap().check().unwrap(); + let bumped = sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM course WHERE enrollment_count <> 0", + ) + .fetch_one(&db) + .await + .unwrap(); assert_eq!( - result - .take::>(0) - .unwrap() - .len(), - 1, - "the borrowed counter must be restored to absent, not to 0" + bumped, 0, + "the borrowed counter must be restored to 0, not left bumped" ); // The proof that matters to a user: the course is still deletable. assert!( @@ -262,12 +266,13 @@ async fn the_creates_give_the_courses_roster_counter_back_untouched() { /// `course_note_file` children with it too, not just itself. #[tokio::test] async fn a_course_note_and_its_files_never_outlive_a_course_delete() { - let db = database::init_mem().await.unwrap(); + let (db, _dbs) = database::init_test_db().await; let course = a_course(&db).await; + let teacher = teacher(&db).await; let note = hezarfen_backend::db::course_note::create( &db, &course, - &teacher(), + &teacher, CourseNoteTitle::try_new("plan").unwrap(), CourseNoteContent::try_new("body").unwrap(), ) @@ -292,18 +297,15 @@ async fn a_course_note_and_its_files_never_outlive_a_course_delete() { 0, "a course_note survived its course's delete" ); - let mut result = db - .query("SELECT VALUE id FROM course_note_file WHERE course_note = $note") - .bind(("note", note.get_id().record())) - .await - .unwrap() - .check() - .unwrap(); + let files = sqlx::query_as::<_, (uuid::Uuid,)>( + "SELECT id FROM course_note_file WHERE course_note = $1", + ) + .bind(note.get_id().clone()) + .fetch_all(&db) + .await + .unwrap(); assert_eq!( - result - .take::>(0) - .unwrap() - .len(), + files.len(), 0, "a course_note_file survived its note's course's delete" ); @@ -316,12 +318,13 @@ async fn a_course_note_and_its_files_never_outlive_a_course_delete() { /// three creates above. #[tokio::test] async fn a_course_note_file_under_a_deleted_note_is_refused() { - let db = database::init_mem().await.unwrap(); + let (db, _dbs) = database::init_test_db().await; let course = a_course(&db).await; + let teacher = teacher(&db).await; let note = hezarfen_backend::db::course_note::create( &db, &course, - &teacher(), + &teacher, CourseNoteTitle::try_new("plan").unwrap(), CourseNoteContent::try_new("").unwrap(), ) @@ -348,29 +351,19 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() { matches!(file, Err(AppError::Conflict(_))), "a file upload under a deleted note must refuse, not {file:?}" ); - let mut result = db - .query("SELECT VALUE id FROM course_note_file WHERE course_note = $note") - .bind(("note", note.get_id().record())) - .await - .unwrap() - .check() - .unwrap(); + let files = sqlx::query_as::<_, (uuid::Uuid,)>( + "SELECT id FROM course_note_file WHERE course_note = $1", + ) + .bind(note.get_id().clone()) + .fetch_all(&db) + .await + .unwrap(); assert_eq!( - result - .take::>(0) - .unwrap() - .len(), + files.len(), 0, "a refused upload left a row naming a note that is gone" ); } - -/// #22, the course's own children over HTTP: a course in an archived term is a -/// past year, so its subjects and course notes (and note files) refuse every -/// write with the coded 409 while all their reads keep answering. The guard -/// sits in each write handler after its authorization check — 403 before 409 — -/// on the `course` the shared loaders already hand back, never inside those -/// loaders, which the read handlers share. #[tokio::test] async fn an_archived_term_freezes_a_course_s_subjects_and_notes() { let (app, db) = app_and_db().await; diff --git a/tests/regress_homework_orphans.rs b/tests/regress_homework_orphans.rs index 108e3da..4b01d61 100644 --- a/tests/regress_homework_orphans.rs +++ b/tests/regress_homework_orphans.rs @@ -13,10 +13,10 @@ //! The lock-level races pin the handlers. //! //! Every race here is judged on the *store*, never on what a request answered: -//! the in-memory engine forges wins under concurrency (src/domain/cap.rs), so a -//! 404 or a 204 is evidence of nothing. The windows are opened by the database -//! itself — a `DEFINE EVENT` on the table under write fires *inside* the -//! writing transaction — rather than by a lucky interleaving. +//! under concurrency a 404 or a 204 is evidence of nothing. The windows are +//! opened by the database itself — an AFTER trigger on the table under write +//! sleeps *inside* the writing transaction — rather than by a lucky +//! interleaving. mod common; @@ -26,44 +26,32 @@ use common::{ id_of, items, login_as, me_id, multipart_file, send, send_raw, unenroll, upload_file_at, }; use hezarfen_backend::database::Database; +use hezarfen_backend::domain::user::UserId; use serde_json::{Value, json}; -use surrealdb::types::RecordId; - -/// `HOMEWORK_LOCK` is process-wide, and every race below holds a lease of it -/// for seconds. Two of them running at once starve each other's window — the -/// second one's gates then run *after* the staging meant to happen inside them, -/// and the test judges an interleaving that never happened. One at a time; the -/// deterministic tests need no ticket. -static ONE_RACE_AT_A_TIME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); +use sqlx::Row as _; /// A due date comfortably clear of the 60s past-scheduling grace. fn far_future() -> i64 { hezarfen_backend::domain::timestamp::Timestamp::now().as_millis() + 7_200_000 } -/// How many rows `sql` selects ids for — the stored state, out of the store. -async fn rows(db: &Database, sql: &str) -> usize { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result.take::>(0).unwrap().len() +/// How many rows `sql` counts — the stored state, out of the store. +async fn rows(db: &Database, sql: &'static str) -> usize { + sqlx::query_scalar::<_, i64>(sql) + .fetch_one(db) + .await + .unwrap() as usize } /// One integer field off one user row, absent counting as zero. async fn counter(db: &Database, user: &str, field: &str) -> i64 { - let mut result = db - .query(format!( - "SELECT VALUE ({field} ?? 0) FROM type::record('user', $key)" - )) - .bind(("key", user.to_string())) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) + sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT COALESCE({field}, 0) FROM app_user WHERE id = $1" + ))) + .bind(UserId::from_key(user)) + .fetch_one(db) + .await + .unwrap() } /// Upload `bytes` onto the caller's submission to `hw` — no assertion. @@ -114,22 +102,25 @@ async fn course_with_student( /// green over the hole. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn an_upload_inside_a_homework_delete_never_orphans() { - let _serial = ONE_RACE_AT_A_TIME.lock().await; let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "ogretmen_odev", "teacher").await; let (course, subject, student, student_id) = course_with_student(&app, &db, &teacher, "fizik").await; let hw = create_homework(&app, &teacher, &course, &subject, "deneme", far_future()).await; - // Hold the delete open once the cascade has run but before it commits. - db.query( - "DEFINE EVENT hold_the_window ON TABLE homework WHEN $event = 'DELETE' \ - THEN { SLEEP 3s; };", + // Hold the delete open once the cascade has run but before it commits: an + // AFTER DELETE trigger sleeping inside the delete's own transaction. + let mut conn = db.acquire().await.expect("acquire for the trigger"); + sqlx::raw_sql( + "CREATE FUNCTION heztest_hold_the_window() RETURNS trigger AS $$ + BEGIN PERFORM pg_sleep(3.0); RETURN NULL; END; + $$ LANGUAGE plpgsql; + CREATE TRIGGER heztest_hold_the_window AFTER DELETE ON homework + FOR EACH ROW EXECUTE FUNCTION heztest_hold_the_window();", ) + .execute(&mut *conn) .await - .expect("define the window event") - .check() - .expect("check the window event"); + .expect("define the window trigger"); let drop_it = { let (app, teacher, hw) = (app.clone(), teacher.clone(), hw.clone()); @@ -176,12 +167,12 @@ async fn an_upload_inside_a_homework_delete_never_orphans() { // Stored state is the whole verdict. assert_eq!( - rows(&db, "SELECT VALUE id FROM homework_submission").await, + rows(&db, "SELECT count(*) FROM homework_submission").await, 0, "a submission outlived its homework" ); assert_eq!( - rows(&db, "SELECT VALUE id FROM homework_file").await, + rows(&db, "SELECT count(*) FROM homework_file").await, 0, "a file outlived its homework" ); @@ -211,7 +202,6 @@ async fn an_upload_inside_a_homework_delete_never_orphans() { /// is committed. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn an_upload_inside_an_audience_patch_is_refused() { - let _serial = ONE_RACE_AT_A_TIME.lock().await; let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "ogretmen_kapsam", "teacher").await; let course = create_course(&app, &teacher, "Coğrafya").await; @@ -241,14 +231,17 @@ async fn an_upload_inside_an_audience_patch_is_refused() { ); let hw = id_of(&res.body); - db.query( - "DEFINE EVENT hold_the_patch ON TABLE homework WHEN $event = 'UPDATE' \ - THEN { SLEEP 3s; };", + let mut conn = db.acquire().await.expect("acquire for the trigger"); + sqlx::raw_sql( + "CREATE FUNCTION heztest_hold_the_patch() RETURNS trigger AS $$ + BEGIN PERFORM pg_sleep(3.0); RETURN NULL; END; + $$ LANGUAGE plpgsql; + CREATE TRIGGER heztest_hold_the_patch AFTER UPDATE ON homework + FOR EACH ROW EXECUTE FUNCTION heztest_hold_the_patch();", ) + .execute(&mut *conn) .await - .expect("define the window event") - .check() - .expect("check the window event"); + .expect("define the window trigger"); let narrowing = { let (app, teacher, hw, kept_id) = @@ -291,12 +284,12 @@ async fn an_upload_inside_an_audience_patch_is_refused() { "a student the homework no longer names must be answered 404" ); assert_eq!( - rows(&db, "SELECT VALUE id FROM homework_submission").await, + rows(&db, "SELECT count(*) FROM homework_submission").await, 0, "a submission landed for a student outside the audience" ); assert_eq!( - rows(&db, "SELECT VALUE id FROM homework_file").await, + rows(&db, "SELECT count(*) FROM homework_file").await, 0, "... with a file on it" ); @@ -347,13 +340,13 @@ async fn a_submission_under_a_vanished_homework_is_refused() { "delete the homework" ); - let refused = upsert(&db, &stale, &user, None).await; + let refused = upsert(&db, &stale, &user, None, false).await; assert!( refused.is_err(), "a submission to a homework that is gone must be refused, got {refused:?}" ); assert_eq!( - rows(&db, "SELECT VALUE id FROM homework_submission").await, + rows(&db, "SELECT count(*) FROM homework_submission").await, 0, "the refused write must leave no row" ); @@ -427,7 +420,7 @@ async fn a_grade_under_a_vanished_homework_is_refused() { "a grade on a homework that is gone must be refused, got {refused:?}" ); assert_eq!( - rows(&db, "SELECT VALUE id FROM homework_result").await, + rows(&db, "SELECT count(*) FROM homework_result").await, 0, "the refused write must leave no row" ); @@ -479,7 +472,6 @@ async fn a_grade_under_a_vanished_homework_is_refused() { /// why it is kept and documented rather than trusted to a red test. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_grade_inside_a_course_delete_never_orphans() { - let _serial = ONE_RACE_AT_A_TIME.lock().await; let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "ogretmen_ders", "teacher").await; let (course, subject, _student, student_id) = @@ -490,14 +482,17 @@ async fn a_grade_inside_a_course_delete_never_orphans() { // seconds against a one-second wait below: under a loaded test binary the // spawned request can take a while to be polled at all, and the window has // to still be open when it gets there. - db.query( - "DEFINE EVENT hold_the_grade ON TABLE homework_result WHEN $event = 'CREATE' \ - THEN { SLEEP 3s; };", + let mut conn = db.acquire().await.expect("acquire for the trigger"); + sqlx::raw_sql( + "CREATE FUNCTION heztest_hold_the_grade() RETURNS trigger AS $$ + BEGIN PERFORM pg_sleep(3.0); RETURN NULL; END; + $$ LANGUAGE plpgsql; + CREATE TRIGGER heztest_hold_the_grade AFTER INSERT ON homework_result + FOR EACH ROW EXECUTE FUNCTION heztest_hold_the_grade();", ) + .execute(&mut *conn) .await - .expect("define the window event") - .check() - .expect("check the window event"); + .expect("define the window trigger"); let grading = { let (app, teacher, hw, target) = @@ -550,12 +545,12 @@ async fn a_grade_inside_a_course_delete_never_orphans() { // Stored state is the whole verdict. assert_eq!( - rows(&db, "SELECT VALUE id FROM homework").await, + rows(&db, "SELECT count(*) FROM homework").await, 0, "the homework survived its course" ); assert_eq!( - rows(&db, "SELECT VALUE id FROM homework_result").await, + rows(&db, "SELECT count(*) FROM homework_result").await, 0, "a grade outlived the homework it was written against" ); @@ -667,7 +662,6 @@ async fn a_student_sees_only_themselves_in_an_assigned_subset() { /// would fail a *correct* implementation too. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_file_add_racing_a_file_delete_never_500s() { - let _serial = ONE_RACE_AT_A_TIME.lock().await; let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "ogretmen_dosya", "teacher").await; let (course, subject, student, _student_id) = @@ -688,14 +682,17 @@ async fn a_file_add_racing_a_file_delete_never_500s() { .await; let first = listed.body["files"][0]["id"].as_str().unwrap().to_string(); - db.query( - "DEFINE EVENT hold_the_delete ON TABLE homework_file WHEN $event = 'DELETE' \ - THEN { SLEEP 150ms; };", + let mut conn = db.acquire().await.expect("acquire for the trigger"); + sqlx::raw_sql( + "CREATE FUNCTION heztest_hold_the_delete() RETURNS trigger AS $$ + BEGIN PERFORM pg_sleep(0.15); RETURN NULL; END; + $$ LANGUAGE plpgsql; + CREATE TRIGGER heztest_hold_the_delete AFTER DELETE ON homework_file + FOR EACH ROW EXECUTE FUNCTION heztest_hold_the_delete();", ) + .execute(&mut *conn) .await - .expect("define the window event") - .check() - .expect("check the window event"); + .expect("define the window trigger"); let removing = { 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() { ); // Whatever the order, the stored count matches the stored rows: the // submission's seat counter is what the cap reads next time. - let files = rows(&db, "SELECT VALUE id FROM homework_file").await; - let mut result = db - .query("SELECT VALUE (file_count ?? 0) FROM homework_submission") + let files = rows(&db, "SELECT count(*) FROM homework_file").await; + let counted: Vec = sqlx::query_scalar("SELECT file_count FROM homework_submission") + .fetch_all(&db) .await - .unwrap() - .check() .unwrap(); - let counted: Vec = result.take(0).unwrap(); assert_eq!( counted.first().copied().unwrap_or(0), files as i64, diff --git a/tests/regress_roles.rs b/tests/regress_roles.rs index 8d63e56..56f05c6 100644 --- a/tests/regress_roles.rs +++ b/tests/regress_roles.rs @@ -2,8 +2,7 @@ //! 2026-08-02 sweep: an event seat a demotion left claimed forever, and the //! two-query deletes that could orphan a child row. //! -//! Every assertion re-reads the *store*. The in-memory engine forges wins under -//! concurrency (src/domain/cap.rs), so nothing below is judged on a response +//! Every assertion re-reads the *store*: nothing below is judged on a response //! body or asked who won a race — the cascade tests drive the reachable half //! and pin what the store holds once the transaction is done. @@ -14,25 +13,17 @@ use common::{app_and_db, id_of, login, login_as, me_id, send}; use hezarfen_backend::database::Database; use hezarfen_backend::domain::timestamp::Timestamp; use serde_json::json; +use sqlx::Row as _; -/// One counter, re-read out of the store — never off a response body. -async fn counter(sql: &str, db: &Database) -> i64 { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) +/// One counter, re-read out of the store — never off a response body. `sql` +/// is a whole scalar query. +async fn counter(sql: &'static str, db: &Database) -> i64 { + sqlx::query_scalar(sql).fetch_one(db).await.unwrap() } -/// How many rows `sql` selects ids for. -async fn rows(sql: &str, db: &Database) -> i64 { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result - .take::>(0) - .unwrap() - .len() as i64 +/// How many rows `sql` counts. +async fn rows(sql: &'static str, db: &Database) -> i64 { + counter(sql, db).await } /// 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) -> /// The API refuses to *schedule* one there (60s grace), so the row is aged in /// the store — the state a real event reaches by the clock simply running on. async fn age_event(event: &str, db: &Database) { - db.query("UPDATE type::record('event', $key) SET starts_at = 1") - .bind(("key", event.to_string())) + sqlx::query("UPDATE event SET starts_at = 1 WHERE id = $1") + .bind(uuid::Uuid::parse_str(event).expect("a uuid event id")) + .execute(db) .await - .unwrap() - .check() .unwrap(); } @@ -109,7 +99,7 @@ async fn a_demotion_frees_the_event_seat_nothing_else_could_free() { let res = seat(&app, &teacher, &event, &ali_id).await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!( - counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", &db).await, 1 ); @@ -126,12 +116,12 @@ async fn a_demotion_frees_the_event_seat_nothing_else_could_free() { // The row goes and the seat comes back with it — one is worthless without // the other. assert_eq!( - rows("SELECT VALUE id FROM registration", &db).await, + rows("SELECT count(*) FROM registration", &db).await, 0, "a non-student may hold no signup row" ); assert_eq!( - counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", &db).await, 0, "the seat must be handed back, or the event is full forever" ); @@ -179,12 +169,12 @@ async fn a_promotion_keeps_the_signup_the_promoted_user_can_still_free() { assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!( - rows("SELECT VALUE id FROM registration", &db).await, + rows("SELECT count(*) FROM registration", &db).await, 1, "a promotion must not destroy a signup its holder can still free" ); assert_eq!( - counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", &db).await, 1, "…and the seat it holds stays claimed with it" ); @@ -205,9 +195,9 @@ async fn a_promotion_keeps_the_signup_the_promoted_user_can_still_free() { .expect("re-login"); let res = free_seat(&app, &promoted, &event, &ali_id).await; assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); - assert_eq!(rows("SELECT VALUE id FROM registration", &db).await, 0); + assert_eq!(rows("SELECT count(*) FROM registration", &db).await, 0); assert_eq!( - counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", &db).await, 0 ); } @@ -247,12 +237,12 @@ async fn a_demotion_leaves_a_frozen_signup_list_exactly_as_it_stands() { assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!( - rows("SELECT VALUE id FROM registration", &db).await, + rows("SELECT count(*) FROM registration", &db).await, 1, "a closed roster must not be rewritten by a role change" ); assert_eq!( - counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", &db).await, 1, "…and its seat stays claimed with it — the row is the seat" ); @@ -285,12 +275,21 @@ async fn the_sweep_deletes_an_orphan_signup_instead_of_stranding_it() { // The state a delete that raced a register used to leave: the row outlives // its event. Written straight into the store, since the cascade now makes // it unreachable through the API. - db.query("DELETE type::record('event', $key)") - .bind(("key", doomed.clone())) + // The state a delete that raced a register used to leave: the row outlives + // its event. Written straight into the store, since the cascade now makes + // it unreachable through the API. Real FKs refuse that state, so the + // delete is forced with FK triggers suspended for the one transaction. + let mut tx = db.begin().await.unwrap(); + sqlx::query("SET LOCAL session_replication_role = replica") + .execute(&mut *tx) .await - .unwrap() - .check() .unwrap(); + sqlx::query("DELETE FROM event WHERE id = $1") + .bind(uuid::Uuid::parse_str(&doomed).expect("a uuid event id")) + .execute(&mut *tx) + .await + .unwrap(); + tx.commit().await.unwrap(); let res = send( &app, @@ -303,12 +302,12 @@ async fn the_sweep_deletes_an_orphan_signup_instead_of_stranding_it() { assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!( - rows("SELECT VALUE id FROM registration", &db).await, + rows("SELECT count(*) FROM registration", &db).await, 0, "an orphan signup must go with the rest — nothing else can ever remove it" ); assert_eq!( - counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await, + counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", &db).await, 0, "and the surviving event still gets its seat back" ); @@ -316,17 +315,11 @@ async fn the_sweep_deletes_an_orphan_signup_instead_of_stranding_it() { /// How many boards list `user` as a participant, read out of the store. async fn boards_listing(user: &str, db: &Database) -> i64 { - let mut result = db - .query("SELECT VALUE id FROM board WHERE type::record('user', $u) IN participants") - .bind(("u", user.to_string())) + sqlx::query_scalar("SELECT count(*) FROM board WHERE $1 = ANY(participants)") + .bind(uuid::Uuid::parse_str(user).expect("a uuid user id")) + .fetch_one(db) .await .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .len() as i64 } /// 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() { ); // Nothing was destroyed, and the board they created is untouched beyond // that: same creator, and its other participant still on it. - assert_eq!(rows("SELECT VALUE id FROM board", &db).await, 2); + assert_eq!(rows("SELECT count(*) FROM board", &db).await, 2); let res = send(&app, "GET", &format!("/boards/{own_id}"), Some(&ali), None).await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!(res.body["creator"], veli_id); @@ -441,34 +434,46 @@ async fn a_student_holding_every_grant( /// `user`'s live role, read out of the store. async fn role_of(user: &str, db: &Database) -> String { - let mut result = db - .query("SELECT VALUE role FROM type::record('user', $u)") - .bind(("u", user.to_string())) + sqlx::query_scalar("SELECT role FROM app_user WHERE id = $1") + .bind(uuid::Uuid::parse_str(user).expect("a uuid user id")) + .fetch_one(db) .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .first() - .cloned() .expect("the user row must exist") } /// Make the next write of `kind` on `table` fail, from inside whatever -/// transaction performs it: a `DEFINE EVENT` on the table under write fires -/// *within* that write, which is the only way to fail one statement of a -/// cascade deterministically (no sleeps, no racing tasks). +/// transaction performs it: a trigger that raises aborts that very write, and +/// with it the whole cascade's transaction — the only way to fail one statement +/// of a cascade deterministically (no sleeps, no racing tasks). async fn poison(table: &str, kind: &str, db: &Database) { - db.query(format!( - "DEFINE EVENT poison ON TABLE {table} WHEN $event = '{kind}' \ - THEN {{ THROW 'poisoned' }}" - )) + let firing = match kind { + "CREATE" => "INSERT", + "UPDATE" => "UPDATE", + "DELETE" => "DELETE", + other => panic!("unknown event kind {other}"), + }; + let mut conn = db.acquire().await.expect("acquire for the trigger"); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!( + "CREATE FUNCTION heztest_poison() RETURNS trigger AS $$ + BEGIN RAISE EXCEPTION 'poisoned'; END; + $$ LANGUAGE plpgsql; + CREATE TRIGGER heztest_poison BEFORE {firing} ON {table} + FOR EACH ROW EXECUTE FUNCTION heztest_poison();" + ))) + .execute(&mut *conn) + .await + .expect("define the poison trigger"); +} + +/// Take the poison back, so the re-sent PATCH can land. +async fn unpoison(table: &str, db: &Database) { + sqlx::raw_sql(sqlx::AssertSqlSafe(format!( + "DROP TRIGGER IF EXISTS heztest_poison ON {table}; + DROP FUNCTION IF EXISTS heztest_poison();" + ))) + .execute(db) .await - .unwrap() - .check() - .unwrap(); + .expect("remove the poison trigger"); } /// 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) { "the role write must roll back with the sweep that failed" ); assert_eq!( - rows("SELECT VALUE id FROM enrollment", db).await, + rows("SELECT count(*) FROM enrollment", db).await, 1, "the enrollment must survive a failed cascade" ); assert_eq!( - counter("SELECT VALUE enrollment_count ?? 0 FROM course", db).await, + counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", db).await, 1, "…and so must its seat, or the roster and the count disagree forever" ); assert_eq!( - rows("SELECT VALUE id FROM parent_link", db).await, + rows("SELECT count(*) FROM parent_link", db).await, 1, "the parent link must survive a failed cascade" ); assert_eq!( - rows("SELECT VALUE id FROM registration", db).await, + rows("SELECT count(*) FROM registration", db).await, 1, "the signup must survive a failed cascade" ); assert_eq!( - counter("SELECT VALUE registration_count ?? 0 FROM event", db).await, + counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", db).await, 1, "…with its seat still claimed" ); @@ -533,18 +538,23 @@ async fn the_retry_takes_everything( assert_eq!(role_of(ali_id, db).await, "parent"); for table in ["enrollment", "parent_link", "registration", "class_member"] { assert_eq!( - rows(&format!("SELECT VALUE id FROM {table}"), db).await, + sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!( + "SELECT count(*) FROM {table}" + ))) + .fetch_one(db) + .await + .unwrap(), 0, "{table} must be swept by the re-sent PATCH" ); } assert_eq!(boards_listing(ali_id, db).await, 0); assert_eq!( - counter("SELECT VALUE enrollment_count ?? 0 FROM course", db).await, + counter("SELECT COALESCE(sum(enrollment_count), 0)::bigint FROM course", db).await, 0 ); assert_eq!( - counter("SELECT VALUE registration_count ?? 0 FROM event", db).await, + counter("SELECT COALESCE(sum(registration_count), 0)::bigint FROM event", db).await, 0 ); // 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( /// enrollment, the parent link and the event seat already gone, and nothing to /// ever put them back. /// -/// The failure is injected the way `regress_classes` does it: a `DEFINE EVENT` -/// on a table the cascade writes fires *inside* that write, so the abort is -/// deterministic instead of a race the in-memory engine would lie about. Both +/// The failure is injected the way `regress_classes` does it: a trigger on a +/// table the cascade writes raises inside that very write, so the abort is +/// deterministic instead of a race. Both /// ends of the cascade are poisoned, in two tests, because they fail different /// things: the board roster is the *last* statement of the parent arm (so every /// 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 ); nothing_was_swept(&ali_id, &db).await; - db.query("REMOVE EVENT poison ON TABLE board") - .await - .unwrap() - .check() - .unwrap(); + unpoison("board", &db).await; the_retry_takes_everything(&app, &db, &admin, &teacher, &ali_id).await; } @@ -630,11 +636,7 @@ async fn a_failure_early_in_the_cascade_rolls_the_role_write_back_with_it() { ); nothing_was_swept(&ali_id, &db).await; - db.query("REMOVE EVENT poison ON TABLE enrollment") - .await - .unwrap() - .check() - .unwrap(); + unpoison("enrollment", &db).await; the_retry_takes_everything(&app, &db, &admin, &teacher, &ali_id).await; } @@ -661,7 +663,7 @@ async fn deleting_an_event_takes_its_children_with_it() { ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(rows("SELECT VALUE id FROM attendance", &db).await, 1); + assert_eq!(rows("SELECT count(*) FROM attendance", &db).await, 1); let res = send( &app, @@ -673,14 +675,14 @@ async fn deleting_an_event_takes_its_children_with_it() { .await; assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); - assert_eq!(rows("SELECT VALUE id FROM event", &db).await, 0); + assert_eq!(rows("SELECT count(*) FROM event", &db).await, 0); assert_eq!( - rows("SELECT VALUE id FROM attendance", &db).await, + rows("SELECT count(*) FROM attendance", &db).await, 0, "no mark may outlive its event" ); assert_eq!( - rows("SELECT VALUE id FROM registration", &db).await, + rows("SELECT count(*) FROM registration", &db).await, 0, "no signup may outlive its event" ); @@ -708,14 +710,14 @@ async fn deleting_a_note_takes_its_attachment_rows_with_it() { let up = common::upload_file(&app, &ali, ¬e, "plan.txt", "text/plain", b"merhaba").await; assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); - assert_eq!(rows("SELECT VALUE id FROM note_file", &db).await, 1); + assert_eq!(rows("SELECT count(*) FROM note_file", &db).await, 1); let res = send(&app, "DELETE", &format!("/notes/{note}"), Some(&ali), None).await; assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); - assert_eq!(rows("SELECT VALUE id FROM note", &db).await, 0); + assert_eq!(rows("SELECT count(*) FROM note", &db).await, 0); assert_eq!( - rows("SELECT VALUE id FROM note_file", &db).await, + rows("SELECT count(*) FROM note_file", &db).await, 0, "no attachment row may outlive its note" );