diff --git a/src/db/subject.rs b/src/db/subject.rs index 71389d8..84bf4b9 100644 --- a/src/db/subject.rs +++ b/src/db/subject.rs @@ -1,13 +1,10 @@ //! The `subject` table: the count-and-create that pins a topic to a live //! course row, the bulk id listing, the field-scoped PATCH, and the guarded -//! delete whose `WHERE` reads the row's own reference counters. The type and +//! delete whose guard reads the row's own reference counters. The type and //! its validation live in [`crate::domain::subject`]. -use surrealdb::types::{RecordId, SurrealValue}; - -use crate::constant::ENROLLMENT_COUNT_FIELD; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; +use crate::constant::SUBJECT_TABLE; +use crate::database::Database; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; use crate::domain::course::CourseId; @@ -26,24 +23,40 @@ pub async fn create( name, description, }; - // The course row is *written* (bumped and put back), not read, so this - // collides with `Course::delete`'s cascade: a topic that outlives its - // course 404s through `subject_with_course` forever, while - // `must_exist` still accepts its id — so a bank template can be - // tagged with a subject nobody can reach. See [`cap::touch_and_create`]. - cap::touch_and_create( - &course.record(), - ENROLLMENT_COUNT_FIELD, - &subject.id.record(), - &subject, - db, + // The course foreign key is the existence proof the old bump-and-restore + // "touch" trick faked: a topic whose course is already gone — or which is + // deleted while this insert is in flight — is refused here, so a subject + // can never outlive its course and a bank template can never be tagged + // with a subject nobody can reach. `23503` is the parent-gone refusal, + // the same answer the touch produced. + let created = sqlx::query_as!( + Subject, + r#"INSERT INTO subject (id, course, name, description, exam_question_count, homework_count) + VALUES ($1, $2, $3, $4, 0, 0) + RETURNING id, course, name, description"#, + subject.id, + subject.course, + subject.name, + subject.description, ) - .await? - .ok_or(AppError::NotFound) + .fetch_one(db) + .await; + match created { + Ok(created) => Ok(created), + Err(err) if crate::database::foreign_key_violation(&err) => Err(AppError::NotFound), + Err(err) => Err(err.into()), + } } pub async fn read(db: &Database, id: &SubjectId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let subject = sqlx::query_as!( + Subject, + r#"SELECT id, course, name, description FROM subject WHERE id = $1"#, + id, + ) + .fetch_optional(db) + .await?; + Ok(subject) } /// Several subjects in one query — the bulk half of a list endpoint that @@ -52,25 +65,27 @@ pub async fn list_by_ids(db: &Database, ids: &[&SubjectId]) -> Result = ids.iter().map(|id| id.record()).collect(); - let mut result = db - .query("SELECT * FROM subject WHERE id IN $ids") - .bind(("ids", records)) - .await? - .check()?; - Ok(result.take::>(0)?) + let keys: Vec = ids.iter().map(|id| **id).collect(); + let rows = sqlx::query_as!( + Subject, + r#"SELECT id, course, name, description FROM subject WHERE id = ANY($1)"#, + keys, + ) + .fetch_all(db) + .await?; + Ok(rows) } -/// The course's subjects in curriculum order (ULID ids sort by creation). +/// The course's subjects in curriculum order (uuid ids sort by creation). pub async fn list_for_course( db: &Database, course: &CourseId, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("subject WHERE course = $course", "ORDER BY id ASC") - .bind("course", course.record()) - .run(limit, offset, db) + PagedList::new("subject WHERE course = $1", "ORDER BY id ASC") + .bind(course.uuid()) + .run::(limit, offset, db) .await } @@ -86,9 +101,9 @@ pub async fn update( name: Option, description: Option, ) -> Result { - FieldUpdate::new(subject.id.record()) - .set("name", name) - .set("description", description) + FieldUpdate::new(SUBJECT_TABLE, subject.id.uuid()) + .set("name", name.map(|name| name.as_str().to_owned())) + .set("description", description.map(|d| d.as_str().to_owned())) .run::(db) .await } @@ -99,72 +114,63 @@ pub async fn update( /// /// Exam questions and homework are *not* cascaded: their `subject` is a /// required field that may not be orphaned, so either one still refuses the -/// delete with a 409. That refusal is the delete's own `WHERE`, read off the -/// two reference counters this row carries -/// ([`crate::constant::SUBJECT_QUESTION_COUNT_FIELD`] and its homework -/// twin), which is what makes it hold against a question created by a -/// request racing this one — the cross-table `SELECT … LIMIT 1` it replaces -/// was a count-then-delete no transaction serializes, pinned by three -/// process-wide locks that could not cover the round trip between them. +/// delete with a 409. That refusal is this transaction's own check, read +/// off the two reference counters this row carries (`exam_question_count` +/// and its homework twin) under a `FOR UPDATE` row lock — the lock *is* +/// the guard, because every counter writer must update this same row, so +/// no question can land between the check and the delete. The old store +/// could not conflict-check the cross-table shape, which is why the check +/// had to be the `DELETE`'s own `WHERE`; here the row lock does it and the +/// check reads the same columns. /// /// Which of the two blocked is read off the counters *before* the delete, /// purely to pick the message; the decision itself was already made by the -/// `WHERE`. +/// check. /// /// The bank's subject is optional metadata, and blocking on it was a dead /// end — only the template's owner may re-tag it, so a manager could never /// clear their own 409, and a private template raising it leaked its -/// existence. Its cascade runs *after* the conditional delete, so a refused +/// existence. Its cascade runs *after* the guarded delete, so a refused /// delete leaves every template's subject where it was. pub async fn delete(db: &Database, subject: Subject) -> Result { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - LET $held = (SELECT exam_question_count AS q, homework_count AS h FROM $sub); - LET $before = (DELETE $sub - WHERE (exam_question_count ?? 0) = 0 AND (homework_count ?? 0) = 0 - RETURN BEFORE); - IF array::len($before) = 0 { - THROW IF array::len($held) = 0 { 'subject_missing' } - ELSE IF ($held[0].q ?? 0) > 0 { 'subject_questions' } - ELSE { 'subject_homework' } - }; - UPDATE bank_question SET subject = NONE WHERE subject = $sub; - RETURN $before; - COMMIT TRANSACTION;", - &[("sub".into(), subject.id.record().into_value())], - &["subject_missing", "subject_questions", "subject_homework"], - ) - .await?; - // An aborted transaction errors every slot; only the THROW's own slot - // names the marker (the [`crate::db::appointment_slot`] treatment), - // and a lost round is re-sent rather than reported. - let thrown = |marker: &str| { - errors - .values() - .any(|error| error.to_string().contains(marker)) - }; - if thrown("subject_questions") { - return Err(AppError::Conflict( - "exam questions still reference this subject — re-tag or delete them first", - )); - } - if thrown("subject_homework") { - return Err(AppError::Conflict( - "homework still references this subject — re-tag or delete it first", - )); - } - if thrown("subject_missing") { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Read through the trailing `RETURN`, not a counted slot — see - // [`crate::db::exam::delete`]. - let slot = result.num_statements().saturating_sub(2); - let deleted: Option = result.take::>(slot)?.into_iter().next(); - deleted.ok_or(AppError::NotFound) + crate::database::tx_with_retry(db, false, async |tx| { + // The pre-image read and the guard in one locked statement: the row + // (and its counters) cannot change under this transaction. + let held = sqlx::query!( + r#"SELECT exam_question_count, homework_count + FROM subject WHERE id = $1 FOR UPDATE"#, + subject.id, + ) + .fetch_optional(&mut *tx) + .await?; + let held = held.ok_or(AppError::NotFound)?; + if held.exam_question_count > 0 { + return Err(AppError::Conflict( + "exam questions still reference this subject — re-tag or delete them first", + )); + } + if held.homework_count > 0 { + return Err(AppError::Conflict( + "homework still references this subject — re-tag or delete it first", + )); + } + let deleted = sqlx::query_as!( + Subject, + r#"DELETE FROM subject WHERE id = $1 + RETURNING id, course, name, description"#, + subject.id, + ) + .fetch_one(&mut *tx) + .await?; + sqlx::query!( + r#"UPDATE bank_question SET subject = NULL WHERE subject = $1"#, + subject.id, + ) + .execute(&mut *tx) + .await?; + Ok(deleted) + }) + .await } #[cfg(test)] diff --git a/src/db/term.rs b/src/db/term.rs index 8b21ac0..6bb8f40 100644 --- a/src/db/term.rs +++ b/src/db/term.rs @@ -4,10 +4,8 @@ //! stamps. The type and the errors its guards hand out live in //! [`crate::domain::term`]. -use surrealdb::types::SurrealValue; - -use crate::constant::{COURSE_COUNT_FIELD, TERM_CLASS_COUNT_FIELD}; -use crate::database::{Database, write_with_retry}; +use crate::constant::TERM_TABLE; +use crate::database::Database; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; use crate::domain::term::{Term, TermId, TermName}; @@ -27,12 +25,30 @@ pub async fn create( ends_at, archived_at: None, }; - let created: Option = db.create(term.id.record()).content(term).await?; - created.ok_or_else(|| AppError::Internal("failed to create term".into())) + let created = sqlx::query_as!( + Term, + r#"INSERT INTO term (id, name, starts_at, ends_at, archived_at) + VALUES ($1, $2, $3, $4, NULL) + RETURNING id, name, starts_at, ends_at, archived_at"#, + term.id, + term.name, + term.starts_at, + term.ends_at, + ) + .fetch_one(db) + .await?; + Ok(created) } pub async fn read(db: &Database, id: &TermId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let term = sqlx::query_as!( + Term, + r#"SELECT id, name, starts_at, ends_at, archived_at FROM term WHERE id = $1"#, + id, + ) + .fetch_optional(db) + .await?; + Ok(term) } /// Every term, newest first — the school calendar is small by nature. @@ -42,7 +58,7 @@ pub async fn list_all( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new("term", "ORDER BY starts_at DESC, id DESC") - .run(limit, offset, db) + .run::(limit, offset, db) .await } @@ -57,10 +73,10 @@ pub async fn update( starts_at: Option, ends_at: Option, ) -> Result { - FieldUpdate::new(term.id.record()) - .set("name", name) - .set("starts_at", starts_at) - .set("ends_at", ends_at) + FieldUpdate::new(TERM_TABLE, term.id.uuid()) + .set("name", name.map(|name| name.as_str().to_owned())) + .set("starts_at", starts_at.map(|at| at.as_millis())) + .set("ends_at", ends_at.map(|at| at.as_millis())) .ordered("starts_at", "ends_at", range_error()) .run::(db) .await @@ -77,20 +93,19 @@ pub async fn update( /// refused itself, with the same 400 the lookup gives). `Err(NotFound)` /// keeps the answer a concurrent *delete* used to get. /// -/// Classes ([`crate::domain::class_group::ClassGroup`]) link a term the same -/// way and count on `class_count` — a column of their own, because -/// `course_count` is seeded at boot from the course rows alone. +/// The referencing foreign keys (`course.term`, `class_group.term`, both +/// `NO ACTION`) are the backstop behind the counters, not a second guard: +/// while the counts are honest the `WHERE` decides every race on its own, +/// because both claim paths lock this very row before they write a link. pub async fn delete(db: &Database, term: Term) -> Result { - let sql = format!( - "DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 \ - AND ({TERM_CLASS_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE" - ); - // Through the retry, because the guard reads the very column a course - // create claims: a lost round writes nothing, and re-sending it is what - // keeps the answer the 404 or 409 it owes instead of a 500. - let gone: Vec = - write_with_retry(db, &sql, &[("term".into(), term.id.record().into_value())]).await?; - if !gone.is_empty() { + let gone = sqlx::query!( + r#"DELETE FROM term + WHERE id = $1 AND course_count = 0 AND class_count = 0"#, + term.id, + ) + .execute(db) + .await?; + if gone.rows_affected() > 0 { return Ok(true); } // Still linked or already gone: the one statement cannot tell those @@ -105,44 +120,39 @@ pub async fn delete(db: &Database, term: Term) -> Result { /// open row, so a repeat archive writes nothing and answers with the /// *original* stamp — the year is not re-dated by a double click. pub async fn archive(db: &Database, term: Term) -> Result { - stamp( - db, - term, - "UPDATE $term SET archived_at = $now WHERE archived_at = NONE RETURN AFTER", - Some(Timestamp::now()), + let written = sqlx::query_as!( + Term, + r#"UPDATE term SET archived_at = $2 + WHERE id = $1 AND archived_at IS NULL + RETURNING id, name, starts_at, ends_at, archived_at"#, + term.id, + Timestamp::now(), ) - .await + .fetch_optional(db) + .await?; + match written { + Some(written) => Ok(written), + // A repeat archive (or a term deleted under the request): the stored + // row is the answer, and only the no-op path pays for the read. + None => read(db, &term.id).await?.ok_or(AppError::NotFound), + } } /// Re-open the term; idempotent the same way. pub async fn unarchive(db: &Database, term: Term) -> Result { - stamp( - db, - term, - "UPDATE $term SET archived_at = NONE WHERE archived_at != NONE RETURN AFTER", - None, + let written = sqlx::query_as!( + Term, + r#"UPDATE term SET archived_at = NULL + WHERE id = $1 AND archived_at IS NOT NULL + RETURNING id, name, starts_at, ends_at, archived_at"#, + term.id, ) - .await -} - -/// One conditional write, through [`write_with_retry`] like every other -/// guarded single statement here; an empty result is the no-op case, and -/// only that path pays for the read that reports the stored row. -async fn stamp( - db: &Database, - term: Term, - sql: &str, - now: Option, -) -> Result { - let mut bindings = vec![("term".into(), term.id.record().into_value())]; - if let Some(now) = now { - bindings.push(("now".into(), now.as_millis().into_value())); - } - let written: Vec = write_with_retry(db, sql, &bindings).await?; - if let Some(written) = written.into_iter().next() { - return Ok(written); + .fetch_optional(db) + .await?; + match written { + Some(written) => Ok(written), + None => read(db, &term.id).await?.ok_or(AppError::NotFound), } - read(db, &term.id).await?.ok_or(AppError::NotFound) } #[cfg(test)] diff --git a/src/domain/course.rs b/src/domain/course.rs index 50c69bb..d74fbc9 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -27,6 +27,12 @@ impl CourseId { pub fn key(&self) -> String { self.0.to_string() } + + /// The inner uuid, for binding the id through the runtime-checked + /// builders ([`crate::db::page::Param`]) whose values are raw uuids. + pub(crate) fn uuid(&self) -> uuid::Uuid { + self.0 + } } #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs index 1d28a16..f444033 100644 --- a/src/domain/course_session.rs +++ b/src/domain/course_session.rs @@ -28,6 +28,12 @@ impl CourseSessionId { pub fn key(&self) -> String { self.0.to_string() } + + /// The inner uuid, for binding the id through the runtime-checked + /// builders ([`crate::db::page::Param`]) whose values are raw uuids. + pub(crate) fn uuid(&self) -> uuid::Uuid { + self.0 + } } #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] diff --git a/src/domain/subject.rs b/src/domain/subject.rs index ce3690a..59180a8 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -34,6 +34,12 @@ impl SubjectId { pub fn key(&self) -> String { self.0.to_string() } + + /// The inner uuid, for binding the id through the runtime-checked + /// builders ([`crate::db::page::Param`]) whose values are raw uuids. + pub(crate) fn uuid(&self) -> Uuid { + self.0 + } } #[derive(Debug, Clone, PartialEq, Eq, Type)] diff --git a/src/domain/term.rs b/src/domain/term.rs index 7e1bec8..bf5a42f 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -34,6 +34,12 @@ impl TermId { pub fn key(&self) -> String { self.0.to_string() } + + /// The inner uuid, for binding the id through the runtime-checked + /// builders ([`crate::db::page::Param`]) whose values are raw uuids. + pub(crate) fn uuid(&self) -> Uuid { + self.0 + } } /// The answer every link to a term that is not there gets — the claim is a