forge
Explore
Log in

Don't you dare go Hollow

wip: L2 port db/term + db/subject to sqlx

Browse files at this commit

7871def3bb17acde9c4a3bc292202587b0c8ceccAhmet Kaan GümüşParent: fcca31c
src/db/subject.rsmodified+97 -91
@@ -1,13 +1,10 @@
1 //! The `subject` table: the count-and-create that pins a topic to a live1 //! The `subject` table: the count-and-create that pins a topic to a live
2 //! course row, the bulk id listing, the field-scoped PATCH, and the guarded2 //! course row, the bulk id listing, the field-scoped PATCH, and the guarded
3-//! delete whose `WHERE` reads the row's own reference counters. The type and3+//! delete whose guard reads the row's own reference counters. The type and
4 //! its validation live in [`crate::domain::subject`].4 //! its validation live in [`crate::domain::subject`].
5 5
6-use surrealdb::types::{RecordId, SurrealValue};6+use crate::constant::SUBJECT_TABLE;
7-7+use crate::database::Database;
8-use crate::constant::ENROLLMENT_COUNT_FIELD;
9-use crate::database::{Database, transaction_with_retry};
10-use crate::db::cap;
11 use crate::db::field_update::FieldUpdate;8 use crate::db::field_update::FieldUpdate;
12 use crate::db::page::PagedList;9 use crate::db::page::PagedList;
13 use crate::domain::course::CourseId;10 use crate::domain::course::CourseId;
@@ -26,24 +23,40 @@ pub async fn create(
26 name,23 name,
27 description,24 description,
28 };25 };
29- // The course row is *written* (bumped and put back), not read, so this26+ // The course foreign key is the existence proof the old bump-and-restore
30- // collides with `Course::delete`'s cascade: a topic that outlives its27+ // "touch" trick faked: a topic whose course is already gone — or which is
31- // course 404s through `subject_with_course` forever, while28+ // deleted while this insert is in flight — is refused here, so a subject
32- // `must_exist` still accepts its id — so a bank template can be29+ // can never outlive its course and a bank template can never be tagged
33- // tagged with a subject nobody can reach. See [`cap::touch_and_create`].30+ // with a subject nobody can reach. `23503` is the parent-gone refusal,
34- cap::touch_and_create(31+ // the same answer the touch produced.
35- &course.record(),32+ let created = sqlx::query_as!(
36- ENROLLMENT_COUNT_FIELD,33+ Subject,
37- &subject.id.record(),34+ r#"INSERT INTO subject (id, course, name, description, exam_question_count, homework_count)
38- &subject,35+ VALUES ($1, $2, $3, $4, 0, 0)
39- db,36+ RETURNING id, course, name, description"#,
37+ subject.id,
38+ subject.course,
39+ subject.name,
40+ subject.description,
40 )41 )
41- .await?42+ .fetch_one(db)
42- .ok_or(AppError::NotFound)43+ .await;
44+ match created {
45+ Ok(created) => Ok(created),
46+ Err(err) if crate::database::foreign_key_violation(&err) => Err(AppError::NotFound),
47+ Err(err) => Err(err.into()),
48+ }
43 }49 }
44 50
45 pub async fn read(db: &Database, id: &SubjectId) -> Result<Option<Subject>, AppError> {51 pub async fn read(db: &Database, id: &SubjectId) -> Result<Option<Subject>, AppError> {
46- Ok(db.select(id.record()).await?)52+ let subject = sqlx::query_as!(
53+ Subject,
54+ r#"SELECT id, course, name, description FROM subject WHERE id = $1"#,
55+ id,
56+ )
57+ .fetch_optional(db)
58+ .await?;
59+ Ok(subject)
47 }60 }
48 61
49 /// Several subjects in one query — the bulk half of a list endpoint that62 /// 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<Vec<Subjec
52 if ids.is_empty() {65 if ids.is_empty() {
53 return Ok(Vec::new());66 return Ok(Vec::new());
54 }67 }
55- let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect();68+ let keys: Vec<SubjectId> = ids.iter().map(|id| **id).collect();
56- let mut result = db69+ let rows = sqlx::query_as!(
57- .query("SELECT * FROM subject WHERE id IN $ids")70+ Subject,
58- .bind(("ids", records))71+ r#"SELECT id, course, name, description FROM subject WHERE id = ANY($1)"#,
59- .await?72+ keys,
60- .check()?;73+ )
61- Ok(result.take::<Vec<Subject>>(0)?)74+ .fetch_all(db)
75+ .await?;
76+ Ok(rows)
62 }77 }
63 78
64-/// The course's subjects in curriculum order (ULID ids sort by creation).79+/// The course's subjects in curriculum order (uuid ids sort by creation).
65 pub async fn list_for_course(80 pub async fn list_for_course(
66 db: &Database,81 db: &Database,
67 course: &CourseId,82 course: &CourseId,
68 limit: Option<i64>,83 limit: Option<i64>,
69 offset: i64,84 offset: i64,
70 ) -> Result<(Vec<Subject>, i64), AppError> {85 ) -> Result<(Vec<Subject>, i64), AppError> {
71- PagedList::new("subject WHERE course = $course", "ORDER BY id ASC")86+ PagedList::new("subject WHERE course = $1", "ORDER BY id ASC")
72- .bind("course", course.record())87+ .bind(course.uuid())
73- .run(limit, offset, db)88+ .run::<Subject>(limit, offset, db)
74 .await89 .await
75 }90 }
76 91
@@ -86,9 +101,9 @@ pub async fn update(
86 name: Option<SubjectName>,101 name: Option<SubjectName>,
87 description: Option<SubjectDescription>,102 description: Option<SubjectDescription>,
88 ) -> Result<Subject, AppError> {103 ) -> Result<Subject, AppError> {
89- FieldUpdate::new(subject.id.record())104+ FieldUpdate::new(SUBJECT_TABLE, subject.id.uuid())
90- .set("name", name)105+ .set("name", name.map(|name| name.as_str().to_owned()))
91- .set("description", description)106+ .set("description", description.map(|d| d.as_str().to_owned()))
92 .run::<Subject>(db)107 .run::<Subject>(db)
93 .await108 .await
94 }109 }
@@ -99,72 +114,63 @@ pub async fn update(
99 ///114 ///
100 /// Exam questions and homework are *not* cascaded: their `subject` is a115 /// Exam questions and homework are *not* cascaded: their `subject` is a
101 /// required field that may not be orphaned, so either one still refuses the116 /// required field that may not be orphaned, so either one still refuses the
102-/// delete with a 409. That refusal is the delete's own `WHERE`, read off the117+/// delete with a 409. That refusal is this transaction's own check, read
103-/// two reference counters this row carries118+/// off the two reference counters this row carries (`exam_question_count`
104-/// ([`crate::constant::SUBJECT_QUESTION_COUNT_FIELD`] and its homework119+/// and its homework twin) under a `FOR UPDATE` row lock — the lock *is*
105-/// twin), which is what makes it hold against a question created by a120+/// the guard, because every counter writer must update this same row, so
106-/// request racing this one — the cross-table `SELECT … LIMIT 1` it replaces121+/// no question can land between the check and the delete. The old store
107-/// was a count-then-delete no transaction serializes, pinned by three122+/// could not conflict-check the cross-table shape, which is why the check
108-/// process-wide locks that could not cover the round trip between them.123+/// had to be the `DELETE`'s own `WHERE`; here the row lock does it and the
124+/// check reads the same columns.
109 ///125 ///
110 /// Which of the two blocked is read off the counters *before* the delete,126 /// Which of the two blocked is read off the counters *before* the delete,
111 /// purely to pick the message; the decision itself was already made by the127 /// purely to pick the message; the decision itself was already made by the
112-/// `WHERE`.128+/// check.
113 ///129 ///
114 /// The bank's subject is optional metadata, and blocking on it was a dead130 /// The bank's subject is optional metadata, and blocking on it was a dead
115 /// end — only the template's owner may re-tag it, so a manager could never131 /// end — only the template's owner may re-tag it, so a manager could never
116 /// clear their own 409, and a private template raising it leaked its132 /// clear their own 409, and a private template raising it leaked its
117-/// existence. Its cascade runs *after* the conditional delete, so a refused133+/// existence. Its cascade runs *after* the guarded delete, so a refused
118 /// delete leaves every template's subject where it was.134 /// delete leaves every template's subject where it was.
119 pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError> {135 pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError> {
120- let (mut result, mut errors) = transaction_with_retry(136+ crate::database::tx_with_retry(db, false, async |tx| {
121- db,137+ // The pre-image read and the guard in one locked statement: the row
122- "BEGIN TRANSACTION;138+ // (and its counters) cannot change under this transaction.
123- LET $held = (SELECT exam_question_count AS q, homework_count AS h FROM $sub);139+ let held = sqlx::query!(
124- LET $before = (DELETE $sub140+ r#"SELECT exam_question_count, homework_count
125- WHERE (exam_question_count ?? 0) = 0 AND (homework_count ?? 0) = 0141+ FROM subject WHERE id = $1 FOR UPDATE"#,
126- RETURN BEFORE);142+ subject.id,
127- IF array::len($before) = 0 {143+ )
128- THROW IF array::len($held) = 0 { 'subject_missing' }144+ .fetch_optional(&mut *tx)
129- ELSE IF ($held[0].q ?? 0) > 0 { 'subject_questions' }145+ .await?;
130- ELSE { 'subject_homework' }146+ let held = held.ok_or(AppError::NotFound)?;
131- };147+ if held.exam_question_count > 0 {
132- UPDATE bank_question SET subject = NONE WHERE subject = $sub;148+ return Err(AppError::Conflict(
133- RETURN $before;149+ "exam questions still reference this subject — re-tag or delete them first",
134- COMMIT TRANSACTION;",150+ ));
135- &[("sub".into(), subject.id.record().into_value())],151+ }
136- &["subject_missing", "subject_questions", "subject_homework"],152+ if held.homework_count > 0 {
137- )153+ return Err(AppError::Conflict(
138- .await?;154+ "homework still references this subject — re-tag or delete it first",
139- // An aborted transaction errors every slot; only the THROW's own slot155+ ));
140- // names the marker (the [`crate::db::appointment_slot`] treatment),156+ }
141- // and a lost round is re-sent rather than reported.157+ let deleted = sqlx::query_as!(
142- let thrown = |marker: &str| {158+ Subject,
143- errors159+ r#"DELETE FROM subject WHERE id = $1
144- .values()160+ RETURNING id, course, name, description"#,
145- .any(|error| error.to_string().contains(marker))161+ subject.id,
146- };162+ )
147- if thrown("subject_questions") {163+ .fetch_one(&mut *tx)
148- return Err(AppError::Conflict(164+ .await?;
149- "exam questions still reference this subject — re-tag or delete them first",165+ sqlx::query!(
150- ));166+ r#"UPDATE bank_question SET subject = NULL WHERE subject = $1"#,
151- }167+ subject.id,
152- if thrown("subject_homework") {168+ )
153- return Err(AppError::Conflict(169+ .execute(&mut *tx)
154- "homework still references this subject — re-tag or delete it first",170+ .await?;
155- ));171+ Ok(deleted)
156- }172+ })
157- if thrown("subject_missing") {173+ .await
158- return Err(AppError::NotFound);
159- }
160- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
161- return Err(error.into());
162- }
163- // Read through the trailing `RETURN`, not a counted slot — see
164- // [`crate::db::exam::delete`].
165- let slot = result.num_statements().saturating_sub(2);
166- let deleted: Option<Subject> = result.take::<Vec<Subject>>(slot)?.into_iter().next();
167- deleted.ok_or(AppError::NotFound)
168 }174 }
169 175
170 #[cfg(test)]176 #[cfg(test)]
src/db/term.rsmodified+66 -56
@@ -4,10 +4,8 @@
4 //! stamps. The type and the errors its guards hand out live in4 //! stamps. The type and the errors its guards hand out live in
5 //! [`crate::domain::term`].5 //! [`crate::domain::term`].
6 6
7-use surrealdb::types::SurrealValue;7+use crate::constant::TERM_TABLE;
8-8+use crate::database::Database;
9-use crate::constant::{COURSE_COUNT_FIELD, TERM_CLASS_COUNT_FIELD};
10-use crate::database::{Database, write_with_retry};
11 use crate::db::field_update::FieldUpdate;9 use crate::db::field_update::FieldUpdate;
12 use crate::db::page::PagedList;10 use crate::db::page::PagedList;
13 use crate::domain::term::{Term, TermId, TermName};11 use crate::domain::term::{Term, TermId, TermName};
@@ -27,12 +25,30 @@ pub async fn create(
27 ends_at,25 ends_at,
28 archived_at: None,26 archived_at: None,
29 };27 };
30- let created: Option<Term> = db.create(term.id.record()).content(term).await?;28+ let created = sqlx::query_as!(
31- created.ok_or_else(|| AppError::Internal("failed to create term".into()))29+ Term,
30+ r#"INSERT INTO term (id, name, starts_at, ends_at, archived_at)
31+ VALUES ($1, $2, $3, $4, NULL)
32+ RETURNING id, name, starts_at, ends_at, archived_at"#,
33+ term.id,
34+ term.name,
35+ term.starts_at,
36+ term.ends_at,
37+ )
38+ .fetch_one(db)
39+ .await?;
40+ Ok(created)
32 }41 }
33 42
34 pub async fn read(db: &Database, id: &TermId) -> Result<Option<Term>, AppError> {43 pub async fn read(db: &Database, id: &TermId) -> Result<Option<Term>, AppError> {
35- Ok(db.select(id.record()).await?)44+ let term = sqlx::query_as!(
45+ Term,
46+ r#"SELECT id, name, starts_at, ends_at, archived_at FROM term WHERE id = $1"#,
47+ id,
48+ )
49+ .fetch_optional(db)
50+ .await?;
51+ Ok(term)
36 }52 }
37 53
38 /// Every term, newest first — the school calendar is small by nature.54 /// Every term, newest first — the school calendar is small by nature.
@@ -42,7 +58,7 @@ pub async fn list_all(
42 offset: i64,58 offset: i64,
43 ) -> Result<(Vec<Term>, i64), AppError> {59 ) -> Result<(Vec<Term>, i64), AppError> {
44 PagedList::new("term", "ORDER BY starts_at DESC, id DESC")60 PagedList::new("term", "ORDER BY starts_at DESC, id DESC")
45- .run(limit, offset, db)61+ .run::<Term>(limit, offset, db)
46 .await62 .await
47 }63 }
48 64
@@ -57,10 +73,10 @@ pub async fn update(
57 starts_at: Option<Timestamp>,73 starts_at: Option<Timestamp>,
58 ends_at: Option<Timestamp>,74 ends_at: Option<Timestamp>,
59 ) -> Result<Term, AppError> {75 ) -> Result<Term, AppError> {
60- FieldUpdate::new(term.id.record())76+ FieldUpdate::new(TERM_TABLE, term.id.uuid())
61- .set("name", name)77+ .set("name", name.map(|name| name.as_str().to_owned()))
62- .set("starts_at", starts_at)78+ .set("starts_at", starts_at.map(|at| at.as_millis()))
63- .set("ends_at", ends_at)79+ .set("ends_at", ends_at.map(|at| at.as_millis()))
64 .ordered("starts_at", "ends_at", range_error())80 .ordered("starts_at", "ends_at", range_error())
65 .run::<Term>(db)81 .run::<Term>(db)
66 .await82 .await
@@ -77,20 +93,19 @@ pub async fn update(
77 /// refused itself, with the same 400 the lookup gives). `Err(NotFound)`93 /// refused itself, with the same 400 the lookup gives). `Err(NotFound)`
78 /// keeps the answer a concurrent *delete* used to get.94 /// keeps the answer a concurrent *delete* used to get.
79 ///95 ///
80-/// Classes ([`crate::domain::class_group::ClassGroup`]) link a term the same96+/// The referencing foreign keys (`course.term`, `class_group.term`, both
81-/// way and count on `class_count` — a column of their own, because97+/// `NO ACTION`) are the backstop behind the counters, not a second guard:
82-/// `course_count` is seeded at boot from the course rows alone.98+/// while the counts are honest the `WHERE` decides every race on its own,
99+/// because both claim paths lock this very row before they write a link.
83 pub async fn delete(db: &Database, term: Term) -> Result<bool, AppError> {100 pub async fn delete(db: &Database, term: Term) -> Result<bool, AppError> {
84- let sql = format!(101+ let gone = sqlx::query!(
85- "DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 \102+ r#"DELETE FROM term
86- AND ({TERM_CLASS_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE"103+ WHERE id = $1 AND course_count = 0 AND class_count = 0"#,
87- );104+ term.id,
88- // Through the retry, because the guard reads the very column a course105+ )
89- // create claims: a lost round writes nothing, and re-sending it is what106+ .execute(db)
90- // keeps the answer the 404 or 409 it owes instead of a 500.107+ .await?;
91- let gone: Vec<Term> =108+ if gone.rows_affected() > 0 {
92- write_with_retry(db, &sql, &[("term".into(), term.id.record().into_value())]).await?;
93- if !gone.is_empty() {
94 return Ok(true);109 return Ok(true);
95 }110 }
96 // Still linked or already gone: the one statement cannot tell those111 // Still linked or already gone: the one statement cannot tell those
@@ -105,44 +120,39 @@ pub async fn delete(db: &Database, term: Term) -> Result<bool, AppError> {
105 /// open row, so a repeat archive writes nothing and answers with the120 /// open row, so a repeat archive writes nothing and answers with the
106 /// *original* stamp — the year is not re-dated by a double click.121 /// *original* stamp — the year is not re-dated by a double click.
107 pub async fn archive(db: &Database, term: Term) -> Result<Term, AppError> {122 pub async fn archive(db: &Database, term: Term) -> Result<Term, AppError> {
108- stamp(123+ let written = sqlx::query_as!(
109- db,124+ Term,
110- term,125+ r#"UPDATE term SET archived_at = $2
111- "UPDATE $term SET archived_at = $now WHERE archived_at = NONE RETURN AFTER",126+ WHERE id = $1 AND archived_at IS NULL
112- Some(Timestamp::now()),127+ RETURNING id, name, starts_at, ends_at, archived_at"#,
128+ term.id,
129+ Timestamp::now(),
113 )130 )
114- .await131+ .fetch_optional(db)
132+ .await?;
133+ match written {
134+ Some(written) => Ok(written),
135+ // A repeat archive (or a term deleted under the request): the stored
136+ // row is the answer, and only the no-op path pays for the read.
137+ None => read(db, &term.id).await?.ok_or(AppError::NotFound),
138+ }
115 }139 }
116 140
117 /// Re-open the term; idempotent the same way.141 /// Re-open the term; idempotent the same way.
118 pub async fn unarchive(db: &Database, term: Term) -> Result<Term, AppError> {142 pub async fn unarchive(db: &Database, term: Term) -> Result<Term, AppError> {
119- stamp(143+ let written = sqlx::query_as!(
120- db,144+ Term,
121- term,145+ r#"UPDATE term SET archived_at = NULL
122- "UPDATE $term SET archived_at = NONE WHERE archived_at != NONE RETURN AFTER",146+ WHERE id = $1 AND archived_at IS NOT NULL
123- None,147+ RETURNING id, name, starts_at, ends_at, archived_at"#,
148+ term.id,
124 )149 )
125- .await150+ .fetch_optional(db)
126-}151+ .await?;
127-152+ match written {
128-/// One conditional write, through [`write_with_retry`] like every other153+ Some(written) => Ok(written),
129-/// guarded single statement here; an empty result is the no-op case, and154+ None => read(db, &term.id).await?.ok_or(AppError::NotFound),
130-/// only that path pays for the read that reports the stored row.
131-async fn stamp(
132- db: &Database,
133- term: Term,
134- sql: &str,
135- now: Option<Timestamp>,
136-) -> Result<Term, AppError> {
137- let mut bindings = vec![("term".into(), term.id.record().into_value())];
138- if let Some(now) = now {
139- bindings.push(("now".into(), now.as_millis().into_value()));
140- }
141- let written: Vec<Term> = write_with_retry(db, sql, &bindings).await?;
142- if let Some(written) = written.into_iter().next() {
143- return Ok(written);
144 }155 }
145- read(db, &term.id).await?.ok_or(AppError::NotFound)
146 }156 }
147 157
148 #[cfg(test)]158 #[cfg(test)]
src/domain/course.rsmodified+6 -0
@@ -27,6 +27,12 @@ impl CourseId {
27 pub fn key(&self) -> String {27 pub fn key(&self) -> String {
28 self.0.to_string()28 self.0.to_string()
29 }29 }
30+
31+ /// The inner uuid, for binding the id through the runtime-checked
32+ /// builders ([`crate::db::page::Param`]) whose values are raw uuids.
33+ pub(crate) fn uuid(&self) -> uuid::Uuid {
34+ self.0
35+ }
30 }36 }
31 37
32 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]38 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
src/domain/course_session.rsmodified+6 -0
@@ -28,6 +28,12 @@ impl CourseSessionId {
28 pub fn key(&self) -> String {28 pub fn key(&self) -> String {
29 self.0.to_string()29 self.0.to_string()
30 }30 }
31+
32+ /// The inner uuid, for binding the id through the runtime-checked
33+ /// builders ([`crate::db::page::Param`]) whose values are raw uuids.
34+ pub(crate) fn uuid(&self) -> uuid::Uuid {
35+ self.0
36+ }
31 }37 }
32 38
33 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]39 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
src/domain/subject.rsmodified+6 -0
@@ -34,6 +34,12 @@ impl SubjectId {
34 pub fn key(&self) -> String {34 pub fn key(&self) -> String {
35 self.0.to_string()35 self.0.to_string()
36 }36 }
37+
38+ /// The inner uuid, for binding the id through the runtime-checked
39+ /// builders ([`crate::db::page::Param`]) whose values are raw uuids.
40+ pub(crate) fn uuid(&self) -> Uuid {
41+ self.0
42+ }
37 }43 }
38 44
39 #[derive(Debug, Clone, PartialEq, Eq, Type)]45 #[derive(Debug, Clone, PartialEq, Eq, Type)]
src/domain/term.rsmodified+6 -0
@@ -34,6 +34,12 @@ impl TermId {
34 pub fn key(&self) -> String {34 pub fn key(&self) -> String {
35 self.0.to_string()35 self.0.to_string()
36 }36 }
37+
38+ /// The inner uuid, for binding the id through the runtime-checked
39+ /// builders ([`crate::db::page::Param`]) whose values are raw uuids.
40+ pub(crate) fn uuid(&self) -> Uuid {
41+ self.0
42+ }
37 }43 }
38 44
39 /// The answer every link to a term that is not there gets — the claim is a45 /// The answer every link to a term that is not there gets — the claim is a