From ec9e1313bbfbf6be4ea2892a3c6b9fd8f1e21712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 13:58:40 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A7=20wip:=20macro=20repair=20round=20?= =?UTF-8?q?1=20(R1-R4=20partial;=20269=20errors=20left)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ai/server.rs | 2 +- src/db/answer_image.rs | 40 +++---- src/db/appointment.rs | 12 ++- src/db/appointment_slot.rs | 30 ++++-- src/db/attendance.rs | 2 +- src/db/badge.rs | 12 ++- src/db/bank_question.rs | 107 +++++++++++++------ src/db/bank_question_image.rs | 52 +++++---- src/db/board.rs | 120 +++++++++++++++------ src/db/board_stroke.rs | 53 +++++---- src/db/chatbot_thread.rs | 12 +-- src/db/class_blueprint.rs | 4 +- src/db/class_group.rs | 36 ++++--- src/db/class_pump.rs | 93 +++++++--------- src/db/course.rs | 177 +++++++++++++++++++------------ src/db/course_note.rs | 38 ++++--- src/db/course_note_file.rs | 40 ++++--- src/db/course_session.rs | 30 +++--- src/db/dietary_profile.rs | 16 +-- src/db/enrollment.rs | 37 ++++--- src/db/event.rs | 12 +-- src/db/exam.rs | 152 +++++++++++++------------- src/db/exam_answer.rs | 54 +++++----- src/db/exam_attempt.rs | 92 ++++++++-------- src/db/exam_question.rs | 117 +++++++++++--------- src/db/exam_result.rs | 48 ++++----- src/db/fee_plan.rs | 31 +++--- src/db/fee_plan_assignment.rs | 26 ++--- src/db/field_update.rs | 128 +++++++++++----------- src/db/meal_attendance.rs | 20 ++-- src/db/meal_booking.rs | 106 ++++++++++-------- src/db/meal_ledger.rs | 31 +++--- src/db/menu.rs | 18 ++-- src/db/menu_dish.rs | 45 ++++---- src/db/message.rs | 20 ++-- src/db/note.rs | 33 +++--- src/db/note_file.rs | 27 ++--- src/db/parent_link.rs | 2 +- src/db/payment_ledger.rs | 55 ++++++---- src/db/pomodoro.rs | 7 +- src/db/pool_question.rs | 112 ++++++++++++++----- src/db/question_image.rs | 49 +++++---- src/db/rag_output.rs | 55 ++++++---- src/db/registration.rs | 5 +- src/db/session.rs | 10 +- src/db/session_attendance.rs | 53 +++++---- src/db/settings.rs | 60 ++++++++--- src/db/solution.rs | 74 +++++++++---- src/db/subject.rs | 34 +++--- src/db/term.rs | 34 +++--- src/db/user.rs | 38 ++++--- src/db/work_entry.rs | 38 +++---- src/domain/appointment.rs | 1 - src/domain/appointment_slot.rs | 1 - src/domain/bank_question.rs | 8 ++ src/domain/chatbot_message.rs | 1 - src/domain/chatbot_thread.rs | 1 - src/domain/event.rs | 5 +- src/domain/exam.rs | 1 - src/domain/exam_question.rs | 1 - src/domain/fee_plan.rs | 1 - src/domain/meal_ledger.rs | 2 +- src/domain/registration.rs | 4 +- src/domain/session_attendance.rs | 4 +- src/rate_limit.rs | 26 +++-- src/service/appointment.rs | 11 +- src/service/exam.rs | 2 + src/service/exam_attempt.rs | 1 - src/service/meal_booking.rs | 5 +- src/service/payment_ledger.rs | 52 +++++---- src/service/settings.rs | 14 +-- src/web/appointments.rs | 2 +- src/web/attendance.rs | 6 +- src/web/bank_questions.rs | 12 ++- src/web/board_ws.rs | 12 +-- src/web/boards.rs | 4 +- src/web/chatbot.rs | 2 +- src/web/classes.rs | 4 +- src/web/course_notes.rs | 8 +- src/web/courses.rs | 2 +- src/web/events.rs | 10 +- src/web/exam_ws.rs | 13 ++- src/web/exams/attempts.rs | 24 ++--- src/web/exams/mod.rs | 4 +- src/web/exams/questions.rs | 4 +- src/web/marks.rs | 4 +- src/web/meals.rs | 12 +-- src/web/messages.rs | 2 +- src/web/notes.rs | 8 +- src/web/page.rs | 4 +- src/web/payments.rs | 9 +- src/web/questions.rs | 2 +- src/web/sessions.rs | 4 +- src/web/users.rs | 4 +- 94 files changed, 1628 insertions(+), 1168 deletions(-) diff --git a/src/ai/server.rs b/src/ai/server.rs index 2e43167..26cbcfe 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -646,7 +646,7 @@ async fn open_blob( // The row exists but its blob does not: server-side damage (a lost volume // path), exactly as `download_file` reads it — not the service's `404`. - let path = blob_path(&api.files_dir(&slug), file.get_id().key()); + let path = blob_path(&api.files_dir(&slug), &file.get_id().key()); let handle = tokio::fs::File::open(&path).await.map_err(|e| { ( "unavailable", diff --git a/src/db/answer_image.rs b/src/db/answer_image.rs index b1ed360..97defb0 100644 --- a/src/db/answer_image.rs +++ b/src/db/answer_image.rs @@ -44,7 +44,7 @@ pub async fn upsert( db: &Database, image: AnswerImage, ) -> Result<(AnswerImage, Option), AppError> { - tx_with_retry(db, false, async |conn| upsert_in(conn, image).await).await + tx_with_retry(db, false, async |conn| upsert_in(conn, &image).await).await } /// The locked exam-row probe plus the upsert, on one connection. @@ -54,7 +54,7 @@ pub(crate) async fn upsert_in( ) -> Result<(AnswerImage, Option), AppError> { let touched = sqlx::query!( r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, - image.exam as &ExamId, + image.exam.uuid(), ) .fetch_optional(&mut *conn) .await?; @@ -64,8 +64,8 @@ pub(crate) async fn upsert_in( let replaced = sqlx::query!( r#"SELECT file FROM answer_image WHERE question = $1 AND app_user = $2 AND seq = $3"#, - image.question as &ExamQuestionId, - image.user as &UserId, + image.question.uuid(), + image.user.uuid(), image.seq, ) .fetch_optional(&mut *conn) @@ -81,11 +81,11 @@ pub(crate) async fn upsert_in( RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", app_user AS "user: UserId", seq, file, content_type AS "content_type: FileContentType", size"#, - image.exam as &ExamId, - image.question as &ExamQuestionId, - image.user as &UserId, + image.exam.uuid(), + image.question.uuid(), + image.user.uuid(), image.file, - image.content_type, + image.content_type.as_str(), image.size, image.seq, ) @@ -108,8 +108,8 @@ pub async fn read( content_type AS "content_type: FileContentType", size FROM answer_image WHERE question = $1 AND app_user = $2 AND seq = $3"#, - question as &ExamQuestionId, - user as &UserId, + question.uuid(), + user.uuid(), seq, ) .fetch_optional(db) @@ -124,7 +124,7 @@ pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result Result Result<(), AppError> { sqlx::query!( r#"DELETE FROM answer_image WHERE exam = $1 AND app_user = $2"#, - exam as &ExamId, - user as &UserId, + exam.uuid(), + user.uuid(), ) .execute(db) .await?; diff --git a/src/db/appointment.rs b/src/db/appointment.rs index f78c047..1741643 100644 --- a/src/db/appointment.rs +++ b/src/db/appointment.rs @@ -177,7 +177,8 @@ pub async fn list_for_teacher( ) .fetch_all(db) .await?; - Ok((rows, rows.len() as i64)) + let total = rows.len() as i64; + Ok((rows, total)) } Some(limit) => { let rows = query_as!( @@ -208,7 +209,8 @@ pub async fn list_for_teacher( ) .fetch_one(db) .await? - .total; + .total + .unwrap_or(0); Ok((rows, total)) } } @@ -313,8 +315,10 @@ pub async fn save_if_unchanged( expected: &Appointment, new: Appointment, ) -> Result, AppError> { - tx_with_retry(db, false, async |tx| { - decision_cas(&mut *tx, expected, new.clone()).await + // Owned capture (`Send` rule of `tx_with_retry` closures). + let expected = expected.clone(); + tx_with_retry(db, false, async move |tx| { + decision_cas(&mut *tx, &expected, new.clone()).await }) .await } diff --git a/src/db/appointment_slot.rs b/src/db/appointment_slot.rs index ee23ab7..202c62e 100644 --- a/src/db/appointment_slot.rs +++ b/src/db/appointment_slot.rs @@ -47,7 +47,12 @@ pub async fn insert_claimed( rows: Vec, overlap_refusal: AppError, ) -> Result, AppError> { - tx_with_retry(db, false, async |tx| { + // `Option::take` makes the FnMut move legal: a refusal is terminal + // (never retried), so the value is taken at most once. + let mut overlap_refusal = Some(overlap_refusal); + // Owned capture (`Send` rule of `tx_with_retry` closures). + let teacher = *teacher; + tx_with_retry(db, false, async move |tx| { // The role handshake. The bar is read off the hierarchy rather than // spelled out, so a new role cannot drift out of it. let held = sqlx::query!( @@ -69,7 +74,7 @@ pub async fn insert_claimed( )); } let mut saved = Vec::with_capacity(rows.len()); - for row in rows { + for row in &rows { match query_as!( AppointmentSlot, "INSERT INTO appointment_slot (id, teacher, starts_at, ends_at, note, series, created_at) @@ -92,7 +97,9 @@ pub async fn insert_claimed( // A teacher cannot publish two overlapping windows: the // exclusion constraint, answering the caller's overlap 409. Err(err) if unique_violation(&err) == Some("appointment_slot_teacher_span") => { - return Err(overlap_refusal); + return Err(overlap_refusal.take().unwrap_or_else(|| { + AppError::Internal("overlap refusal re-raised".into()) + })); } Err(err) => return Err(err.into()), } @@ -246,21 +253,22 @@ pub async fn list_for_series( /// occupied rows are still there, a vanished one is not — which is the /// 409/404 the caller expects. pub async fn delete_free(db: &Database, ids: &[AppointmentSlotId]) -> Result<(), AppError> { - tx_with_retry(db, false, async |tx| { + let ids: Vec = ids.iter().map(|id| id.uuid()).collect(); + tx_with_retry(db, false, async move |tx| { // The settled bookings of the *free* slots go first; a booked slot's // rows survive (its occupied counter excludes it from both sweeps). sqlx::query!( "DELETE FROM appointment a USING appointment_slot s WHERE a.slot = s.id AND s.id = ANY($1) AND s.occupied < 1", - ids + &ids ) .execute(&mut *tx) .await?; - let gone: Vec = query_as!( - AppointmentSlotId, - "DELETE FROM appointment_slot WHERE id = ANY($1) AND occupied < 1 RETURNING id", - ids + let gone: Vec = sqlx::query_scalar!( + "DELETE FROM appointment_slot WHERE id = ANY($1) AND occupied < 1 \ + RETURNING id AS \"id: AppointmentSlotId\"", + &ids ) .fetch_all(&mut *tx) .await?; @@ -270,8 +278,8 @@ pub async fn delete_free(db: &Database, ids: &[AppointmentSlotId]) -> Result<(), // Shortfall: distinguish "a live booking holds one" from "one was // never there" off what still exists. let remaining = sqlx::query!( - "SELECT count(*) AS standing FROM appointment_slot WHERE id = ANY($1)", - ids + "SELECT count(*) AS \"standing!\" FROM appointment_slot WHERE id = ANY($1)", + &ids ) .fetch_one(&mut *tx) .await? diff --git a/src/db/attendance.rs b/src/db/attendance.rs index 9460044..54d7d5b 100644 --- a/src/db/attendance.rs +++ b/src/db/attendance.rs @@ -32,7 +32,7 @@ pub async fn mark( VALUES ($1, $2, $3, $4) ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4 RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \ - status, marked_by AS \"marked_by: UserId\"", + status AS \"status: AttendanceStatus\", marked_by AS \"marked_by: UserId\"", event.uuid(), user.uuid(), status.as_str(), diff --git a/src/db/badge.rs b/src/db/badge.rs index adc4a18..2eb590c 100644 --- a/src/db/badge.rs +++ b/src/db/badge.rs @@ -4,6 +4,8 @@ //! those are is [`crate::domain::badge::earned`] — pure, no I/O — and the //! service wrappers the web layer calls live in [`crate::service::badge`]. +use sqlx::AssertSqlSafe; + use crate::constant::{BADGE_AWARD_TABLE, BADGES}; use crate::database::Database; use crate::domain::badge::{BadgeAward, BadgeStats}; @@ -55,17 +57,17 @@ pub async fn load(db: &Database, user: &UserId) -> Result /// but spelled as the projected column on purpose, because it is the /// *served* order, not an internal one. pub async fn list_for(db: &Database, user: &UserId) -> Result, AppError> { - let ids: Vec<&str> = BADGES.iter().map(|(id, ..)| *id).collect(); + let ids: Vec = BADGES.iter().map(|(id, ..)| (*id).to_string()).collect(); let awards = sqlx::query_as!( BadgeAward, r#"SELECT badge, - earned_at AS "earned_at: Timestamp" + earned_at AS "earned_at!: Timestamp" FROM badge_award WHERE app_user = $1 AND badge = ANY($2) ORDER BY earned_at ASC, badge ASC LIMIT $3"#, user.uuid(), - ids, + &ids, BADGES.len() as i64, ) .fetch_all(db) @@ -102,13 +104,13 @@ pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> { } let now = Timestamp::now().as_millis(); for badge in earned { - sqlx::query(&format!( + sqlx::query(AssertSqlSafe(format!( "INSERT INTO {BADGE_AWARD_TABLE} (app_user, badge, earned_at) \ VALUES ($1, $2, $3) \ ON CONFLICT (app_user, badge) DO UPDATE \ SET earned_at = badge_award.earned_at \ WHERE badge_award.earned_at IS NULL" - )) + ))) .bind(user.uuid()) .bind(badge) .bind(now) diff --git a/src/db/bank_question.rs b/src/db/bank_question.rs index 8b8c63e..a9a39f3 100644 --- a/src/db/bank_question.rs +++ b/src/db/bank_question.rs @@ -14,7 +14,10 @@ use crate::db::page::{PagedList, Param}; use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; use crate::domain::bank_question_image::BankQuestionImage; use crate::domain::exam::ExamId; -use crate::domain::exam_question::{QuestionPoints, QuestionSpec, QuestionText}; +use crate::domain::exam_question::{ + Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, +}; +use crate::domain::note_file::FileContentType; use crate::domain::subject::SubjectId; use crate::domain::text_fold::{search_fold, search_fold_sql}; use crate::domain::timestamp::Timestamp; @@ -76,18 +79,25 @@ async fn insert( (id, owner, subject, text, kind, points, choices, correct, source_exam, visibility, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) - RETURNING *"#, - question.id, - question.owner, - question.subject, - question.text, - question.kind, - question.points, + RETURNING id AS "id: BankQuestionId", owner AS "owner: UserId", + subject AS "subject: Option", text AS "text: QuestionText", + kind AS "kind: QuestionKind", points AS "points: QuestionPoints", + choices AS "choices: Option>>", + correct AS "correct: Option", + source_exam AS "source_exam: Option", + visibility AS "visibility: BankVisibility", + created_at AS "created_at: Timestamp""#, + question.id.uuid(), + question.owner.uuid(), + question.subject.as_ref().map(SubjectId::uuid), + question.text.as_str(), + question.kind.as_str(), + question.points.as_i64(), question.choices, - question.correct, - question.source_exam, - question.visibility, - question.created_at, + question.correct.as_ref().map(ChoiceId::as_str), + question.source_exam.as_ref().map(ExamId::uuid), + question.visibility.as_str(), + question.created_at.as_millis(), ) .fetch_one(db) .await?; @@ -97,8 +107,16 @@ async fn insert( pub async fn read(db: &Database, id: &BankQuestionId) -> Result, AppError> { let row = sqlx::query_as!( BankQuestion, - "SELECT * FROM bank_question WHERE id = $1", - id + r#"SELECT id AS "id: BankQuestionId", owner AS "owner: UserId", + subject AS "subject: Option", text AS "text: QuestionText", + kind AS "kind: QuestionKind", points AS "points: QuestionPoints", + choices AS "choices: Option>>", + correct AS "correct: Option", + source_exam AS "source_exam: Option", + visibility AS "visibility: BankVisibility", + created_at AS "created_at: Timestamp" + FROM bank_question WHERE id = $1"#, + id.uuid() ) .fetch_optional(db) .await?; @@ -205,7 +223,7 @@ pub async fn usage_counts( if ids.is_empty() { return Ok(HashMap::new()); } - let ids: Vec = ids.iter().map(|id| (*id).clone()).collect(); + let ids: Vec = ids.iter().map(|id| id.uuid()).collect(); let rows = sqlx::query!( r#"SELECT from_bank AS "from_bank: BankQuestionId", count(*) AS n FROM exam_question @@ -263,22 +281,29 @@ pub async fn update_if_unchanged( AND choices IS NOT DISTINCT FROM $13 AND correct IS NOT DISTINCT FROM $14 AND visibility = $15 - RETURNING *"#, - expected.id, - subject, - text, - points, - kind, + RETURNING id AS "id: BankQuestionId", owner AS "owner: UserId", + subject AS "subject: Option", text AS "text: QuestionText", + kind AS "kind: QuestionKind", points AS "points: QuestionPoints", + choices AS "choices: Option>>", + correct AS "correct: Option", + source_exam AS "source_exam: Option", + visibility AS "visibility: BankVisibility", + created_at AS "created_at: Timestamp""#, + expected.id.uuid(), + subject.as_ref().map(SubjectId::uuid), + text.as_str(), + points.as_i64(), + kind.as_str(), choices, - correct, - visibility, - expected.subject, - expected.text, - expected.points, - expected.kind, + correct.as_ref().map(ChoiceId::as_str), + visibility.as_str(), + expected.subject.as_ref().map(SubjectId::uuid), + expected.text.as_str(), + expected.points.as_i64(), + expected.kind.as_str(), expected.choices, - expected.correct, - expected.visibility, + expected.correct.as_ref().map(ChoiceId::as_str), + expected.visibility.as_str(), ) .fetch_optional(db) .await?; @@ -309,27 +334,39 @@ pub async fn delete( let id = target.id.clone(); sqlx::query!( "UPDATE exam_question SET from_bank = NULL WHERE from_bank = $1", - id + id.uuid() ) .execute(tx) .await?; sqlx::query!( "UPDATE exam_question SET banked_as = NULL WHERE banked_as = $1", - id + id.uuid() ) .execute(tx) .await?; let images = sqlx::query_as!( BankQuestionImage, - "DELETE FROM bank_question_image WHERE bank_question = $1 RETURNING *", - id + r#"DELETE FROM bank_question_image WHERE bank_question = $1 + RETURNING bank_question AS "bank_question: BankQuestionId", + slot AS "slot: Option", file, + content_type AS "content_type: FileContentType", size"#, + id.uuid() ) .fetch_all(tx) .await?; let question = sqlx::query_as!( BankQuestion, - "DELETE FROM bank_question WHERE id = $1 RETURNING *", - id + r#"DELETE FROM bank_question WHERE id = $1 + RETURNING id AS "id: BankQuestionId", owner AS "owner: UserId", + subject AS "subject: Option", + text AS "text: QuestionText", kind AS "kind: QuestionKind", + points AS "points: QuestionPoints", + choices AS "choices: Option>>", + correct AS "correct: Option", + source_exam AS "source_exam: Option", + visibility AS "visibility: BankVisibility", + created_at AS "created_at: Timestamp""#, + id.uuid() ) .fetch_optional(tx) .await? diff --git a/src/db/bank_question_image.rs b/src/db/bank_question_image.rs index 3cb2be6..adb948e 100644 --- a/src/db/bank_question_image.rs +++ b/src/db/bank_question_image.rs @@ -7,6 +7,7 @@ use crate::database::{Database, foreign_key_violation, tx_with_retry}; use crate::domain::bank_question::BankQuestionId; use crate::domain::bank_question_image::BankQuestionImage; use crate::domain::exam_question::ChoiceId; +use crate::domain::note_file::FileContentType; use crate::error::AppError; /// Create or replace the slot's image row — the table's `NULLS NOT DISTINCT` @@ -33,8 +34,8 @@ pub async fn upsert( r#"SELECT file FROM bank_question_image WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2 FOR UPDATE"#, - image.bank_question.clone(), - image.slot.clone(), + image.bank_question.uuid(), + image.slot.as_ref().map(ChoiceId::as_str), ) .fetch_optional(tx) .await? @@ -46,11 +47,13 @@ pub async fn upsert( VALUES ($1, $2, $3, $4, $5) ON CONFLICT (bank_question, slot) DO UPDATE SET file = $3, content_type = $4, size = $5 - RETURNING *"#, - image.bank_question.clone(), - image.slot.clone(), + RETURNING bank_question AS "bank_question: BankQuestionId", + slot AS "slot: Option", file, + content_type AS "content_type: FileContentType", size"#, + image.bank_question.uuid(), + image.slot.as_ref().map(ChoiceId::as_str), image.file.clone(), - image.content_type, + image.content_type.as_str(), image.size, ) .fetch_one(tx) @@ -73,10 +76,13 @@ pub async fn read_slot( ) -> Result, AppError> { let row = sqlx::query_as!( BankQuestionImage, - r#"SELECT * FROM bank_question_image + r#"SELECT bank_question AS "bank_question: BankQuestionId", + slot AS "slot: Option", file, + content_type AS "content_type: FileContentType", size + FROM bank_question_image WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2"#, - question, - slot.cloned(), + question.uuid(), + slot.map(ChoiceId::as_str), ) .fetch_optional(db) .await?; @@ -89,8 +95,11 @@ pub async fn list_for_question( ) -> Result, AppError> { let rows = sqlx::query_as!( BankQuestionImage, - "SELECT * FROM bank_question_image WHERE bank_question = $1", - question + r#"SELECT bank_question AS "bank_question: BankQuestionId", + slot AS "slot: Option", file, + content_type AS "content_type: FileContentType", size + FROM bank_question_image WHERE bank_question = $1"#, + question.uuid() ) .fetch_all(db) .await?; @@ -106,10 +115,13 @@ pub async fn list_for_questions( if questions.is_empty() { return Ok(Vec::new()); } - let ids: Vec = questions.iter().map(|q| (*q).clone()).collect(); + let ids: Vec = questions.iter().map(|q| q.uuid()).collect(); let rows = sqlx::query_as!( BankQuestionImage, - "SELECT * FROM bank_question_image WHERE bank_question = ANY($1)", + r#"SELECT bank_question AS "bank_question: BankQuestionId", + slot AS "slot: Option", file, + content_type AS "content_type: FileContentType", size + FROM bank_question_image WHERE bank_question = ANY($1)"#, ids ) .fetch_all(db) @@ -138,8 +150,10 @@ pub async fn delete_choices_not_in( WHERE bank_question = $1 AND slot IS NOT NULL AND NOT (slot = ANY($2)) - RETURNING *"#, - question, + RETURNING bank_question AS "bank_question: BankQuestionId", + slot AS "slot: Option", file, + content_type AS "content_type: FileContentType", size"#, + question.uuid(), keep ) .fetch_all(db) @@ -155,9 +169,11 @@ pub async fn delete( BankQuestionImage, r#"DELETE FROM bank_question_image WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2 - RETURNING *"#, - image.bank_question, - image.slot + RETURNING bank_question AS "bank_question: BankQuestionId", + slot AS "slot: Option", file, + content_type AS "content_type: FileContentType", size"#, + image.bank_question.uuid(), + image.slot.as_ref().map(ChoiceId::as_str) ) .fetch_optional(db) .await?; diff --git a/src/db/board.rs b/src/db/board.rs index 034ee91..a7e22a3 100644 --- a/src/db/board.rs +++ b/src/db/board.rs @@ -41,14 +41,23 @@ pub async fn create( epoch, closed_at, created_at) SELECT $3, $1, $4, $5, false, NULL, NULL, 0, NULL, $6 WHERE EXISTS (SELECT 1 FROM seat) - RETURNING id, creator, title, participants, locked, locked_by, locked_at, - epoch, closed_at, created_at"#, - board.creator, + RETURNING id AS "id: BoardId", creator AS "creator: UserId", + title AS "title: BoardTitle", + participants AS "participants: Vec", locked, + locked_by AS "locked_by: Option", + locked_at AS "locked_at: Option", epoch, + closed_at AS "closed_at: Option", + created_at AS "created_at: Timestamp""#, + board.creator.uuid(), MAX_BOARDS_PER_CREATOR, - board.id, - board.title, - &board.participants, - board.created_at + board.id.uuid(), + board.title.as_str(), + &board + .participants + .iter() + .map(UserId::uuid) + .collect::>(), + board.created_at.as_millis() ) .fetch_optional(db) .await; @@ -71,10 +80,15 @@ pub async fn create( pub async fn read(db: &Database, id: &BoardId) -> Result, AppError> { let board = sqlx::query_as!( Board, - r#"SELECT id, creator, title, participants, locked, locked_by, locked_at, - epoch, closed_at, created_at + r#"SELECT id AS "id: BoardId", creator AS "creator: UserId", + title AS "title: BoardTitle", + participants AS "participants: Vec", locked, + locked_by AS "locked_by: Option", + locked_at AS "locked_at: Option", epoch, + closed_at AS "closed_at: Option", + created_at AS "created_at: Timestamp" FROM board WHERE id = $1"#, - id + id.uuid() ) .fetch_optional(db) .await?; @@ -122,10 +136,18 @@ pub async fn set_participants( let updated = sqlx::query_as!( Board, r#"UPDATE board SET participants = $2 WHERE id = $1 - RETURNING id, creator, title, participants, locked, locked_by, locked_at, - epoch, closed_at, created_at"#, - board.id, + RETURNING id AS "id: BoardId", creator AS "creator: UserId", + title AS "title: BoardTitle", + participants AS "participants: Vec", locked, + locked_by AS "locked_by: Option", + locked_at AS "locked_at: Option", epoch, + closed_at AS "closed_at: Option", + created_at AS "created_at: Timestamp""#, + board.id.uuid(), &participants + .iter() + .map(UserId::uuid) + .collect::>() ) .fetch_optional(db) .await?; @@ -136,10 +158,15 @@ pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Resul let updated = sqlx::query_as!( Board, r#"UPDATE board SET title = $2 WHERE id = $1 - RETURNING id, creator, title, participants, locked, locked_by, locked_at, - epoch, closed_at, created_at"#, - board.id, - title + RETURNING id AS "id: BoardId", creator AS "creator: UserId", + title AS "title: BoardTitle", + participants AS "participants: Vec", locked, + locked_by AS "locked_by: Option", + locked_at AS "locked_at: Option", epoch, + closed_at AS "closed_at: Option", + created_at AS "created_at: Timestamp""#, + board.id.uuid(), + title.as_str() ) .fetch_optional(db) .await?; @@ -158,12 +185,17 @@ pub async fn set_locked( let updated = sqlx::query_as!( Board, r#"UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1 - RETURNING id, creator, title, participants, locked, locked_by, locked_at, - epoch, closed_at, created_at"#, - board.id, + RETURNING id AS "id: BoardId", creator AS "creator: UserId", + title AS "title: BoardTitle", + participants AS "participants: Vec", locked, + locked_by AS "locked_by: Option", + locked_at AS "locked_at: Option", epoch, + closed_at AS "closed_at: Option", + created_at AS "created_at: Timestamp""#, + board.id.uuid(), locked, - locked.then(|| by.clone()), - locked.then(|| now) + locked.then(|| by.uuid()), + locked.then(|| now.as_millis()) ) .fetch_optional(db) .await?; @@ -193,10 +225,18 @@ pub(crate) async fn invite_group( WHERE id = $1 AND cardinality((SELECT coalesce(array_agg(DISTINCT x), '{}') FROM unnest(participants || $2::uuid[]) AS x)) <= $3 - RETURNING id, creator, title, participants, locked, locked_by, locked_at, - epoch, closed_at, created_at"#, - board.clone(), - &invited, + RETURNING id AS "id: BoardId", creator AS "creator: UserId", + title AS "title: BoardTitle", + participants AS "participants: Vec", locked, + locked_by AS "locked_by: Option", + locked_at AS "locked_at: Option", epoch, + closed_at AS "closed_at: Option", + created_at AS "created_at: Timestamp""#, + board.uuid(), + &invited + .iter() + .map(UserId::uuid) + .collect::>(), MAX_BOARD_PARTICIPANTS as i64 ) .fetch_optional(db) @@ -216,10 +256,15 @@ pub async fn close(db: &Database, board: &Board) -> Result { let closed = sqlx::query_as!( Board, r#"UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL - RETURNING id, creator, title, participants, locked, locked_by, locked_at, - epoch, closed_at, created_at"#, - board.id, - Timestamp::now() + RETURNING id AS "id: BoardId", creator AS "creator: UserId", + title AS "title: BoardTitle", + participants AS "participants: Vec", locked, + locked_by AS "locked_by: Option", + locked_at AS "locked_at: Option", epoch, + closed_at AS "closed_at: Option", + created_at AS "created_at: Timestamp""#, + board.id.uuid(), + Timestamp::now().as_millis() ) .fetch_optional(db) .await?; @@ -241,15 +286,20 @@ pub async fn close(db: &Database, board: &Board) -> Result { /// under a record that no longer exists. pub async fn delete(db: &Database, board: Board) -> Result { tx_with_retry(db, true, async |conn| { - sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id) + sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id.uuid()) .execute(&mut *conn) .await?; let gone = sqlx::query_as!( Board, r#"DELETE FROM board WHERE id = $1 - RETURNING id, creator, title, participants, locked, locked_by, locked_at, - epoch, closed_at, created_at"#, - board.id + RETURNING id AS "id: BoardId", creator AS "creator: UserId", + title AS "title: BoardTitle", + participants AS "participants: Vec", locked, + locked_by AS "locked_by: Option", + locked_at AS "locked_at: Option", epoch, + closed_at AS "closed_at: Option", + created_at AS "created_at: Timestamp""#, + board.id.uuid() ) .fetch_optional(&mut *conn) .await?; @@ -259,7 +309,7 @@ pub async fn delete(db: &Database, board: Board) -> Result { // the limit shut. sqlx::query!( "UPDATE app_user SET board_count = GREATEST(board_count - 1, 0) WHERE id = $1", - board.creator + board.creator.uuid() ) .execute(&mut *conn) .await?; diff --git a/src/db/board_stroke.rs b/src/db/board_stroke.rs index 0b10745..325d31f 100644 --- a/src/db/board_stroke.rs +++ b/src/db/board_stroke.rs @@ -56,16 +56,18 @@ pub async fn append( INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at) SELECT $5, $1, $6, $7, $8, NULL, $3, $9 WHERE EXISTS (SELECT 1 FROM bump) - RETURNING id, board, author, kind, payload, count, epoch, created_at"#, - board.clone(), + RETURNING id AS "id: BoardStrokeId", board AS "board: BoardId", + author AS "author: UserId", kind, payload, count, epoch, + created_at AS "created_at: Timestamp""#, + board.uuid(), MAX_BOARD_STROKES, epoch, MAX_EPOCH_STROKES, - BoardStrokeId::generate(), - author.clone(), + BoardStrokeId::generate().uuid(), + author.uuid(), KIND_STROKE, payload, - Timestamp::now() + Timestamp::now().as_millis() ) .fetch_optional(db) .await?; @@ -169,8 +171,13 @@ pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result", locked, + locked_by AS "locked_by: Option", + locked_at AS "locked_at: Option", epoch, + closed_at AS "closed_at: Option", + created_at AS "created_at: Timestamp" FROM board WHERE id = $1 FOR UPDATE"#, board.uuid() ) @@ -224,14 +231,16 @@ pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result Ok(sqlx::query_as!( BoardStroke, - r#"SELECT id, board, author, kind, payload, count, epoch, created_at + r#"SELECT id AS "id: BoardStrokeId", board AS "board: BoardId", + author AS "author: UserId", kind, payload, count, epoch, + created_at AS "created_at: Timestamp" FROM board_stroke WHERE board = $1 AND epoch = $2 AND kind = $3 AND id > $4 ORDER BY id LIMIT $5"#, - board.clone(), + board.uuid(), epoch, KIND_STROKE, - after, + after.uuid(), chunk ) .fetch_all(db) .await?), None => Ok(sqlx::query_as!( BoardStroke, - r#"SELECT id, board, author, kind, payload, count, epoch, created_at + r#"SELECT id AS "id: BoardStrokeId", board AS "board: BoardId", + author AS "author: UserId", kind, payload, count, epoch, + created_at AS "created_at: Timestamp" FROM board_stroke WHERE board = $1 AND epoch = $2 AND kind = $3 ORDER BY id LIMIT $4"#, - board.clone(), + board.uuid(), epoch, KIND_STROKE, chunk @@ -332,9 +345,11 @@ pub async fn history( pub async fn epochs(db: &Database, board: &BoardId) -> Result, AppError> { Ok(sqlx::query_as!( BoardStroke, - r#"SELECT id, board, author, kind, payload, count, epoch, created_at + r#"SELECT id AS "id: BoardStrokeId", board AS "board: BoardId", + author AS "author: UserId", kind, payload, count, epoch, + created_at AS "created_at: Timestamp" FROM board_stroke WHERE board = $1 AND kind = $2 ORDER BY id"#, - board.clone(), + board.uuid(), KIND_CLEAR ) .fetch_all(db) diff --git a/src/db/chatbot_thread.rs b/src/db/chatbot_thread.rs index f020d18..1f63f5e 100644 --- a/src/db/chatbot_thread.rs +++ b/src/db/chatbot_thread.rs @@ -45,7 +45,7 @@ pub async fn create_capped( (SELECT max_chatbot_threads FROM settings WHERE id = 'school'), $2) RETURNING 1) - INSERT INTO chatbot_thread (id, user_id, title AS \"title: ChatbotThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\") + INSERT INTO chatbot_thread (id, user_id, title, created_at, updated_at) SELECT $3, $1, $4, $5, $5 WHERE EXISTS (SELECT 1 FROM seat) RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \ @@ -105,8 +105,8 @@ pub async fn read_for( ) -> Result, AppError> { let thread = query_as!( ChatbotThread, - "SELECT id, user_id, title AS \"title: ChatbotThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM chatbot_thread WHERE id = $1", - id + "SELECT id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM chatbot_thread WHERE id = $1", + id.uuid() ) .fetch_optional(db) .await?; @@ -159,7 +159,7 @@ pub async fn rename( /// thread. On a re-sent round the thread is already gone, so the caller /// gets the `404` that is the truth. pub async fn delete(db: &Database, thread: ChatbotThread) -> Result { - tx_with_retry(db, false, async |tx| { + tx_with_retry(db, false, async move |tx| { // Children first: the foreign key would refuse the parent while a // turn still names it. sqlx::query!( @@ -171,7 +171,7 @@ pub async fn delete(db: &Database, thread: ChatbotThread) -> Result Result Ok(blueprint), + Ok(_) => Ok(blueprint.clone()), Err(e) if unique_violation(&e) == Some("class_blueprint_pkey") => Err( AppError::Conflict("a blueprint already exists for that grade"), ), @@ -166,7 +166,7 @@ pub async fn set_courses_if_unchanged( Ok(updated.map(|row| ClassBlueprint { id: id.clone(), grade: row.grade, - courses: wanted, + courses: wanted.clone(), creator: row.creator, })) }) diff --git a/src/db/class_group.rs b/src/db/class_group.rs index b46de3d..f6dc76f 100644 --- a/src/db/class_group.rs +++ b/src/db/class_group.rs @@ -41,13 +41,15 @@ pub async fn create( RETURNING 1) INSERT INTO class_group (id, creator, name, grade, term, teacher) SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat) - RETURNING id, creator, name, grade, term, teacher"#, + RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", + name AS "name: ClassName", grade AS "grade: ClassGrade", + term AS "term: TermId", teacher AS "teacher: UserId""#, term.uuid(), id.uuid(), creator.uuid(), name.as_str(), - grade.as_deref(), - teacher.as_ref() + grade.as_ref().map(ClassGrade::as_str), + teacher.as_ref().map(UserId::uuid) ) .fetch_optional(db) .await; @@ -72,13 +74,15 @@ pub async fn create( ClassGroup, r#"INSERT INTO class_group (id, creator, name, grade, term, teacher) VALUES ($1, $2, $3, $4, $5, $6) - RETURNING id, creator, name, grade, term, teacher"#, + RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", + name AS "name: ClassName", grade AS "grade: ClassGrade", + term AS "term: TermId", teacher AS "teacher: UserId""#, id.uuid(), creator.uuid(), name.as_str(), - grade.as_deref(), - term.as_ref(), - teacher.as_ref() + grade.as_ref().map(ClassGrade::as_str), + term.as_ref().map(TermId::uuid), + teacher.as_ref().map(UserId::uuid) ) .fetch_optional(db) .await?; @@ -91,7 +95,9 @@ pub async fn create( pub async fn read(db: &Database, id: &ClassGroupId) -> Result, AppError> { let class = sqlx::query_as!( ClassGroup, - r#"SELECT id, creator, name, grade, term, teacher + r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", + name AS "name: ClassName", grade AS "grade: ClassGrade", + term AS "term: TermId", teacher AS "teacher: UserId" FROM class_group WHERE id = $1"#, id.uuid() ) @@ -183,12 +189,14 @@ pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result = ids.to_vec(); + let ids: Vec = ids.iter().map(ClassGroupId::uuid).collect(); let classes = sqlx::query_as!( ClassGroup, - r#"SELECT id, creator, name, grade, term, teacher + r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", + name AS "name: ClassName", grade AS "grade: ClassGrade", + term AS "term: TermId", teacher AS "teacher: UserId" FROM class_group WHERE id = ANY($1)"#, - ids as _ + &ids ) .fetch_all(db) .await?; @@ -204,7 +212,9 @@ pub async fn list_for_grade( ) -> Result, AppError> { let classes = sqlx::query_as!( ClassGroup, - r#"SELECT id, creator, name, grade, term, teacher + r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", + name AS "name: ClassName", grade AS "grade: ClassGrade", + term AS "term: TermId", teacher AS "teacher: UserId" FROM class_group WHERE grade = $1"#, grade.as_str() ) @@ -243,7 +253,7 @@ pub async fn delete(db: &Database, class: ClassGroup) -> Result r#"DELETE FROM class_group WHERE id = $1 AND class_member_count = 0 AND class_course_count = 0 - RETURNING term AS "term: Option""#, + RETURNING term AS "term: uuid::Uuid""#, class.id.uuid() ) .fetch_optional(&mut *tx) diff --git a/src/db/class_pump.rs b/src/db/class_pump.rs index 83f65a8..a7d81a0 100644 --- a/src/db/class_pump.rs +++ b/src/db/class_pump.rs @@ -277,7 +277,7 @@ async fn early_verdicts( class as _, user as _ ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await? .is_some(), Pivot::Course(course) => sqlx::query_scalar!( @@ -285,7 +285,7 @@ async fn early_verdicts( class as _, course as _ ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await? .is_some(), }; @@ -297,7 +297,7 @@ async fn early_verdicts( r#"SELECT 1 AS "one" FROM class_blueprint WHERE grade = $1 FOR KEY SHARE"#, source as _ ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await? .is_some(); if !alive { @@ -310,7 +310,7 @@ async fn early_verdicts( r#"SELECT role AS "role: Role" FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#, user as _ ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await?; if row.map(|row| row.role) != Some(Role::Student) { return Ok(Some(Early::PivotGone)); @@ -321,7 +321,7 @@ async fn early_verdicts( r#"SELECT 1 AS "one" FROM course WHERE id = $1 FOR KEY SHARE"#, course as _ ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await? .is_some(); if !alive { @@ -338,7 +338,7 @@ async fn early_verdicts( class as _, Axis::Member.cap(), ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await? .is_some(), Axis::Course => sqlx::query_scalar!( @@ -347,7 +347,7 @@ async fn early_verdicts( class as _, Axis::Course.cap(), ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await? .is_some(), }; @@ -386,7 +386,7 @@ pub(crate) async fn add_member( // The claim and the link are one statement (the cap recipe's CTE): the // conditional `UPDATE` on the class row gates the `INSERT`, so a full // or gone class writes nothing at all. - let inserted = match sqlx::query_scalar!( + let inserted = match sqlx::query!( r#"WITH seat AS ( UPDATE class_group SET class_member_count = class_member_count + 1 WHERE id = $1 AND class_member_count < $2 @@ -400,7 +400,7 @@ pub(crate) async fn add_member( by as _, added_at as _ ) - .execute(tx) + .execute(&mut *tx) .await { Ok(result) => result, @@ -435,10 +435,7 @@ pub(crate) async fn add_member( class as _ ) .fetch_all(&mut *tx) - .await? - .into_iter() - .map(|row| row.course) - .collect(); + .await?; let pairs = courses.into_iter().map(|course| (course, user.uuid())); match enroll_pairs(tx, class, pairs, by).await? { Sweep::Done => {} @@ -481,7 +478,7 @@ pub(crate) async fn attach_course( { return Ok(refusal_of(early)); } - let inserted = match sqlx::query_scalar!( + let inserted = match sqlx::query!( r#"WITH seat AS ( UPDATE class_group SET class_course_count = class_course_count + 1 WHERE id = $1 AND class_course_count < $2 @@ -496,7 +493,7 @@ pub(crate) async fn attach_course( attached_at as _, source as _ ) - .execute(tx) + .execute(&mut *tx) .await { Ok(result) => result, @@ -525,10 +522,7 @@ pub(crate) async fn attach_course( class as _ ) .fetch_all(&mut *tx) - .await? - .into_iter() - .map(|row| row.app_user) - .collect(); + .await?; let pairs = members.into_iter().map(|user| (course.uuid(), user)); match enroll_pairs(tx, class, pairs, by).await? { Sweep::Done => {} @@ -707,7 +701,7 @@ pub(crate) async fn remove_member( class as _, user as _ ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await?; let Some(_) = gone else { return Ok(0); @@ -720,22 +714,18 @@ pub(crate) async fn remove_member( ) .execute(&mut *tx) .await?; - sweep_enrollments( - tx, - class, - sqlx::query!( - r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid" - FROM enrollment WHERE app_user = $1 AND source = $2"#, - user as _, - class as _ - ) - .fetch_all(&mut *tx) - .await? - .into_iter() - .map(|row| (row.course, row.app_user)) - .collect::>(), + let rows = sqlx::query!( + r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid" + FROM enrollment WHERE app_user = $1 AND source = $2"#, + user as _, + class as _ ) - .await?; + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|row| (row.course, row.app_user)) + .collect::>(); + sweep_enrollments(tx, class, rows).await?; Ok(1) }) .await @@ -763,7 +753,7 @@ pub(crate) async fn detach_course( course as _, source as _ ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await? } None => { @@ -773,7 +763,7 @@ pub(crate) async fn detach_course( class as _, course as _ ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await? } }; @@ -788,22 +778,18 @@ pub(crate) async fn detach_course( ) .execute(&mut *tx) .await?; - sweep_enrollments( - tx, - class, - sqlx::query!( - r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid" - FROM enrollment WHERE course = $1 AND source = $2"#, - course as _, - class as _ - ) - .fetch_all(&mut *tx) - .await? - .into_iter() - .map(|row| (row.course, row.app_user)) - .collect::>(), + let rows = sqlx::query!( + r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid" + FROM enrollment WHERE course = $1 AND source = $2"#, + course as _, + class as _ ) - .await?; + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|row| (row.course, row.app_user)) + .collect::>(); + sweep_enrollments(tx, class, rows).await?; Ok(1) }) .await @@ -838,8 +824,7 @@ async fn sweep_enrollments( class as _ ) .fetch_optional(&mut *tx) - .await? - .map(|row| row.class); + .await?; let Some(heir) = heir else { release(tx, course, user).await?; continue; diff --git a/src/db/course.rs b/src/db/course.rs index 0859b9a..8ff3636 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -27,13 +27,16 @@ pub async fn create( Course, r#"INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity) VALUES ($1, $2, $3, $4, $5, $6, NULL, $7) - RETURNING id, creator, teachers, title, description, kind, term, capacity"#, - id, - creator, - Vec::::new(), - title, - description, - kind, + RETURNING id AS "id: CourseId", creator AS "creator: UserId", + teachers AS "teachers: Vec", title AS "title: CourseTitle", + description AS "description: CourseDescription", + kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, + id.uuid(), + creator.uuid(), + &Vec::::new(), + title.as_str(), + description.as_str(), + kind.as_str(), capacity, ) .fetch_one(db) @@ -55,15 +58,18 @@ pub async fn create( RETURNING 1) INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity) SELECT $1, $2, $3, $4, $5, $6, $8, $7 WHERE EXISTS (SELECT 1 FROM seat) - RETURNING id, creator, teachers, title, description, kind, term, capacity"#, - id, - creator, - Vec::::new(), - title, - description, - kind, + RETURNING id AS "id: CourseId", creator AS "creator: UserId", + teachers AS "teachers: Vec", title AS "title: CourseTitle", + description AS "description: CourseDescription", + kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, + id.uuid(), + creator.uuid(), + &Vec::::new(), + title.as_str(), + description.as_str(), + kind.as_str(), capacity, - term, + term.uuid(), cap::UNLIMITED, ) .fetch_one(db) @@ -84,9 +90,12 @@ pub async fn create( pub async fn read(db: &Database, id: &CourseId) -> Result, AppError> { let course = sqlx::query_as!( Course, - r#"SELECT id, creator, teachers, title, description, kind, term, capacity + r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", + teachers AS "teachers: Vec", title AS "title: CourseTitle", + description AS "description: CourseDescription", + kind AS "kind: CourseKind", term AS "term: TermId", capacity FROM course WHERE id = $1"#, - id, + id.uuid(), ) .fetch_optional(db) .await?; @@ -96,7 +105,10 @@ pub async fn read(db: &Database, id: &CourseId) -> Result, AppErr pub async fn list_all(db: &Database) -> Result, AppError> { let rows = sqlx::query_as!( Course, - r#"SELECT id, creator, teachers, title, description, kind, term, capacity + r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", + teachers AS "teachers: Vec", title AS "title: CourseTitle", + description AS "description: CourseDescription", + kind AS "kind: CourseKind", term AS "term: TermId", capacity FROM course ORDER BY id DESC"#, ) .fetch_all(db) @@ -137,10 +149,13 @@ pub async fn list_enrolled( pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result, AppError> { let rows = sqlx::query_as!( Course, - r#"SELECT id, creator, teachers, title, description, kind, term, capacity + r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", + teachers AS "teachers: Vec", title AS "title: CourseTitle", + description AS "description: CourseDescription", + kind AS "kind: CourseKind", term AS "term: TermId", capacity FROM course WHERE creator = $1 OR $2 = ANY(teachers) ORDER BY id DESC"#, - user, - user, + user.uuid(), + user.uuid(), ) .fetch_all(db) .await?; @@ -153,12 +168,15 @@ pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result, if ids.is_empty() { return Ok(Vec::new()); } - let keys: Vec = ids.to_vec(); + let keys: Vec = ids.iter().map(CourseId::uuid).collect(); let rows = sqlx::query_as!( Course, - r#"SELECT id, creator, teachers, title, description, kind, term, capacity + r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", + teachers AS "teachers: Vec", title AS "title: CourseTitle", + description AS "description: CourseDescription", + kind AS "kind: CourseKind", term AS "term: TermId", capacity FROM course WHERE id = ANY($1)"#, - keys, + &keys, ) .fetch_all(db) .await?; @@ -235,11 +253,14 @@ pub async fn assign_teacher( Course, r#"UPDATE course SET teachers = (SELECT array_agg(DISTINCT x) - FROM unnest(course.teachers || $2) AS x) + FROM unnest(course.teachers || $2::uuid) AS x) WHERE id = $1 - RETURNING id, creator, teachers, title, description, kind, term, capacity"#, - course.id, - teacher, + RETURNING id AS "id: CourseId", creator AS "creator: UserId", + teachers AS "teachers: Vec", title AS "title: CourseTitle", + description AS "description: CourseDescription", + kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, + course.id.uuid(), + teacher.uuid(), ) .fetch_optional(db) .await?; @@ -263,9 +284,12 @@ pub async fn unassign_teacher( Course, r#"UPDATE course SET teachers = array_remove(teachers, $2) WHERE id = $1 - RETURNING id, creator, teachers, title, description, kind, term, capacity"#, - course.id, - teacher, + RETURNING id AS "id: CourseId", creator AS "creator: UserId", + teachers AS "teachers: Vec", title AS "title: CourseTitle", + description AS "description: CourseDescription", + kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, + course.id.uuid(), + teacher.uuid(), ) .fetch_optional(db) .await?; @@ -278,7 +302,7 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App sqlx::query!( r#"UPDATE course SET teachers = array_remove(teachers, $1) WHERE $1 = ANY(teachers)"#, - user, + user.uuid(), ) .execute(db) .await?; @@ -352,7 +376,7 @@ pub async fn delete(db: &Database, course: Course) -> Result { // this very row, so check and cascade are one decision. let guard = sqlx::query!( r#"SELECT enrollment_count, term FROM course WHERE id = $1 FOR UPDATE"#, - course.id, + course.id.uuid(), ) .fetch_optional(&mut *tx) .await?; @@ -366,7 +390,7 @@ pub async fn delete(db: &Database, course: Course) -> Result { // source_exam clear — and must be collected before the sweeps take // the rows they name. let exams: Vec = - sqlx::query!(r#"SELECT id FROM exam WHERE course = $1"#, course.id,) + sqlx::query!(r#"SELECT id FROM exam WHERE course = $1"#, course.id.uuid(),) .fetch_all(&mut *tx) .await? .into_iter() @@ -382,7 +406,7 @@ pub async fn delete(db: &Database, course: Course) -> Result { JOIN exam e ON r.exam = e.id WHERE r.exam = ANY($1) GROUP BY e.kind) s WHERE k.name = s.kind"#, - exams, + &exams, ) .execute(&mut *tx) .await?; @@ -399,27 +423,27 @@ pub async fn delete(db: &Database, course: Course) -> Result { // Events aimed at this course keep standing, audience cleared. sqlx::query!( r#"UPDATE event SET audience_course = NULL WHERE audience_course = $1"#, - course.id, + course.id.uuid(), ) .execute(&mut *tx) .await?; // The exam subtree, deepest children first. - sqlx::query!(r#"DELETE FROM exam_result WHERE exam = ANY($1)"#, exams) + sqlx::query!(r#"DELETE FROM exam_result WHERE exam = ANY($1)"#, &exams) .execute(&mut *tx) .await?; - sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = ANY($1)"#, exams) + sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = ANY($1)"#, &exams) .execute(&mut *tx) .await?; - sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = ANY($1)"#, exams) + sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = ANY($1)"#, &exams) .execute(&mut *tx) .await?; - sqlx::query!(r#"DELETE FROM answer_image WHERE exam = ANY($1)"#, exams) + sqlx::query!(r#"DELETE FROM answer_image WHERE exam = ANY($1)"#, &exams) .execute(&mut *tx) .await?; - sqlx::query!(r#"DELETE FROM question_image WHERE exam = ANY($1)"#, exams) + sqlx::query!(r#"DELETE FROM question_image WHERE exam = ANY($1)"#, &exams) .execute(&mut *tx) .await?; - sqlx::query!(r#"DELETE FROM exam_question WHERE exam = ANY($1)"#, exams) + sqlx::query!(r#"DELETE FROM exam_question WHERE exam = ANY($1)"#, &exams) .execute(&mut *tx) .await?; // The homework subtree: files, then submissions (whose graded_by @@ -428,39 +452,45 @@ pub async fn delete(db: &Database, course: Course) -> Result { r#"DELETE FROM homework_file WHERE submission IN ( SELECT id FROM homework_submission WHERE homework IN (SELECT id FROM homework WHERE course = $1))"#, - course.id, + course.id.uuid(), ) .execute(&mut *tx) .await?; sqlx::query!( r#"DELETE FROM homework_submission WHERE homework IN ( SELECT id FROM homework WHERE course = $1)"#, - course.id, + course.id.uuid(), ) .execute(&mut *tx) .await?; sqlx::query!( r#"DELETE FROM homework_result WHERE homework IN ( SELECT id FROM homework WHERE course = $1)"#, - course.id, + course.id.uuid(), ) .execute(&mut *tx) .await?; // Derived AI rows for this course's notes. - sqlx::query!(r#"DELETE FROM rag_output WHERE course = $1"#, course.id) - .execute(&mut *tx) - .await?; + sqlx::query!( + r#"DELETE FROM rag_output WHERE course = $1"#, + course.id.uuid() + ) + .execute(&mut *tx) + .await?; // Notes: files before their notes. sqlx::query!( r#"DELETE FROM course_note_file WHERE course_note IN ( SELECT id FROM course_note WHERE course = $1)"#, - course.id, + course.id.uuid(), + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM course_note WHERE course = $1"#, + course.id.uuid() ) .execute(&mut *tx) .await?; - sqlx::query!(r#"DELETE FROM course_note WHERE course = $1"#, course.id) - .execute(&mut *tx) - .await?; // Class attachments: detach and hand each class its count back in // one statement, then strike the course out of every blueprint. sqlx::query!( @@ -469,58 +499,67 @@ pub async fn delete(db: &Database, course: Course) -> Result { UPDATE class_group g SET class_course_count = GREATEST(g.class_course_count - 1, 0) FROM detached WHERE g.id = detached.class"#, - course.id, + course.id.uuid(), ) .execute(&mut *tx) .await?; sqlx::query!( r#"UPDATE class_blueprint SET courses = array_remove(courses, $1) WHERE $1 = ANY(courses)"#, - course.id, + course.id.uuid(), ) .execute(&mut *tx) .await?; // Sessions with their roll call, then the roster itself. sqlx::query!( r#"DELETE FROM session_attendance WHERE course = $1"#, - course.id, + course.id.uuid(), + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM course_session WHERE course = $1"#, + course.id.uuid() + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM enrollment WHERE course = $1"#, + course.id.uuid() ) .execute(&mut *tx) .await?; - sqlx::query!(r#"DELETE FROM course_session WHERE course = $1"#, course.id) - .execute(&mut *tx) - .await?; - sqlx::query!(r#"DELETE FROM enrollment WHERE course = $1"#, course.id) - .execute(&mut *tx) - .await?; // The bank keeps its templates; their links to this course's // content go first, so the subject/exam deletes below cannot trip // a foreign key behind them. sqlx::query!( r#"UPDATE bank_question SET subject = NULL WHERE subject IN (SELECT id FROM subject WHERE course = $1)"#, - course.id, + course.id.uuid(), ) .execute(&mut *tx) .await?; sqlx::query!( r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = ANY($1)"#, - exams, + &exams, ) .execute(&mut *tx) .await?; // Subjects before exams would trip `exam.subject` — exams go first. - sqlx::query!(r#"DELETE FROM exam WHERE course = $1"#, course.id) - .execute(&mut *tx) - .await?; - sqlx::query!(r#"DELETE FROM homework WHERE course = $1"#, course.id) + sqlx::query!(r#"DELETE FROM exam WHERE course = $1"#, course.id.uuid()) .execute(&mut *tx) .await?; - sqlx::query!(r#"DELETE FROM subject WHERE course = $1"#, course.id) + sqlx::query!( + r#"DELETE FROM homework WHERE course = $1"#, + course.id.uuid() + ) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM subject WHERE course = $1"#, course.id.uuid()) .execute(&mut *tx) .await?; // Last: the course itself, now FK-silent. - sqlx::query!(r#"DELETE FROM course WHERE id = $1"#, course.id) + sqlx::query!(r#"DELETE FROM course WHERE id = $1"#, course.id.uuid()) .execute(&mut *tx) .await?; Ok(true) diff --git a/src/db/course_note.rs b/src/db/course_note.rs index 030df94..d3c6007 100644 --- a/src/db/course_note.rs +++ b/src/db/course_note.rs @@ -6,7 +6,9 @@ use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; use crate::domain::course::CourseId; use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle}; -use crate::domain::course_note_file::CourseNoteFile; +use crate::domain::course_note_file::{ + CourseNoteFile, CourseNoteFileId, FileContentType, FileName, +}; use crate::domain::user::UserId; use crate::error::AppError; @@ -34,12 +36,14 @@ pub async fn create( CourseNote, r#"INSERT INTO course_note (id, course, author, title, content) VALUES ($1, $2, $3, $4, $5) - RETURNING id, course, author, title, content"#, - note.id, - note.course, - note.author, - note.title, - note.content + RETURNING id AS "id: CourseNoteId", course AS "course: CourseId", + author AS "author: UserId", title AS "title: CourseNoteTitle", + content AS "content: CourseNoteContent""#, + note.id.uuid(), + note.course.uuid(), + note.author.uuid(), + note.title.as_str(), + note.content.as_str() ) .fetch_one(db) .await; @@ -53,8 +57,10 @@ pub async fn create( pub async fn read(db: &Database, id: &CourseNoteId) -> Result, AppError> { let note = sqlx::query_as!( CourseNote, - r#"SELECT id, course, author, title, content FROM course_note WHERE id = $1"#, - id + r#"SELECT id AS "id: CourseNoteId", course AS "course: CourseId", + author AS "author: UserId", title AS "title: CourseNoteTitle", + content AS "content: CourseNoteContent" FROM course_note WHERE id = $1"#, + id.uuid() ) .fetch_optional(db) .await?; @@ -112,21 +118,25 @@ pub async fn delete( note: CourseNote, ) -> Result<(CourseNote, Vec), AppError> { tx_with_retry(db, true, async |conn| { - sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id) + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id.uuid()) .execute(&mut *conn) .await?; let files = sqlx::query_as!( CourseNoteFile, r#"DELETE FROM course_note_file WHERE course_note = $1 - RETURNING id, course_note, name, content_type, size"#, - note.id + RETURNING id AS "id: CourseNoteFileId", + course_note AS "course_note: CourseNoteId", name AS "name: FileName", + content_type AS "content_type: FileContentType", size"#, + note.id.uuid() ) .fetch_all(&mut *conn) .await?; let gone = sqlx::query_as!( CourseNote, - r#"DELETE FROM course_note WHERE id = $1 RETURNING id, course, author, title, content"#, - note.id + r#"DELETE FROM course_note WHERE id = $1 RETURNING id AS "id: CourseNoteId", course AS "course: CourseId", + author AS "author: UserId", title AS "title: CourseNoteTitle", + content AS "content: CourseNoteContent""#, + note.id.uuid() ) .fetch_optional(&mut *conn) .await?; diff --git a/src/db/course_note_file.rs b/src/db/course_note_file.rs index d8f8e36..489928d 100644 --- a/src/db/course_note_file.rs +++ b/src/db/course_note_file.rs @@ -7,7 +7,9 @@ use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::page::PagedList; use crate::domain::course::CourseId; use crate::domain::course_note::CourseNoteId; -use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; +use crate::domain::course_note_file::{ + CourseNoteFile, CourseNoteFileId, FileContentType, FileName, +}; use crate::error::AppError; /// Persist the row assembled by [`CourseNoteFile::new`], refusing once its @@ -26,12 +28,14 @@ pub async fn insert(db: &Database, file: CourseNoteFile) -> Result Result, AppError> { let file = sqlx::query_as!( CourseNoteFile, - r#"SELECT id, course_note, name, content_type, size FROM course_note_file WHERE id = $1"#, - id + r#"SELECT id AS "id: CourseNoteFileId", + course_note AS "course_note: CourseNoteId", name AS "name: FileName", + content_type AS "content_type: FileContentType", size FROM course_note_file WHERE id = $1"#, + id.uuid() ) .fetch_optional(db) .await?; @@ -78,10 +84,12 @@ pub async fn read_for( ) -> Result, AppError> { let file = sqlx::query_as!( CourseNoteFile, - r#"SELECT id, course_note, name, content_type, size FROM course_note_file + r#"SELECT id AS "id: CourseNoteFileId", + course_note AS "course_note: CourseNoteId", name AS "name: FileName", + content_type AS "content_type: FileContentType", size FROM course_note_file WHERE id = $1 AND course_note = $2"#, - id, - note + id.uuid(), + note.uuid() ) .fetch_optional(db) .await?; @@ -114,7 +122,7 @@ pub async fn file_keys_for_course( let rows = sqlx::query!( r#"SELECT course_note_file.id AS "id: CourseNoteFileId" FROM course_note_file WHERE course_note IN (SELECT id FROM course_note WHERE course = $1)"#, - course.0 + course.uuid() ) .fetch_all(db) .await?; @@ -129,15 +137,17 @@ pub async fn delete(db: &Database, file: CourseNoteFile) -> Result Result, AppError> { let session = sqlx::query_as!( CourseSession, - r#"SELECT id, course, teacher, topic, starts_at, ends_at + r#"SELECT id AS "id: CourseSessionId", course AS "course: CourseId", + teacher AS "teacher: UserId", topic AS "topic: SessionTopic", + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp" FROM course_session WHERE id = $1"#, - id, + id.uuid(), ) .fetch_optional(db) .await?; @@ -132,15 +136,17 @@ pub async fn delete(db: &Database, session: CourseSession) -> Result Result, AppError> { let row = sqlx::query_as!( DietaryProfile, - "SELECT student, tags, note, updated_by, updated_at + "SELECT student AS \"student: UserId\", tags AS \"tags: DietaryTags\", note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\" FROM dietary_profile WHERE student = $1", - *student, + student.uuid(), ) .fetch_optional(db) .await?; @@ -62,12 +62,12 @@ pub async fn save( note = CASE WHEN $6 THEN $3 ELSE dietary_profile.note END, updated_by = $4, updated_at = $5 - RETURNING student, tags, note, updated_by, updated_at", - *student, - tags.map(|t| t.as_slice().to_vec()), - note.clone().flatten().map(|n| n.as_str().to_string()), - *by, - Timestamp::now(), + RETURNING student AS \"student: UserId\", tags AS \"tags: DietaryTags\", note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"", + student.uuid(), + tags.as_ref().map(|t| t.as_slice()), + note.as_ref().and_then(|n| n.as_ref()).map(|n| n.as_str()), + by.uuid(), + Timestamp::now().as_millis(), note.is_some(), ) .fetch_one(db) diff --git a/src/db/enrollment.rs b/src/db/enrollment.rs index fdffd98..a712afb 100644 --- a/src/db/enrollment.rs +++ b/src/db/enrollment.rs @@ -7,6 +7,7 @@ use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::cap; use crate::db::page::PagedList; +use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; use crate::domain::enrollment::Enrollment; use crate::domain::role::Role; @@ -64,8 +65,8 @@ pub async fn enroll( // already in" still outranks everything. let held = sqlx::query!( r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#, - course, - user, + course.uuid(), + user.uuid(), ) .fetch_optional(&mut *tx) .await?; @@ -77,7 +78,7 @@ pub async fn enroll( // demotion (see the doc above). let role = sqlx::query!( r#"SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#, - user, + user.uuid(), ) .fetch_optional(&mut *tx) .await?; @@ -98,11 +99,12 @@ pub async fn enroll( RETURNING 1) INSERT INTO enrollment (course, app_user, enrolled_by, source) SELECT $1, $3, $4, NULL WHERE EXISTS (SELECT 1 FROM seat) - RETURNING course, app_user AS "user", enrolled_by, source"#, - course, + RETURNING course AS "course: CourseId", app_user AS "user: UserId", + enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId""#, + course.uuid(), cap::UNLIMITED, - user, - enrolled_by, + user.uuid(), + enrolled_by.uuid(), ) .fetch_optional(&mut *tx) .await?; @@ -161,9 +163,10 @@ async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result Result, AppError> { let row = sqlx::query_as!( Enrollment, - r#"SELECT course, app_user AS "user", enrolled_by, source + r#"SELECT course AS "course: CourseId", app_user AS "user: UserId", + enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId" FROM enrollment WHERE course = $1 AND app_user = $2"#, - course, - user, + course.uuid(), + user.uuid(), ) .fetch_optional(db) .await?; @@ -231,9 +235,10 @@ pub async fn remove( enrollment_count - (SELECT count(*) FROM gone), 0) WHERE id = $1 RETURNING 1) - SELECT course, app_user AS "user", enrolled_by, source FROM gone"#, - course, - user, + SELECT course AS "course: CourseId", app_user AS "user: UserId", + enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId" FROM gone"#, + course.uuid(), + user.uuid(), ) .fetch_optional(db) .await?; diff --git a/src/db/event.rs b/src/db/event.rs index f1c71f4..3cb7469 100644 --- a/src/db/event.rs +++ b/src/db/event.rs @@ -40,7 +40,7 @@ pub async fn includes(db: &Database, event: &Event, user: &User) -> Result { let row = sqlx::query!( "SELECT EXISTS(SELECT 1 FROM class_member WHERE class = $1 AND app_user = $2) - AS present", + AS \"present!\"", class.uuid(), user.get_id().uuid() ) @@ -120,7 +120,7 @@ pub async fn create( // bundle guarantees only the matching payload is ever non-NULL. let created = query_as!( Event, - "INSERT INTO event (id, creator, title AS \"title: EventTitle\", description AS \"description: EventDescription\", audience_kind, audience_role, \ + "INSERT INTO event (id, creator, title, description, audience_kind, audience_role, \ audience_course, audience_class, audience_capacity, starts_at, ends_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \ @@ -134,7 +134,7 @@ pub async fn create( creator.uuid(), title.as_str(), description.as_str(), - audience.kind, + audience.kind.as_str(), audience.role.map(|r| r.as_str().to_string()), audience.course.map(|c| c.uuid()), audience.class.map(|c| c.uuid()), @@ -225,11 +225,11 @@ pub async fn update( ) .set( "audience_course", - audience.as_ref().map(|a| Param::OptUuid(a.course.map(|c| c.uuid()))), + audience.as_ref().map(|a| Param::OptUuid(a.course.as_ref().map(|c| c.uuid()))), ) .set( "audience_class", - audience.as_ref().map(|a| Param::OptUuid(a.class.map(|c| c.uuid()))), + audience.as_ref().map(|a| Param::OptUuid(a.class.as_ref().map(|c| c.uuid()))), ) .set( "audience_capacity", @@ -259,7 +259,7 @@ pub async fn update( /// for the event row (its insert's foreign key proves the event the moment /// it lands), so a lost round re-sends instead of answering 500. pub async fn delete(db: &Database, event: Event) -> Result { - tx_with_retry(db, true, async |tx| { + tx_with_retry(db, true, async move |tx| { sqlx::query!("DELETE FROM attendance WHERE event = $1", event.get_id().uuid()) .execute(&mut *tx) .await?; diff --git a/src/db/exam.rs b/src/db/exam.rs index 2a758dc..880fbc0 100644 --- a/src/db/exam.rs +++ b/src/db/exam.rs @@ -44,23 +44,23 @@ pub async fn create( RETURNING id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", title AS "title: ExamTitle", description AS "description: ExamDescription", - kind AS "kind: ExamKind", mode AS "mode: Option", - starts_at AS "starts_at: Option", - ends_at AS "ends_at: Option", - duration_ms AS "duration_ms: Option", + kind AS "kind: ExamKind", mode AS "mode: ExamMode", + starts_at AS "starts_at: Timestamp", + ends_at AS "ends_at: Timestamp", + duration_ms AS "duration_ms: ExamDuration", max_attempts AS "max_attempts: ExamAttemptLimit", allow_rejoin, allow_review, draft"#, - ExamId::generate(), - creator as &UserId, - course as &CourseId, - title, - description, - kind, - schedule.mode, - schedule.starts_at, - schedule.ends_at, - schedule.duration_ms, - max_attempts, + ExamId::generate().uuid(), + creator.uuid(), + course.uuid(), + title.as_str(), + description.as_str(), + kind.as_str(), + schedule.mode.as_ref().map(ExamMode::as_str), + schedule.starts_at.map(|at| at.as_millis()), + schedule.ends_at.map(|at| at.as_millis()), + schedule.duration_ms.map(|duration| duration.as_millis()), + max_attempts.as_i64(), allow_rejoin, allow_review, draft, @@ -79,14 +79,14 @@ pub async fn read(db: &Database, id: &ExamId) -> Result, AppError> Exam, r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", title AS "title: ExamTitle", description AS "description: ExamDescription", - kind AS "kind: ExamKind", mode AS "mode: Option", - starts_at AS "starts_at: Option", - ends_at AS "ends_at: Option", - duration_ms AS "duration_ms: Option", + kind AS "kind: ExamKind", mode AS "mode: ExamMode", + starts_at AS "starts_at: Timestamp", + ends_at AS "ends_at: Timestamp", + duration_ms AS "duration_ms: ExamDuration", max_attempts AS "max_attempts: ExamAttemptLimit", allow_rejoin, allow_review, draft FROM exam WHERE id = $1"#, - id as &ExamId, + id.uuid(), ) .fetch_optional(db) .await?) @@ -99,10 +99,10 @@ pub async fn list_all(db: &Database) -> Result, AppError> { Exam, r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", title AS "title: ExamTitle", description AS "description: ExamDescription", - kind AS "kind: ExamKind", mode AS "mode: Option", - starts_at AS "starts_at: Option", - ends_at AS "ends_at: Option", - duration_ms AS "duration_ms: Option", + kind AS "kind: ExamKind", mode AS "mode: ExamMode", + starts_at AS "starts_at: Timestamp", + ends_at AS "ends_at: Timestamp", + duration_ms AS "duration_ms: ExamDuration", max_attempts AS "max_attempts: ExamAttemptLimit", allow_rejoin, allow_review, draft FROM exam ORDER BY id DESC"#, @@ -116,14 +116,14 @@ pub async fn list_for_course(db: &Database, course: &CourseId) -> Result", - starts_at AS "starts_at: Option", - ends_at AS "ends_at: Option", - duration_ms AS "duration_ms: Option", + kind AS "kind: ExamKind", mode AS "mode: ExamMode", + starts_at AS "starts_at: Timestamp", + ends_at AS "ends_at: Timestamp", + duration_ms AS "duration_ms: ExamDuration", max_attempts AS "max_attempts: ExamAttemptLimit", allow_rejoin, allow_review, draft FROM exam WHERE course = $1 ORDER BY id DESC"#, - course as &CourseId, + course.uuid(), ) .fetch_all(db) .await?) @@ -140,14 +140,14 @@ pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result", - starts_at AS "starts_at: Option", - ends_at AS "ends_at: Option", - duration_ms AS "duration_ms: Option", + kind AS "kind: ExamKind", mode AS "mode: ExamMode", + starts_at AS "starts_at: Timestamp", + ends_at AS "ends_at: Timestamp", + duration_ms AS "duration_ms: ExamDuration", max_attempts AS "max_attempts: ExamAttemptLimit", allow_rejoin, allow_review, draft FROM exam WHERE course = ANY($1) ORDER BY id DESC"#, - courses, + &courses, ) .fetch_all(db) .await?) @@ -160,7 +160,7 @@ pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result Result { let row = sqlx::query!( r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#, - id as &ExamId, + id.uuid(), ) .fetch_one(db) .await?; @@ -240,17 +240,17 @@ pub async fn update_if_unchanged( let gates = sqlx::query!( r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat, EXISTS(SELECT 1 FROM exam_result WHERE exam = $1) AS graded"#, - expected.id as &ExamId, + expected.id.uuid(), ) .fetch_one(&mut *conn) .await?; - if gates.sat || gates.graded { + if gates.sat.unwrap_or(false) || gates.graded.unwrap_or(false) { return Err(redraft_error()); } } let was_results = sqlx::query!( r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#, - expected.id as &ExamId, + expected.id.uuid(), ) .fetch_optional(&mut *conn) .await? @@ -274,32 +274,32 @@ pub async fn update_if_unchanged( RETURNING id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", title AS "title: ExamTitle", description AS "description: ExamDescription", - kind AS "kind: ExamKind", mode AS "mode: Option", - starts_at AS "starts_at: Option", - ends_at AS "ends_at: Option", - duration_ms AS "duration_ms: Option", + kind AS "kind: ExamKind", mode AS "mode: ExamMode", + starts_at AS "starts_at: Timestamp", + ends_at AS "ends_at: Timestamp", + duration_ms AS "duration_ms: ExamDuration", max_attempts AS "max_attempts: ExamAttemptLimit", allow_rejoin, allow_review, draft"#, - expected.id as &ExamId, - expected.title, - expected.description, - expected.kind, - expected.mode, - expected.starts_at, - expected.ends_at, - expected.duration_ms, - expected.max_attempts, + expected.id.uuid(), + expected.title.as_str(), + expected.description.as_str(), + expected.kind.as_str(), + expected.mode.as_ref().map(ExamMode::as_str), + expected.starts_at.map(|at| at.as_millis()), + expected.ends_at.map(|at| at.as_millis()), + expected.duration_ms.map(|duration| duration.as_millis()), + expected.max_attempts.as_i64(), expected.allow_rejoin, expected.allow_review, expected.draft, - was.0, - was.1, - was.2, - was.3, - was.4, - was.5, - was.6, - was.7, + was.0.as_str(), + was.1.as_str(), + was.2.as_str(), + was.3.as_ref().map(ExamMode::as_str), + was.4.map(|at| at.as_millis()), + was.5.map(|at| at.as_millis()), + was.6.map(|duration| duration.as_millis()), + was.7.as_i64(), was.8, was.9, was.10, @@ -358,7 +358,7 @@ pub async fn delete(db: &Database, target: Exam) -> Result { // The row lock every other exam-child writer contends on. let locked = sqlx::query!( r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, - target.id as &ExamId, + target.id.uuid(), ) .fetch_optional(&mut *conn) .await?; @@ -371,7 +371,7 @@ pub async fn delete(db: &Database, target: Exam) -> Result { // refused. let image_files = sqlx::query!( r#"SELECT file FROM question_image WHERE exam = $1"#, - target.id as &ExamId, + target.id.uuid(), ) .fetch_all(&mut *conn) .await? @@ -380,7 +380,7 @@ pub async fn delete(db: &Database, target: Exam) -> Result { .collect(); let answer_image_files = sqlx::query!( r#"SELECT file FROM answer_image WHERE exam = $1"#, - target.id as &ExamId, + target.id.uuid(), ) .fetch_all(&mut *conn) .await? @@ -399,23 +399,23 @@ pub async fn delete(db: &Database, target: Exam) -> Result { GROUP BY e.kind) UPDATE kind_ref k SET count = GREATEST(k.count - c.n, 0) FROM kinds c WHERE k.name = c.kind"#, - target.id as &ExamId, + target.id.uuid(), ) .execute(&mut *conn) .await?; - sqlx::query!(r#"DELETE FROM exam_result WHERE exam = $1"#, target.id as &ExamId) + sqlx::query!(r#"DELETE FROM exam_result WHERE exam = $1"#, target.id.uuid()) .execute(&mut *conn) .await?; - sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = $1"#, target.id as &ExamId) + sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = $1"#, target.id.uuid()) .execute(&mut *conn) .await?; - sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = $1"#, target.id as &ExamId) + sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = $1"#, target.id.uuid()) .execute(&mut *conn) .await?; - sqlx::query!(r#"DELETE FROM answer_image WHERE exam = $1"#, target.id as &ExamId) + sqlx::query!(r#"DELETE FROM answer_image WHERE exam = $1"#, target.id.uuid()) .execute(&mut *conn) .await?; - sqlx::query!(r#"DELETE FROM question_image WHERE exam = $1"#, target.id as &ExamId) + sqlx::query!(r#"DELETE FROM question_image WHERE exam = $1"#, target.id.uuid()) .execute(&mut *conn) .await?; // The cascaded questions give their subject references back, @@ -428,16 +428,16 @@ pub async fn delete(db: &Database, target: Exam) -> Result { GROUP BY subject) UPDATE subject s SET exam_question_count = GREATEST(s.exam_question_count - c.n, 0) FROM subs c WHERE s.id = c.subject"#, - target.id as &ExamId, + target.id.uuid(), ) .execute(&mut *conn) .await?; - sqlx::query!(r#"DELETE FROM exam_question WHERE exam = $1"#, target.id as &ExamId) + sqlx::query!(r#"DELETE FROM exam_question WHERE exam = $1"#, target.id.uuid()) .execute(&mut *conn) .await?; sqlx::query!( r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = $1"#, - target.id as &ExamId, + target.id.uuid(), ) .execute(&mut *conn) .await?; @@ -447,13 +447,13 @@ pub async fn delete(db: &Database, target: Exam) -> Result { RETURNING id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", title AS "title: ExamTitle", description AS "description: ExamDescription", - kind AS "kind: ExamKind", mode AS "mode: Option", - starts_at AS "starts_at: Option", - ends_at AS "ends_at: Option", - duration_ms AS "duration_ms: Option", + kind AS "kind: ExamKind", mode AS "mode: ExamMode", + starts_at AS "starts_at: Timestamp", + ends_at AS "ends_at: Timestamp", + duration_ms AS "duration_ms: ExamDuration", max_attempts AS "max_attempts: ExamAttemptLimit", allow_rejoin, allow_review, draft"#, - target.id as &ExamId, + target.id.uuid(), ) .fetch_optional(&mut *conn) .await?; diff --git a/src/db/exam_answer.rs b/src/db/exam_answer.rs index 4b60638..edf4a39 100644 --- a/src/db/exam_answer.rs +++ b/src/db/exam_answer.rs @@ -76,7 +76,7 @@ pub async fn save( // child insert whose parent is gone refuses itself — which is what // retired the bump-and-restore this used to ride on. tx_with_retry(db, false, async |conn| { - save_in(conn, question, user, seq, selected, text).await + save_in(conn, question, user, seq, selected.clone(), text.clone()).await }) .await } @@ -93,7 +93,7 @@ pub(crate) async fn save_in( ) -> Result { let touched = sqlx::query!( r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, - question.get_exam() as &ExamId, + question.get_exam().uuid(), ) .fetch_optional(&mut *conn) .await?; @@ -110,16 +110,16 @@ pub(crate) async fn save_in( updated_at = EXCLUDED.updated_at RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", app_user AS "user: UserId", seq, - selected AS "selected: Option", - text AS "text: Option", + selected AS "selected: ChoiceId", + text AS "text: AnswerText", updated_at AS "updated_at: Timestamp""#, - question.get_exam() as &ExamId, - question.get_id() as &ExamQuestionId, - user as &UserId, + question.get_exam().uuid(), + question.get_id().uuid(), + user.uuid(), + selected.as_ref().map(ChoiceId::as_str), + text.as_ref().map(AnswerText::as_str), + now.as_millis(), seq, - selected, - text, - now, ) .fetch_one(&mut *conn) .await @@ -136,13 +136,13 @@ pub async fn read( ExamAnswer, r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", app_user AS "user: UserId", seq, - selected AS "selected: Option", - text AS "text: Option", + selected AS "selected: ChoiceId", + text AS "text: AnswerText", updated_at AS "updated_at: Timestamp" FROM exam_answer WHERE question = $1 AND app_user = $2 AND seq = $3"#, - question as &ExamQuestionId, - user as &UserId, + question.uuid(), + user.uuid(), seq, ) .fetch_optional(db) @@ -158,8 +158,8 @@ pub async fn delete( ) -> Result<(), AppError> { sqlx::query!( r#"DELETE FROM exam_answer WHERE question = $1 AND app_user = $2 AND seq = $3"#, - question as &ExamQuestionId, - user as &UserId, + question.uuid(), + user.uuid(), seq, ) .execute(db) @@ -180,14 +180,14 @@ pub async fn list_for_exam_user( ExamAnswer, r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", app_user AS "user: UserId", seq, - selected AS "selected: Option", - text AS "text: Option", + selected AS "selected: ChoiceId", + text AS "text: AnswerText", updated_at AS "updated_at: Timestamp" FROM exam_answer WHERE exam = $1 AND app_user = $2 AND seq = $3 ORDER BY question ASC"#, - exam as &ExamId, - user as &UserId, + exam.uuid(), + user.uuid(), seq, ) .fetch_all(db) @@ -204,8 +204,8 @@ pub async fn list_seqs_for_user( let rows = sqlx::query!( r#"SELECT DISTINCT seq FROM exam_answer WHERE exam = $1 AND app_user = $2 ORDER BY seq ASC"#, - exam as &ExamId, - user as &UserId, + exam.uuid(), + user.uuid(), ) .fetch_all(db) .await?; @@ -218,11 +218,11 @@ pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result", - text AS "text: Option", + selected AS "selected: ChoiceId", + text AS "text: AnswerText", updated_at AS "updated_at: Timestamp" FROM exam_answer WHERE exam = $1 ORDER BY question ASC"#, - exam as &ExamId, + exam.uuid(), ) .fetch_all(db) .await?) @@ -237,8 +237,8 @@ pub async fn delete_for_exam_user( ) -> Result<(), AppError> { sqlx::query!( r#"DELETE FROM exam_answer WHERE exam = $1 AND app_user = $2"#, - exam as &ExamId, - user as &UserId, + exam.uuid(), + user.uuid(), ) .execute(db) .await?; diff --git a/src/db/exam_attempt.rs b/src/db/exam_attempt.rs index 1259997..555531b 100644 --- a/src/db/exam_attempt.rs +++ b/src/db/exam_attempt.rs @@ -7,7 +7,7 @@ use sqlx::PgConnection; use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::cap::Claimed; -use crate::domain::exam::ExamId; +use crate::domain::exam::{ExamId, ExamMode}; use crate::domain::exam_attempt::{ExamAttempt, ExamAttemptId}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -37,7 +37,7 @@ fn frozen_error() -> AppError { pub(crate) async fn freeze_gate(conn: &mut PgConnection, exam: &ExamId) -> Result<(), AppError> { let row = sqlx::query!( r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, - exam as &ExamId, + exam.uuid(), ) .fetch_optional(&mut *conn) .await?; @@ -46,11 +46,11 @@ pub(crate) async fn freeze_gate(conn: &mut PgConnection, exam: &ExamId) -> Resul } let sat = sqlx::query!( r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat"#, - exam as &ExamId, + exam.uuid(), ) .fetch_one(&mut *conn) .await?; - if sat.sat { + if sat.sat.unwrap_or(false) { return Err(frozen_error()); } Ok(()) @@ -73,11 +73,11 @@ pub async fn finish(db: &Database, attempt: ExamAttempt) -> Result", - left_at AS "left_at: Option""#, - Timestamp::now(), - id.exam, - id.user, + finished_at AS "finished_at: Timestamp", + left_at AS "left_at: Timestamp""#, + Timestamp::now().as_millis(), + id.exam.uuid(), + id.user.uuid(), id.seq, ) .fetch_optional(db) @@ -106,11 +106,11 @@ pub async fn set_left( WHERE exam = $2 AND app_user = $3 AND seq = $4 RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, started_at AS "started_at: Timestamp", - finished_at AS "finished_at: Option", - left_at AS "left_at: Option""#, - left_at, - id.exam, - id.user, + finished_at AS "finished_at: Timestamp", + left_at AS "left_at: Timestamp""#, + left_at.map(|at| at.as_millis()), + id.exam.uuid(), + id.user.uuid(), id.seq, ) .fetch_optional(db) @@ -139,10 +139,10 @@ pub async fn stamp_left_if_running( AND a.left_at IS NULL AND a.finished_at IS NULL AND (e.duration_ms IS NULL OR $4 < a.started_at + e.duration_ms) AND (e.duration_ms IS NOT NULL OR e.ends_at IS NULL OR $4 < e.ends_at)"#, - attempt_id.exam, - attempt_id.user, + attempt_id.exam.uuid(), + attempt_id.user.uuid(), attempt_id.seq, - now, + now.as_millis(), ) .execute(db) .await?; @@ -156,12 +156,12 @@ pub async fn read(db: &Database, id: &ExamAttemptId) -> Result", - left_at AS "left_at: Option" + finished_at AS "finished_at: Timestamp", + left_at AS "left_at: Timestamp" FROM exam_attempt WHERE exam = $1 AND app_user = $2 AND seq = $3"#, - id.exam, - id.user, + id.exam.uuid(), + id.user.uuid(), id.seq, ) .fetch_optional(db) @@ -179,14 +179,14 @@ pub async fn read_latest_for_user( ExamAttempt, r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, started_at AS "started_at: Timestamp", - finished_at AS "finished_at: Option", - left_at AS "left_at: Option" + finished_at AS "finished_at: Timestamp", + left_at AS "left_at: Timestamp" FROM exam_attempt WHERE exam = $1 AND app_user = $2 ORDER BY seq DESC LIMIT 1"#, - exam as &ExamId, - user as &UserId, + exam.uuid(), + user.uuid(), ) .fetch_optional(db) .await?) @@ -202,13 +202,13 @@ pub async fn list_for_user( ExamAttempt, r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, started_at AS "started_at: Timestamp", - finished_at AS "finished_at: Option", - left_at AS "left_at: Option" + finished_at AS "finished_at: Timestamp", + left_at AS "left_at: Timestamp" FROM exam_attempt WHERE exam = $1 AND app_user = $2 ORDER BY seq DESC"#, - exam as &ExamId, - user as &UserId, + exam.uuid(), + user.uuid(), ) .fetch_all(db) .await?) @@ -226,12 +226,12 @@ pub async fn list_unfinished_for_user( ExamAttempt, r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, started_at AS "started_at: Timestamp", - finished_at AS "finished_at: Option", - left_at AS "left_at: Option" + finished_at AS "finished_at: Timestamp", + left_at AS "left_at: Timestamp" FROM exam_attempt WHERE app_user = $1 AND finished_at IS NULL ORDER BY started_at, exam"#, - user as &UserId, + user.uuid(), ) .fetch_all(db) .await?) @@ -242,12 +242,12 @@ pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result", - left_at AS "left_at: Option" + finished_at AS "finished_at: Timestamp", + left_at AS "left_at: Timestamp" FROM exam_attempt WHERE exam = $1 ORDER BY started_at DESC, seq DESC"#, - exam as &ExamId, + exam.uuid(), ) .fetch_all(db) .await?) @@ -258,11 +258,11 @@ pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result Result { let row = sqlx::query!( r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat"#, - exam as &ExamId, + exam.uuid(), ) .fetch_one(db) .await?; - Ok(row.sat) + Ok(row.sat.unwrap_or(false)) } /// The sitting-create guard: the exam row locked `FOR UPDATE` and @@ -280,11 +280,11 @@ pub(crate) async fn guard_start( now: Timestamp, ) -> Result<(), AppError> { let row = sqlx::query!( - r#"SELECT draft AS "draft: bool", mode AS "mode: Option", - starts_at AS "starts_at: Option", - ends_at AS "ends_at: Option" + r#"SELECT draft AS "draft: bool", mode AS "mode: ExamMode", + starts_at AS "starts_at: Timestamp", + ends_at AS "ends_at: Timestamp" FROM exam WHERE id = $1 FOR UPDATE"#, - exam as &ExamId, + exam.uuid(), ) .fetch_optional(&mut *conn) .await?; @@ -336,13 +336,13 @@ pub(crate) async fn create_in( SELECT $1, $2, $3, $5, NULL, NULL WHERE EXISTS (SELECT 1 FROM seat) RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, started_at AS "started_at: Timestamp", - finished_at AS "finished_at: Option", - left_at AS "left_at: Option""#, - attempt.exam, - attempt.user, + finished_at AS "finished_at: Timestamp", + left_at AS "left_at: Timestamp""#, + attempt.exam.uuid(), + attempt.user.uuid(), attempt.seq, bump, - attempt.started_at, + attempt.started_at.as_millis(), ) .fetch_optional(&mut *conn) .await; diff --git a/src/db/exam_question.rs b/src/db/exam_question.rs index 2c8966c..90295bf 100644 --- a/src/db/exam_question.rs +++ b/src/db/exam_question.rs @@ -14,7 +14,8 @@ use crate::db::page::{PagedList, Param}; use crate::domain::bank_question::BankQuestionId; use crate::domain::exam::ExamId; use crate::domain::exam_question::{ - Choice, ExamQuestion, ExamQuestionId, QuestionPoints, QuestionSpec, QuestionText, + Choice, ChoiceId, ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, + QuestionText, }; use crate::domain::subject::SubjectId; use crate::error::{AppError, ValidationError}; @@ -29,6 +30,13 @@ fn dead_subject() -> AppError { }) } +/// The `choices` JSONB bind as the macros type the parameter — a +/// `serde_json::Value`. A `Choice` is two plain strings: serializing one +/// cannot fail. +fn choices_as_value(choices: &[Choice]) -> serde_json::Value { + serde_json::to_value(choices).expect("Choice serialization cannot fail") +} + pub async fn create( db: &Database, exam: &ExamId, @@ -71,7 +79,7 @@ async fn insert( text, points, kind: spec.kind, - choices: spec.choices, + choices: spec.choices.map(Json), correct: spec.correct, from_bank, // An insert never banks anything: only a to-bank save writes this. @@ -115,19 +123,22 @@ async fn claim_subject_and_insert( RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", subject AS "subject: SubjectId", text AS "text: QuestionText", kind AS "kind: QuestionKind", points AS "points: QuestionPoints", - choices AS "choices: Option>>", - correct AS "correct: Option", - from_bank AS "from_bank: Option", - banked_as AS "banked_as: Option""#, - question.subject, - question.id, - question.exam, - question.text, - question.kind, - question.points, - question.choices, - question.correct, - question.from_bank, + choices AS "choices: Json>", + correct AS "correct: ChoiceId", + from_bank AS "from_bank: BankQuestionId", + banked_as AS "banked_as: BankQuestionId""#, + question.subject.uuid(), + question.id.uuid(), + question.exam.uuid(), + question.text.as_str(), + question.kind.as_str(), + question.points.as_i64(), + question + .choices + .as_ref() + .map(|json| choices_as_value(&json.0)), + question.correct.as_ref().map(ChoiceId::as_str), + question.from_bank.as_ref().map(BankQuestionId::uuid), ) .fetch_optional(&mut *conn) .await?; @@ -140,12 +151,12 @@ pub async fn read(db: &Database, id: &ExamQuestionId) -> Result>>", - correct AS "correct: Option", - from_bank AS "from_bank: Option", - banked_as AS "banked_as: Option" + choices AS "choices: Json>", + correct AS "correct: ChoiceId", + from_bank AS "from_bank: BankQuestionId", + banked_as AS "banked_as: BankQuestionId" FROM exam_question WHERE id = $1"#, - id as &ExamQuestionId, + id.uuid(), ) .fetch_optional(db) .await?) @@ -204,8 +215,8 @@ pub async fn list_shared_with( WHERE q.exam = $2 AND (q.from_bank IN (SELECT t FROM shared) OR q.banked_as IN (SELECT t FROM shared))"#, - live, - exam as &ExamId, + &live, + exam.uuid(), ) .fetch_all(db) .await?; @@ -256,14 +267,14 @@ pub async fn update( r#"UPDATE subject SET exam_question_count = GREATEST(exam_question_count - 1, 0) WHERE id = $1"#, - previous as &SubjectId, + previous.uuid(), ) .execute(&mut *conn) .await?; let claimed = sqlx::query!( r#"UPDATE subject SET exam_question_count = subject.exam_question_count + 1 - WHERE id = $1 RETURNING 1"#, - next as &SubjectId, + WHERE id = $1 RETURNING 1 AS n"#, + next.uuid(), ) .fetch_optional(&mut *conn) .await?; @@ -285,18 +296,18 @@ pub async fn update( RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", subject AS "subject: SubjectId", text AS "text: QuestionText", kind AS "kind: QuestionKind", points AS "points: QuestionPoints", - choices AS "choices: Option>>", - correct AS "correct: Option", - from_bank AS "from_bank: Option", - banked_as AS "banked_as: Option""#, - question.id as &ExamQuestionId, - subject, - text, - points, - spec.kind, - spec.choices, - spec.correct, - question.subject as &SubjectId, + choices AS "choices: Json>", + correct AS "correct: ChoiceId", + from_bank AS "from_bank: BankQuestionId", + banked_as AS "banked_as: BankQuestionId""#, + question.id.uuid(), + subject.uuid(), + text.as_str(), + points.as_i64(), + spec.kind.as_str(), + spec.choices.as_deref().map(choices_as_value), + spec.correct.as_ref().map(ChoiceId::as_str), + question.subject.uuid(), ) .fetch_optional(&mut *conn) .await?; @@ -307,11 +318,11 @@ pub async fn update( // which is the 409. let live = sqlx::query!( r#"SELECT EXISTS(SELECT 1 FROM exam_question WHERE id = $1) AS live"#, - question.id as &ExamQuestionId, + question.id.uuid(), ) .fetch_one(&mut *conn) .await?; - if !live.live { + if !live.live.unwrap_or(false) { return Err(AppError::NotFound); } return Err(AppError::Conflict( @@ -346,12 +357,12 @@ pub async fn link_banked_as( RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", subject AS "subject: SubjectId", text AS "text: QuestionText", kind AS "kind: QuestionKind", points AS "points: QuestionPoints", - choices AS "choices: Option>>", - correct AS "correct: Option", - from_bank AS "from_bank: Option", - banked_as AS "banked_as: Option""#, - question.id as &ExamQuestionId, - template as &BankQuestionId, + choices AS "choices: Json>", + correct AS "correct: ChoiceId", + from_bank AS "from_bank: BankQuestionId", + banked_as AS "banked_as: BankQuestionId""#, + question.id.uuid(), + template.uuid(), ) .fetch_optional(db) .await?; @@ -369,13 +380,13 @@ pub async fn delete(db: &Database, question: ExamQuestion) -> Result Result>>", - correct AS "correct: Option", - from_bank AS "from_bank: Option", - banked_as AS "banked_as: Option""#, - question.id as &ExamQuestionId, + choices AS "choices: Json>", + correct AS "correct: ChoiceId", + from_bank AS "from_bank: BankQuestionId", + banked_as AS "banked_as: BankQuestionId""#, + question.id.uuid(), ) .fetch_optional(&mut *conn) .await?; @@ -401,7 +412,7 @@ pub async fn delete(db: &Database, question: ExamQuestion) -> Result Result Result Result { validate_installments(&installments)?; + let installments = serde_json::to_value(&installments) + .map_err(|e| AppError::Internal(format!("fee plan encode: {e}")))?; let id = FeePlanId::generate(); let created_at = Timestamp::now(); sqlx::query_as!( FeePlan, "INSERT INTO fee_plan (id, name, installments, created_by, created_at) \ VALUES ($1, $2, $3, $4, $5) \ - RETURNING id, name, installments, created_by, created_at", - id, - name, - sqlx::types::Json(installments), - created_by, - created_at, + RETURNING id AS \"id: FeePlanId\", name AS \"name: FeePlanName\", installments AS \"installments: sqlx::types::Json>\", created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"", + id.uuid(), + name.as_str(), + installments, + created_by.uuid(), + created_at.as_millis(), ) .fetch_one(db) .await @@ -49,9 +51,9 @@ pub async fn create( pub async fn read(db: &Database, id: &FeePlanId) -> Result, AppError> { sqlx::query_as!( FeePlan, - "SELECT id, name, installments, created_by, created_at \ + "SELECT id AS \"id: FeePlanId\", name AS \"name: FeePlanName\", installments AS \"installments: sqlx::types::Json>\", created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\" FROM fee_plan WHERE id = $1", - id, + id.uuid(), ) .fetch_optional(db) .await @@ -103,15 +105,20 @@ pub async fn update( // is the whole answer, assigned or not. return read(db, &plan.id).await?.ok_or(AppError::NotFound); } + let installments = installments + .as_ref() + .map(serde_json::to_value) + .transpose() + .map_err(|e| AppError::Internal(format!("fee plan encode: {e}")))?; let edited = sqlx::query_as!( FeePlan, "UPDATE fee_plan \ SET name = COALESCE($2, name), installments = COALESCE($3, installments) \ WHERE id = $1 AND assignment_count = 0 \ - RETURNING id, name, installments, created_by, created_at", - plan.id, + RETURNING id AS \"id: FeePlanId\", name AS \"name: FeePlanName\", installments AS \"installments: sqlx::types::Json>\", created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"", + plan.id.uuid(), name.map(|n| n.as_str().to_string()), - installments.map(sqlx::types::Json), + installments, ) .fetch_optional(db) .await?; @@ -143,7 +150,7 @@ pub async fn update( pub async fn delete(db: &Database, plan: FeePlan) -> Result { let deleted = sqlx::query!( "DELETE FROM fee_plan WHERE id = $1 AND assignment_count = 0 RETURNING id", - plan.id, + plan.id.uuid(), ) .fetch_optional(db) .await?; diff --git a/src/db/fee_plan_assignment.rs b/src/db/fee_plan_assignment.rs index 9f6fd66..13bb9ed 100644 --- a/src/db/fee_plan_assignment.rs +++ b/src/db/fee_plan_assignment.rs @@ -18,10 +18,10 @@ pub async fn read( ) -> Result, AppError> { sqlx::query_as!( FeePlanAssignment, - "SELECT plan, student, assigned_by, created_at \ + "SELECT plan AS \"plan: FeePlanId\", student AS \"student: UserId\", assigned_by AS \"assigned_by: UserId\", created_at AS \"created_at: Timestamp\" FROM fee_plan_assignment WHERE plan = $1 AND student = $2", - id.plan, - id.student, + id.plan.uuid(), + id.student.uuid(), ) .fetch_optional(db) .await @@ -58,13 +58,13 @@ pub async fn create( RETURNING 1) INSERT INTO fee_plan_assignment (plan, student, assigned_by, created_at) SELECT $3, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) - RETURNING plan, student, assigned_by, created_at"#, - plan, + RETURNING plan AS "plan: FeePlanId", student AS "student: UserId", assigned_by AS "assigned_by: UserId", created_at AS "created_at: Timestamp""#, + plan.uuid(), cap::UNLIMITED, - plan, - student, - assigned_by, - created_at, + plan.uuid(), + student.uuid(), + assigned_by.uuid(), + created_at.as_millis(), ) .fetch_optional(db) .await; @@ -101,13 +101,13 @@ pub async fn list_for_plan( /// can be behind. Kept because a *test* asserting the rows and the counter /// agree is the only thing that would catch the counter drifting. pub async fn exists_for_plan(db: &Database, plan: &FeePlanId) -> Result { - let (exists,) = sqlx::query!( - "SELECT EXISTS (SELECT 1 FROM fee_plan_assignment WHERE plan = $1)", - plan + let row = sqlx::query!( + "SELECT EXISTS (SELECT 1 FROM fee_plan_assignment WHERE plan = $1) AS \"exists!\"", + plan.uuid() ) .fetch_one(db) .await?; - Ok(exists) + Ok(row.exists) } /// Which plans a student is on — one student may hold several. diff --git a/src/db/field_update.rs b/src/db/field_update.rs index 7f4f657..ba14470 100644 --- a/src/db/field_update.rs +++ b/src/db/field_update.rs @@ -125,7 +125,12 @@ impl FieldUpdate { /// row stays editable field by field. `NULL` on either side passes, /// exactly like [`crate::web::check_time_range`] skipping an absent end. #[must_use] - pub(crate) fn ordered(mut self, low: &'static str, high: &'static str, refused: AppError) -> Self { + pub(crate) fn ordered( + mut self, + low: &'static str, + high: &'static str, + refused: AppError, + ) -> Self { self.ordered = Some((low, high, refused)); self } @@ -374,71 +379,75 @@ async fn run_with_refcount( where T: for<'r> FromRow<'r, PgRow> + Send + Unpin, { - let mut slot: Option = Some(refused); - let outcome = tx_with_retry(db, false, async |tx| { + // Owned captures + `async move`: the closure's future must be Send and + // general enough for axum's handler registration — borrowed captures + // (`async |tx|` over `&mut`/`&T`) fail that check tree-wide. + let mut refused = Some(refused); + let outcome = tx_with_retry(db, false, async move |tx| { let binds = binds.clone(); - if let Some(release) = release { - sqlx::query(AssertSqlSafe(format!( - "UPDATE {counter_table} \ + if let Some(release) = release { + sqlx::query(AssertSqlSafe(format!( + "UPDATE {counter_table} \ SET {counter_field} = GREATEST({counter_field} - 1, 0) WHERE id = $1" - ))) - .bind(release) - .execute(&mut *tx) - .await?; - } - // The conditional claim doubles as the existence check: zero rows - // is the claimed row being gone, the caller's own refusal. - if let Some(claim) = claim { - let seat: Option = sqlx::query_scalar(AssertSqlSafe(format!( - "UPDATE {counter_table} SET {counter_field} = {counter_field} + 1 \ + ))) + .bind(release) + .execute(&mut *tx) + .await?; + } + // The conditional claim doubles as the existence check: zero rows + // is the claimed row being gone, the caller's own refusal. + if let Some(claim) = claim { + let seat: Option = sqlx::query_scalar(AssertSqlSafe(format!( + "UPDATE {counter_table} SET {counter_field} = {counter_field} + 1 \ WHERE id = $1 RETURNING 1" - ))) - .bind(claim) - .fetch_optional(&mut *tx) - .await?; - if seat.is_none() { - return Err(slot.take().unwrap_or_else(|| mark(REFUSAL_MARK))); - } - } - let mut args = PgArguments::default(); - for bind in binds.iter().cloned() { - bind.add_to(&mut args); - } - let rows: Vec = sqlx::query_as_with(AssertSqlSafe(update.as_str()), args) - .fetch_all(&mut *tx) - .await?; - if !rows.is_empty() { - return Ok(rows); - } - // Zero rows: the caller's own guard bit, the row deleted in the - // window after the handler's read, or — the CAS only — the link - // moved since the handler read it. Nothing was written yet either - // way, so the probe that tells the cases apart is free: it matches - // only a row that is *there*, whose *own* guards still hold, and - // whose link has moved off what the handler read — which is the - // CAS, and nothing else, having bitten. Carrying the caller's - // guards is what keeps that true when a write is refused for - // *both* reasons at once: a `.guard()`/`.ordered()` refusal is the - // caller's own answer to give, and reporting it as "the link - // moved" would send the client to re-read a link that was never - // its problem. - let mut args = PgArguments::default(); - for bind in binds { - bind.add_to(&mut args); - } - let live: Option = sqlx::query_scalar_with(AssertSqlSafe(probe.as_str()), args) - .fetch_optional(&mut *tx) - .await?; - match live { - Some(_) => Err(mark(STALE_MARK)), - None => Err(mark(GONE_MARK)), + ))) + .bind(claim) + .fetch_optional(&mut *tx) + .await?; + if seat.is_none() { + return Err(refused.take().unwrap_or_else(|| mark(REFUSAL_MARK))); } + } + let mut args = PgArguments::default(); + for bind in binds.iter().cloned() { + bind.add_to(&mut args); + } + let rows: Vec = sqlx::query_as_with(AssertSqlSafe(update.as_str()), args) + .fetch_all(&mut *tx) + .await?; + if !rows.is_empty() { + return Ok(rows); + } + // Zero rows: the caller's own guard bit, the row deleted in the + // window after the handler's read, or — the CAS only — the link + // moved since the handler read it. Nothing was written yet either + // way, so the probe that tells the cases apart is free: it matches + // only a row that is *there*, whose *own* guards still hold, and + // whose link has moved off what the handler read — which is the + // CAS, and nothing else, having bitten. Carrying the caller's + // guards is what keeps that true when a write is refused for + // *both* reasons at once: a `.guard()`/`.ordered()` refusal is the + // caller's own answer to give, and reporting it as "the link + // moved" would send the client to re-read a link that was never + // its problem. + let mut args = PgArguments::default(); + for bind in binds { + bind.add_to(&mut args); + } + let live: Option = sqlx::query_scalar_with(AssertSqlSafe(probe.as_str()), args) + .fetch_optional(&mut *tx) + .await?; + match live { + Some(_) => Err(mark(STALE_MARK)), + None => Err(mark(GONE_MARK)), + } }) .await; match outcome { - Err(AppError::Internal(m)) if m == REFUSAL_MARK => { - Err(slot.take().unwrap_or_else(|| mark(REFUSAL_MARK))) - } + // The mark only ever leaves the closure once the real refusal was + // spent, so it is the final answer here (today's slot.take() could + // never resurrect it either). + Err(AppError::Internal(m)) if m == REFUSAL_MARK => Err(mark(REFUSAL_MARK)), Err(AppError::Internal(m)) if m == STALE_MARK => Err(AppError::Conflict(STALE_MOVE)), // The row is gone: exactly the "wrote nothing" answer the plain path // reports, so the caller's refusal is unchanged. @@ -446,4 +455,3 @@ where other => other, } } - diff --git a/src/db/meal_attendance.rs b/src/db/meal_attendance.rs index a848c83..b061844 100644 --- a/src/db/meal_attendance.rs +++ b/src/db/meal_attendance.rs @@ -39,13 +39,15 @@ pub async fn mark( marked_by: &UserId, ) -> Result { let marked_at = Timestamp::now(); + // Owned captures (`Send` rule of `tx_with_retry` closures). + let menu_key = menu.key().to_string(); let student = *student; let marked_by = *marked_by; - tx_with_retry(db, false, async |tx| { + tx_with_retry(db, false, async move |tx| { let bumped = sqlx::query!( "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 RETURNING 1 AS bumped", - menu.key(), + menu_key, ) .fetch_optional(&mut *tx) .await?; @@ -60,12 +62,14 @@ pub async fn mark( SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by, marked_at = EXCLUDED.marked_at - RETURNING menu, student, status, marked_by, marked_at", - menu.key(), - student, - status, - marked_by, - marked_at, + RETURNING menu AS \"menu: MenuId\", student AS \"student: UserId\", + status AS \"status: MealAttendanceStatus\", marked_by AS \"marked_by: UserId\", + marked_at AS \"marked_at: Timestamp\"", + menu_key, + student.uuid(), + status.as_str(), + marked_by.uuid(), + marked_at.as_millis(), ) .fetch_one(&mut *tx) .await?; diff --git a/src/db/meal_booking.rs b/src/db/meal_booking.rs index 06cf601..1d395e6 100644 --- a/src/db/meal_booking.rs +++ b/src/db/meal_booking.rs @@ -8,7 +8,7 @@ use crate::database::{Database, tx_with_retry}; use crate::db::cap::Claimed; use crate::db::page::PagedList; -use crate::domain::meal_booking::{MealBooking, MealBookingId}; +use crate::domain::meal_booking::{MealBooking, MealBookingId, MealBookingStatus}; use crate::domain::meal_ledger::{LedgerAmount, MealLedger}; use crate::domain::menu::MenuId; use crate::domain::timestamp::Timestamp; @@ -18,10 +18,10 @@ use crate::error::AppError; pub async fn read(db: &Database, id: &MealBookingId) -> Result, AppError> { let row = sqlx::query_as!( MealBooking, - "SELECT menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at + "SELECT menu AS \"menu: MenuId\", student AS \"student: UserId\", booked_by AS \"booked_by: UserId\", status AS \"status: MealBookingStatus\", attempt, price_minor AS \"price_minor: LedgerAmount\", cancelled_at AS \"cancelled_at: Timestamp\", created_at AS \"created_at: Timestamp\" FROM meal_booking WHERE menu = $1 AND student = $2", id.menu().key(), - *id.student(), + id.student().uuid(), ) .fetch_optional(db) .await?; @@ -64,14 +64,14 @@ pub async fn list_for_students( if students.is_empty() { return Ok((Vec::new(), 0)); } - let keys: Vec = students.iter().map(UserId::key).collect(); + let ids: Vec = students.iter().map(UserId::uuid).collect(); let rows = sqlx::query_as!( MealBooking, - "SELECT menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at + "SELECT menu AS \"menu: MenuId\", student AS \"student: UserId\", booked_by AS \"booked_by: UserId\", status AS \"status: MealBookingStatus\", attempt, price_minor AS \"price_minor: LedgerAmount\", cancelled_at AS \"cancelled_at: Timestamp\", created_at AS \"created_at: Timestamp\" FROM meal_booking WHERE student = ANY($1::uuid[]) ORDER BY created_at DESC, menu DESC LIMIT $2 OFFSET $3", - keys, + &ids, limit, offset, ) @@ -81,10 +81,11 @@ pub async fn list_for_students( let total = if limit.is_some() || offset != 0 { sqlx::query_scalar!( "SELECT count(*) FROM meal_booking WHERE student = ANY($1::uuid[])", - keys, + &ids, ) .fetch_one(db) - .await? as i64 + .await? + .unwrap_or(0) } else { rows.len() as i64 }; @@ -133,9 +134,28 @@ pub(crate) async fn claim_and_place( charge: Option<&MealLedger>, ) -> Result, AppError> { let menu_key = menu.key().to_string(); - let student = row.student; + let student = row.student.uuid(); let attempt = row.attempt; - tx_with_retry(db, false, async |tx| { + // Owned captures only: a closure holding a `&T` fails the higher-ranked + // `Send` check `tx_with_retry`'s future must pass. + let booked_by = row.booked_by.uuid(); + let status = row.status.as_str(); + let cancelled_at = row.cancelled_at.map(|t| t.as_millis()); + let created_at = row.created_at.as_millis(); + let charge = charge.map(|line| { + ( + line.id.key().to_string(), + line.student.uuid(), + line.kind.as_str(), + line.amount_minor.as_minor(), + line.source.clone(), + line.method.as_ref().map(|m| m.as_str().to_string()), + line.note.as_ref().map(|n| n.as_str().to_string()), + line.recorded_by.uuid(), + line.created_at.as_millis(), + ) + }); + tx_with_retry(db, false, async move |tx| { // Already held? Same attempt, same price it was taken at — answered // as `Duplicate`, which the caller replays into the winner's row // (and its charge) without claiming anything. @@ -175,12 +195,12 @@ pub(crate) async fn claim_and_place( "UPDATE meal_booking SET status = 'booked', attempt = $3, price_minor = $4, cancelled_at = NULL WHERE menu = $1 AND student = $2 - AND status = 'cancelled' AND attempt = $3 - 1 - RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at", + AND status = 'cancelled' AND attempt = $3::bigint - 1 + RETURNING menu AS \"menu: MenuId\", student AS \"student: UserId\", booked_by AS \"booked_by: UserId\", status AS \"status: MealBookingStatus\", attempt, price_minor AS \"price_minor: LedgerAmount\", cancelled_at AS \"cancelled_at: Timestamp\", created_at AS \"created_at: Timestamp\"", menu_key, student, attempt, - price, + price.map(LedgerAmount::as_minor), ) .fetch_optional(&mut *tx) .await?; @@ -196,15 +216,15 @@ pub(crate) async fn claim_and_place( (menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (menu, student) DO NOTHING - RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at", + RETURNING menu AS \"menu: MenuId\", student AS \"student: UserId\", booked_by AS \"booked_by: UserId\", status AS \"status: MealBookingStatus\", attempt, price_minor AS \"price_minor: LedgerAmount\", cancelled_at AS \"cancelled_at: Timestamp\", created_at AS \"created_at: Timestamp\"", menu_key, student, - row.booked_by, - row.status, - row.attempt, - price, - row.cancelled_at, - row.created_at, + booked_by, + status, + attempt, + price.map(LedgerAmount::as_minor), + cancelled_at, + created_at, ) .fetch_optional(&mut *tx) .await?; @@ -216,21 +236,23 @@ pub(crate) async fn claim_and_place( }; // The charge rides the same transaction; already there (a replayed // POST of this seat) means fine — nothing is written twice. - if let Some(line) = charge { + if let Some((id, student, kind, amount, source, method, note, recorded_by, created_at)) = + &charge + { sqlx::query!( "INSERT INTO meal_ledger (id, student, kind, amount_minor, source, method, note, recorded_by, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) ON CONFLICT (id) DO NOTHING", - line.id.key(), - line.student, - line.kind, - line.amount_minor, - line.source, - line.method, - line.note, - line.recorded_by, - line.created_at, + id.as_str(), + student, + kind, + amount, + source.as_deref(), + method.as_deref(), + note.as_deref(), + recorded_by, + created_at, ) .execute(&mut *tx) .await?; @@ -278,18 +300,18 @@ pub async fn release_seat( ) -> Result, AppError> { let refund = MealLedger::reversal_for(booked, recorded_by); let menu_key = booked.menu.key().to_string(); - let student = booked.student; + let student = booked.student.uuid(); let attempt = booked.attempt; let cancelled_at = Timestamp::now(); - tx_with_retry(db, false, async |tx| { + tx_with_retry(db, false, async move |tx| { let flipped = sqlx::query_as!( MealBooking, "UPDATE meal_booking SET status = 'cancelled', cancelled_at = $3 WHERE menu = $1 AND student = $2 AND status = 'booked' AND attempt = $4 - RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at", + RETURNING menu AS \"menu: MenuId\", student AS \"student: UserId\", booked_by AS \"booked_by: UserId\", status AS \"status: MealBookingStatus\", attempt, price_minor AS \"price_minor: LedgerAmount\", cancelled_at AS \"cancelled_at: Timestamp\", created_at AS \"created_at: Timestamp\"", menu_key, student, - cancelled_at, + cancelled_at.as_millis(), attempt, ) .fetch_optional(&mut *tx) @@ -326,14 +348,14 @@ pub async fn release_seat( VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) ON CONFLICT (id) DO NOTHING", line.id.key(), - line.student, - line.kind, - line.amount_minor, - line.source, - line.method, - line.note, - line.recorded_by, - line.created_at, + line.student.uuid(), + line.kind.as_str(), + line.amount_minor.as_minor(), + line.source.as_deref(), + line.method.as_ref().map(|m| m.as_str()), + line.note.as_ref().map(|n| n.as_str()), + line.recorded_by.uuid(), + line.created_at.as_millis(), ) .execute(&mut *tx) .await?; diff --git a/src/db/meal_ledger.rs b/src/db/meal_ledger.rs index f4266dc..3f74054 100644 --- a/src/db/meal_ledger.rs +++ b/src/db/meal_ledger.rs @@ -5,7 +5,10 @@ use crate::database::Database; use crate::db::page::PagedList; -use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId}; +use crate::domain::meal_ledger::{ + LedgerAmount, LedgerMethod, LedgerNote, MealLedger, MealLedgerId, MealLedgerKind, +}; +use crate::domain::timestamp::Timestamp; use crate::domain::menu::MenuId; use crate::domain::user::UserId; use crate::error::AppError; @@ -31,16 +34,16 @@ pub(crate) async fn append(db: &Database, row: MealLedger) -> Result Result Result, AppError> { let row = sqlx::query_as!( MealLedger, - "SELECT id, student, kind, amount_minor, source, method, note, recorded_by, created_at + "SELECT id AS \"id: MealLedgerId\", student AS \"student: UserId\", kind AS \"kind: MealLedgerKind\", amount_minor AS \"amount_minor: LedgerAmount\", source, method AS \"method: LedgerMethod\", note AS \"note: LedgerNote\", recorded_by AS \"recorded_by: UserId\", created_at AS \"created_at: Timestamp\" FROM meal_ledger WHERE id = $1", id.key(), ) @@ -77,7 +80,7 @@ pub async fn price_snapshot( menu: &MenuId, ) -> Result, AppError> { let row = - sqlx::query!("SELECT CAST(COALESCE(sum(price_minor), 0) AS BIGINT) AS total FROM menu_dish WHERE menu = $1", menu.key()) + sqlx::query!("SELECT CAST(COALESCE(sum(price_minor), 0) AS BIGINT) AS \"total!\" FROM menu_dish WHERE menu = $1", menu.key()) .fetch_one(db) .await?; let total = row.total; @@ -98,7 +101,7 @@ pub async fn list_for_student( "meal_ledger WHERE student = $1", "ORDER BY created_at DESC, id DESC", ) - .bind(student.key()) + .bind(student.uuid()) .run(limit, offset, db) .await } @@ -127,9 +130,9 @@ pub async fn list_for_student( pub async fn balance_of(db: &Database, student: &UserId) -> Result { let totals = sqlx::query!( r#"SELECT kind AS "kind: crate::domain::meal_ledger::MealLedgerKind", - CAST(sum(amount_minor) AS BIGINT) AS total + CAST(sum(amount_minor) AS BIGINT) AS "total!" FROM meal_ledger WHERE student = $1 GROUP BY kind"#, - *student, + student.uuid(), ) .fetch_all(db) .await?; diff --git a/src/db/menu.rs b/src/db/menu.rs index 40c7ebb..ccac24a 100644 --- a/src/db/menu.rs +++ b/src/db/menu.rs @@ -41,7 +41,7 @@ pub async fn create( let slot_s = slot.as_str().to_string(); let created_by = *created_by; let created_at = Timestamp::now(); - tx_with_retry(db, false, async |tx| { + tx_with_retry(db, false, async move |tx| { // Duplicate gate ahead of the retired check: "already published" // outranks "slot retired", on the very path a rival publish races. let exists = sqlx::query!("SELECT 1 AS taken FROM menu WHERE id = $1", id_key,) @@ -62,15 +62,15 @@ pub async fn create( ) INSERT INTO menu (id, date, slot, capacity, version, created_by, created_at) SELECT $1, $3, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM ref) - RETURNING id, date, slot, capacity, version, created_by, created_at", + RETURNING id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"", id_key, counter, date_s, slot_s, capacity, Some(0i64), - created_by, - created_at, + created_by.uuid(), + created_at.as_millis(), ) .fetch_optional(&mut *tx) .await @@ -102,7 +102,7 @@ pub async fn create( pub async fn read(db: &Database, id: &MenuId) -> Result, AppError> { let row = sqlx::query_as!( Menu, - "SELECT id, date, slot, capacity, version, created_by, created_at + "SELECT id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\" FROM menu WHERE id = $1", id.key(), ) @@ -119,7 +119,7 @@ pub async fn find( ) -> Result, AppError> { let row = sqlx::query_as!( Menu, - "SELECT id, date, slot, capacity, version, created_by, created_at + "SELECT id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\" FROM menu WHERE date = $1 AND slot = $2 LIMIT 1", date.as_str(), slot.as_str(), @@ -174,7 +174,7 @@ pub async fn update( Menu, "UPDATE menu SET capacity = $2, version = COALESCE(version, 0) + 1 WHERE id = $1 - RETURNING id, date, slot, capacity, version, created_by, created_at", + RETURNING id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"", menu.id.key(), capacity, ) @@ -217,11 +217,11 @@ pub async fn update( pub async fn delete(db: &Database, menu: Menu) -> Result { let key = menu.id.key().to_string(); let counter = slot_ref(menu.slot.as_str()); - let deleted = tx_with_retry(db, true, async |tx| { + let deleted = tx_with_retry(db, true, async move |tx| { let deleted = sqlx::query_as!( Menu, "DELETE FROM menu WHERE id = $1 AND seats_booked = 0 - RETURNING id, date, slot, capacity, version, created_by, created_at", + RETURNING id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"", key, ) .fetch_optional(&mut *tx) diff --git a/src/db/menu_dish.rs b/src/db/menu_dish.rs index e66d605..e65c4b6 100644 --- a/src/db/menu_dish.rs +++ b/src/db/menu_dish.rs @@ -32,7 +32,7 @@ pub async fn create( let menu_key = menu.key().to_string(); let id = MenuDishId::generate(); let created_at = Timestamp::now(); - tx_with_retry(db, false, async |tx| { + tx_with_retry(db, false, async move |tx| { // The lock first: every later statement in this transaction then // sees the committed state of whoever queued ahead of it. let locked = sqlx::query!( @@ -55,14 +55,14 @@ pub async fn create( "INSERT INTO menu_dish (id, menu, name, description, price_minor, tags, created_at) SELECT $1, $2, $3, $4, $5, $6, $7 WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $8 - RETURNING id, menu, name, description, price_minor, tags, created_at", - id, + RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"", + id.uuid(), menu_key, - name, - description, - price_minor, - tags, - created_at, + name.as_str(), + description.as_ref().map(|d| d.as_str()), + price_minor.as_minor(), + tags.as_slice(), + created_at.as_millis(), cap, ) .fetch_optional(&mut *tx) @@ -81,9 +81,9 @@ pub async fn create( pub async fn read(db: &Database, id: &MenuDishId) -> Result, AppError> { let row = sqlx::query_as!( MenuDish, - "SELECT id, menu, name, description, price_minor, tags, created_at + "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\" FROM menu_dish WHERE id = $1", - id.key(), + id.uuid(), ) .fetch_optional(db) .await?; @@ -104,9 +104,9 @@ pub async fn list_for_menus(db: &Database, menus: &[MenuId]) -> Result = menus.iter().map(|m| m.key().to_string()).collect(); let rows = sqlx::query_as!( MenuDish, - "SELECT id, menu, name, description, price_minor, tags, created_at + "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\" FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC", - keys, + &keys, ) .fetch_all(db) .await?; @@ -131,9 +131,9 @@ pub async fn update( price_minor: Option, tags: Option, ) -> Result { - let dish_key = dish.id.key(); + let dish_key = dish.id.uuid(); let menu_key = dish.menu.key().to_string(); - tx_with_retry(db, false, async |tx| { + tx_with_retry(db, false, async move |tx| { let bumped = sqlx::query!( "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 RETURNING 1 AS bumped", @@ -152,16 +152,13 @@ pub async fn update( price_minor = COALESCE($5, price_minor), tags = COALESCE($6, tags) WHERE id = $1 - RETURNING id, menu, name, description, price_minor, tags, created_at", + RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"", dish_key, - name.map(|n| n.as_str().to_string()), + name.as_ref().map(|n| n.as_str()), description.is_some(), - description - .clone() - .flatten() - .map(|d| d.as_str().to_string()), + description.as_ref().and_then(|d| d.as_ref()).map(|d| d.as_str()), price_minor.map(DishPrice::as_minor), - tags.map(|t| t.as_slice().to_vec()), + tags.as_ref().map(|t| t.as_slice()), ) .fetch_optional(&mut *tx) .await?; @@ -171,9 +168,9 @@ pub async fn update( } pub async fn delete(db: &Database, dish: MenuDish) -> Result { - let dish_key = dish.id.key(); + let dish_key = dish.id.uuid(); let menu_key = dish.menu.key().to_string(); - tx_with_retry(db, false, async |tx| { + tx_with_retry(db, false, async move |tx| { let bumped = sqlx::query!( "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 RETURNING 1 AS bumped", @@ -187,7 +184,7 @@ pub async fn delete(db: &Database, dish: MenuDish) -> Result let row = sqlx::query_as!( MenuDish, "DELETE FROM menu_dish WHERE id = $1 - RETURNING id, menu, name, description, price_minor, tags, created_at", + RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"", dish_key, ) .fetch_optional(&mut *tx) diff --git a/src/db/message.rs b/src/db/message.rs index ec62ef1..87d0cec 100644 --- a/src/db/message.rs +++ b/src/db/message.rs @@ -27,7 +27,7 @@ pub async fn send( sender_folder, recipient_folder, sender_origin, recipient_origin) VALUES ($1, $2, $3, $4, $5, $6, $7, false, 'sent', 'inbox', NULL, NULL) RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ - subject, body, label AS \"label: MessageLabel\", \ + subject AS \"subject: MessageSubject\", body AS \"body: MessageBody\", label AS \"label: MessageLabel\", \ sent_at AS \"sent_at: Timestamp\", read, \ sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", @@ -83,7 +83,7 @@ pub async fn list_folder( if read.is_some() { from.push_str(&format!(" AND read = ${}", if home_arm { 3 } else { 2 })); } - let mut builder = PagedList::new(from, "ORDER BY id DESC").bind(user); + let mut builder = PagedList::new(from, "ORDER BY id DESC").bind(user.uuid()); if home_arm { builder = builder.bind(folder.as_str().to_string()); } @@ -103,7 +103,7 @@ pub async fn read_for( let message = query_as!( Message, "SELECT id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ - subject, body, label AS \"label: MessageLabel\", \ + subject AS \"subject: MessageSubject\", body AS \"body: MessageBody\", label AS \"label: MessageLabel\", \ sent_at AS \"sent_at: Timestamp\", read, \ sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\" \ @@ -125,12 +125,12 @@ pub async fn set_read(db: &Database, message: Message, read: bool) -> Result Resul "UPDATE message SET sender_folder = 'deleted', sender_origin = NULL \ WHERE id = $1 AND sender_folder = 'trash' \ RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ - subject, body, label AS \"label: MessageLabel\", \ + subject AS \"subject: MessageSubject\", body AS \"body: MessageBody\", label AS \"label: MessageLabel\", \ sent_at AS \"sent_at: Timestamp\", read, \ sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", @@ -225,7 +225,7 @@ pub async fn delete_for(db: &Database, message: Message, user: &UserId) -> Resul "UPDATE message SET recipient_folder = 'deleted', recipient_origin = NULL \ WHERE id = $1 AND recipient_folder = 'trash' \ RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ - subject, body, label AS \"label: MessageLabel\", \ + subject AS \"subject: MessageSubject\", body AS \"body: MessageBody\", label AS \"label: MessageLabel\", \ sent_at AS \"sent_at: Timestamp\", read, \ sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", @@ -244,7 +244,7 @@ pub async fn delete_for(db: &Database, message: Message, user: &UserId) -> Resul Message, "DELETE FROM message WHERE id = $1 \ RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ - subject, body, label AS \"label: MessageLabel\", \ + subject AS \"subject: MessageSubject\", body AS \"body: MessageBody\", label AS \"label: MessageLabel\", \ sent_at AS \"sent_at: Timestamp\", read, \ sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", diff --git a/src/db/note.rs b/src/db/note.rs index 36b5caa..c7e919a 100644 --- a/src/db/note.rs +++ b/src/db/note.rs @@ -5,7 +5,7 @@ use crate::database::{Database, tx_with_retry}; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; -use crate::domain::note_file::NoteFile; +use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId}; use crate::domain::user::UserId; use crate::error::AppError; @@ -26,11 +26,12 @@ pub async fn create( Note, r#"INSERT INTO note (id, app_user, title, content) VALUES ($1, $2, $3, $4) - RETURNING id, app_user AS "user", title, content"#, - note.id, - note.user, - note.title, - note.content + RETURNING id AS "id: NoteId", app_user AS "user: UserId", + title AS "title: NoteTitle", content AS "content: NoteContent""#, + note.id.uuid(), + note.user.uuid(), + note.title.as_str(), + note.content.as_str() ) .fetch_one(db) .await?; @@ -45,9 +46,10 @@ pub async fn read_owned( ) -> Result, AppError> { let note = sqlx::query_as!( Note, - r#"SELECT id, app_user AS "user", title, content FROM note WHERE id = $1 AND app_user = $2"#, - id, - owner + r#"SELECT id AS "id: NoteId", app_user AS "user: UserId", + title AS "title: NoteTitle", content AS "content: NoteContent" FROM note WHERE id = $1 AND app_user = $2"#, + id.uuid(), + owner.uuid() ) .fetch_optional(db) .await?; @@ -106,20 +108,23 @@ pub async fn update( /// separate `delete_for_note` call stays, as a harmless idempotent repeat. pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec), AppError> { tx_with_retry(db, true, async |conn| { - sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id) + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id.uuid()) .execute(&mut *conn) .await?; let files = sqlx::query_as!( NoteFile, - r#"DELETE FROM note_file WHERE note = $1 RETURNING id, note, name, content_type, size"#, - note.id + r#"DELETE FROM note_file WHERE note = $1 + RETURNING id AS "id: NoteFileId", note AS "note: NoteId", name AS "name: FileName", + content_type AS "content_type: FileContentType", size"#, + note.id.uuid() ) .fetch_all(&mut *conn) .await?; let gone = sqlx::query_as!( Note, - r#"DELETE FROM note WHERE id = $1 RETURNING id, app_user AS "user", title, content"#, - note.id + r#"DELETE FROM note WHERE id = $1 RETURNING id AS "id: NoteId", app_user AS "user: UserId", + title AS "title: NoteTitle", content AS "content: NoteContent""#, + note.id.uuid() ) .fetch_optional(&mut *conn) .await?; diff --git a/src/db/note_file.rs b/src/db/note_file.rs index bd38aff..54803cb 100644 --- a/src/db/note_file.rs +++ b/src/db/note_file.rs @@ -6,7 +6,7 @@ use crate::constant::MAX_NOTE_FILES; use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::page::PagedList; use crate::domain::note::NoteId; -use crate::domain::note_file::{NoteFile, NoteFileId}; +use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId}; use crate::error::AppError; /// Persist the row assembled by [`NoteFile::new`], refusing once its note @@ -28,12 +28,13 @@ pub async fn insert(db: &Database, file: NoteFile) -> Result RETURNING 1) INSERT INTO note_file (id, note, name, content_type, size) SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) - RETURNING id, note, name, content_type, size"#, - file.note, + RETURNING id AS "id: NoteFileId", note AS "note: NoteId", name AS "name: FileName", + content_type AS "content_type: FileContentType", size"#, + file.note.uuid(), MAX_NOTE_FILES as i64, - file.id, - file.name, - file.content_type, + file.id.uuid(), + file.name.as_str(), + file.content_type.as_str(), file.size ) .fetch_optional(db) @@ -62,9 +63,10 @@ pub async fn read_for( ) -> Result, AppError> { let file = sqlx::query_as!( NoteFile, - r#"SELECT id, note, name, content_type, size FROM note_file WHERE id = $1 AND note = $2"#, - id, - note + r#"SELECT id AS "id: NoteFileId", note AS "note: NoteId", name AS "name: FileName", + content_type AS "content_type: FileContentType", size FROM note_file WHERE id = $1 AND note = $2"#, + id.uuid(), + note.uuid() ) .fetch_optional(db) .await?; @@ -91,15 +93,16 @@ pub async fn delete(db: &Database, file: NoteFile) -> Result tx_with_retry(db, true, async |conn| { let gone = sqlx::query_as!( NoteFile, - r#"DELETE FROM note_file WHERE id = $1 RETURNING id, note, name, content_type, size"#, - file.id + r#"DELETE FROM note_file WHERE id = $1 RETURNING id AS "id: NoteFileId", note AS "note: NoteId", name AS "name: FileName", + content_type AS "content_type: FileContentType", size"#, + file.id.uuid() ) .fetch_optional(&mut *conn) .await?; let file = gone.ok_or(AppError::NotFound)?; sqlx::query!( "UPDATE note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1", - file.note + file.note.uuid() ) .execute(&mut *conn) .await?; diff --git a/src/db/parent_link.rs b/src/db/parent_link.rs index 691fcaf..af4dc3f 100644 --- a/src/db/parent_link.rs +++ b/src/db/parent_link.rs @@ -38,7 +38,7 @@ pub async fn link( /// role) is [`crate::service::parent_link::links_live`]. pub async fn exists(db: &Database, parent: &UserId, student: &UserId) -> Result { let row = sqlx::query!( - "SELECT EXISTS(SELECT 1 FROM parent_link WHERE parent = $1 AND student = $2) AS present", + "SELECT EXISTS(SELECT 1 FROM parent_link WHERE parent = $1 AND student = $2) AS \"present!\"", parent.uuid(), student.uuid() ) diff --git a/src/db/payment_ledger.rs b/src/db/payment_ledger.rs index 59233c3..e6dabd7 100644 --- a/src/db/payment_ledger.rs +++ b/src/db/payment_ledger.rs @@ -21,7 +21,9 @@ use crate::database::Database; use crate::db::page::PagedList; use crate::domain::fee_plan::Installment; use crate::domain::fee_plan_assignment::FeePlanAssignment; -use crate::domain::payment_ledger::{PaymentLedger, PaymentLedgerId, PaymentLedgerKind}; +use crate::domain::payment_ledger::{ + LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind, +}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -56,28 +58,32 @@ pub(crate) async fn append( ON CONFLICT (id) DO NOTHING RETURNING id, student, kind, amount_minor, source, due_at, method, note, recorded_by, created_at) - SELECT id AS "id!", student AS "student!", + SELECT id AS "id!: PaymentLedgerId", student AS "student!: UserId", kind AS "kind!: PaymentLedgerKind", - amount_minor AS "amount_minor!", source, due_at, method, note, - recorded_by AS "recorded_by!", created_at AS "created_at!" + amount_minor AS "amount_minor!: LedgerAmount", source, + due_at AS "due_at: Timestamp", method AS "method: LedgerMethod", + note AS "note: LedgerNote", + recorded_by AS "recorded_by!: UserId", created_at AS "created_at!: Timestamp" FROM ins UNION ALL - SELECT id AS "id!", student AS "student!", + SELECT id AS "id!: PaymentLedgerId", student AS "student!: UserId", kind AS "kind!: PaymentLedgerKind", - amount_minor AS "amount_minor!", source, due_at, method, note, - recorded_by AS "recorded_by!", created_at AS "created_at!" + amount_minor AS "amount_minor!: LedgerAmount", source, + due_at AS "due_at: Timestamp", method AS "method: LedgerMethod", + note AS "note: LedgerNote", + recorded_by AS "recorded_by!: UserId", created_at AS "created_at!: Timestamp" FROM payment_ledger WHERE id = $1 AND NOT EXISTS (SELECT 1 FROM ins)"#, - row.id, - row.student, - row.kind, - row.amount_minor, + row.id.key(), + row.student.uuid(), + row.kind.as_str(), + row.amount_minor.as_minor(), row.source, - row.due_at, - row.method, - row.note, - row.recorded_by, - row.created_at, + row.due_at.map(|t| t.as_millis()), + row.method.as_ref().map(|m| m.as_str()), + row.note.as_ref().map(|n| n.as_str()), + row.recorded_by.uuid(), + row.created_at.as_millis(), ) .fetch_optional(exe) .await?; @@ -98,10 +104,13 @@ pub async fn read( ) -> Result, AppError> { sqlx::query_as!( PaymentLedger, - "SELECT id, student, kind, amount_minor, source, due_at, method, note, \ - recorded_by, created_at \ + "SELECT id AS \"id: PaymentLedgerId\", student AS \"student: UserId\", + kind AS \"kind: PaymentLedgerKind\", amount_minor AS \"amount_minor: LedgerAmount\", + source, due_at AS \"due_at: Timestamp\", method AS \"method: LedgerMethod\", + note AS \"note: LedgerNote\", recorded_by AS \"recorded_by: UserId\", + created_at AS \"created_at: Timestamp\" FROM payment_ledger WHERE id = $1", - id, + id.key(), ) .fetch_optional(exe) .await @@ -125,7 +134,7 @@ pub async fn charge_for_installment( append( exe, PaymentLedger { - id: PaymentLedgerId::for_installment(assignment.get_id(), n), + id: PaymentLedgerId::for_installment(&assignment.get_id(), n), student: assignment.get_student().clone(), kind: PaymentLedgerKind::Charge, amount_minor: installment.get_amount_minor(), @@ -190,7 +199,7 @@ pub async fn balance_of(db: &Database, student: &UserId) -> Result { - row.source.map(PaymentLedgerId::from_key) + row.source.map(|s| PaymentLedgerId::from_key(&s)) } // A charge's source is an assignment key, not a ledger row — // and by then the root lock is held, which is the point. diff --git a/src/db/pomodoro.rs b/src/db/pomodoro.rs index be86811..323c62d 100644 --- a/src/db/pomodoro.rs +++ b/src/db/pomodoro.rs @@ -126,7 +126,10 @@ pub async fn start( pub async fn finish(db: &Database, user: &UserId) -> Result { let done = Timestamp::now(); let day = done.day_number(); - let saved = tx_with_retry(db, false, async |tx| { + // Owned capture: an `async move` closure holding a `&UserId` fails the + // higher-ranked `Send` check `tx_with_retry`'s future must pass. + let user = *user; + let saved = tx_with_retry(db, false, async move |tx| { // Take the open row. Empty means nothing is running. let open = sqlx::query!( "DELETE FROM pomodoro_session @@ -222,7 +225,7 @@ pub async fn finish(db: &Database, user: &UserId) -> Result Result", image_file, + image_content_type AS "image_content_type: Option", + image_size"#, + question.id.uuid(), + question.asker.uuid(), + question.title.as_str(), + question.body.as_str(), question.status, - question.asked_at, + question.asked_at.as_millis(), ) .fetch_one(db) .await?; @@ -33,8 +41,14 @@ pub async fn insert(db: &Database, question: PoolQuestion) -> Result Result, AppError> { let row = sqlx::query_as!( PoolQuestion, - "SELECT * FROM pool_question WHERE id = $1", - id + r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", + status, asked_at AS "asked_at: Timestamp", + approved_by AS "approved_by: Option", image_file, + image_content_type AS "image_content_type: Option", + image_size + FROM pool_question WHERE id = $1"#, + id.uuid() ) .fetch_optional(db) .await?; @@ -46,7 +60,13 @@ pub async fn read(db: &Database, id: &PoolQuestionId) -> Result Result, AppError> { let rows = sqlx::query_as!( PoolQuestion, - "SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC", + r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", + status, asked_at AS "asked_at: Timestamp", + approved_by AS "approved_by: Option", image_file, + image_content_type AS "image_content_type: Option", + image_size + FROM pool_question ORDER BY asked_at DESC, id DESC"#, ) .fetch_all(db) .await?; @@ -58,11 +78,17 @@ pub async fn list_all(db: &Database) -> Result, AppError> { pub async fn list_visible_to(db: &Database, user: &UserId) -> Result, AppError> { let rows = sqlx::query_as!( PoolQuestion, - r#"SELECT * FROM pool_question + r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", + status, asked_at AS "asked_at: Timestamp", + approved_by AS "approved_by: Option", image_file, + image_content_type AS "image_content_type: Option", + image_size + FROM pool_question WHERE status = $1 OR asker = $2 ORDER BY asked_at DESC, id DESC"#, STATUS_APPROVED, - user + user.uuid() ) .fetch_all(db) .await?; @@ -111,10 +137,15 @@ pub async fn approve( PoolQuestion, r#"UPDATE pool_question SET status = $2, approved_by = $3 WHERE id = $1 AND status = $4 - RETURNING *"#, - *id, + RETURNING id AS "id: PoolQuestionId", asker AS "asker: UserId", + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", + status, asked_at AS "asked_at: Timestamp", + approved_by AS "approved_by: Option", image_file, + image_content_type AS "image_content_type: Option", + image_size"#, + id.uuid(), STATUS_APPROVED, - approver, + approver.uuid(), STATUS_PENDING, ) .fetch_optional(tx) @@ -126,14 +157,14 @@ pub async fn approve( sqlx::query!( "UPDATE app_user SET pool_approved_total = pool_approved_total + 1 WHERE id = $1", - approver + approver.uuid() ) .execute(tx) .await?; sqlx::query!( "UPDATE app_user SET pool_published_total = pool_published_total + 1 WHERE id = $1", - question.asker + question.asker.uuid() ) .execute(tx) .await?; @@ -164,8 +195,14 @@ pub async fn set_image( tx_with_retry(db, false, async |tx| { let before = sqlx::query_as!( PoolQuestion, - "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE", - *id + r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", + status, asked_at AS "asked_at: Timestamp", + approved_by AS "approved_by: Option", image_file, + image_content_type AS "image_content_type: Option", + image_size + FROM pool_question WHERE id = $1 FOR UPDATE"#, + id.uuid() ) .fetch_optional(tx) .await?; @@ -176,9 +213,9 @@ pub async fn set_image( r#"UPDATE pool_question SET image_file = $2, image_content_type = $3, image_size = $4 WHERE id = $1 AND status = $5"#, - *id, + id.uuid(), file, - content_type, + content_type.as_str(), size, STATUS_PENDING, ) @@ -201,8 +238,14 @@ pub async fn clear_image( tx_with_retry(db, false, async |tx| { let before = sqlx::query_as!( PoolQuestion, - "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE", - *id + r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", + status, asked_at AS "asked_at: Timestamp", + approved_by AS "approved_by: Option", image_file, + image_content_type AS "image_content_type: Option", + image_size + FROM pool_question WHERE id = $1 FOR UPDATE"#, + id.uuid() ) .fetch_optional(tx) .await?; @@ -213,7 +256,7 @@ pub async fn clear_image( r#"UPDATE pool_question SET image_file = NULL, image_content_type = NULL, image_size = NULL WHERE id = $1 AND status = $2"#, - *id, + id.uuid(), STATUS_PENDING, ) .execute(tx) @@ -244,15 +287,26 @@ pub async fn delete( tx_with_retry(db, true, async |tx| { let solutions = sqlx::query_as!( Solution, - "DELETE FROM solution WHERE question = $1 RETURNING *", - *id + r#"DELETE FROM solution WHERE question = $1 + RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", + author AS "author: UserId", body AS "body: SolutionBody", + offered_at AS "offered_at: Timestamp", image_file, + image_content_type AS "image_content_type: Option", + image_size"#, + id.uuid() ) .fetch_all(tx) .await?; let question = sqlx::query_as!( PoolQuestion, - "DELETE FROM pool_question WHERE id = $1 RETURNING *", - *id + r#"DELETE FROM pool_question WHERE id = $1 + RETURNING id AS "id: PoolQuestionId", asker AS "asker: UserId", + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", + status, asked_at AS "asked_at: Timestamp", + approved_by AS "approved_by: Option", image_file, + image_content_type AS "image_content_type: Option", + image_size"#, + id.uuid() ) .fetch_optional(tx) .await?; diff --git a/src/db/question_image.rs b/src/db/question_image.rs index 14483e8..37e1d9e 100644 --- a/src/db/question_image.rs +++ b/src/db/question_image.rs @@ -31,7 +31,7 @@ pub async fn upsert( db: &Database, image: QuestionImage, ) -> Result<(QuestionImage, Option), AppError> { - tx_with_retry(db, false, async |conn| upsert_in(conn, image).await).await + tx_with_retry(db, false, async |conn| upsert_in(conn, image.clone()).await).await } /// The gated read-and-replace, on one connection. @@ -49,13 +49,13 @@ pub(crate) async fn upsert_in( SET file = EXCLUDED.file, content_type = EXCLUDED.content_type, size = EXCLUDED.size RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", - slot AS "slot: Option", file, + slot AS "slot: ChoiceId", file, content_type AS "content_type: FileContentType", size"#, - image.exam as &ExamId, - image.question as &ExamQuestionId, - image.slot, + image.exam.uuid(), + image.question.uuid(), + image.slot.as_ref().map(ChoiceId::as_str), image.file, - image.content_type, + image.content_type.as_str(), image.size, ) .fetch_one(&mut *conn) @@ -74,8 +74,8 @@ pub(crate) async fn replaced_file( let row = sqlx::query!( r#"SELECT file FROM question_image WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#, - question as &ExamQuestionId, - slot.map(ChoiceId::clone), + question.uuid(), + slot.map(ChoiceId::as_str), ) .fetch_optional(conn) .await?; @@ -90,12 +90,12 @@ pub async fn read_slot( Ok(sqlx::query_as!( QuestionImage, r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", - slot AS "slot: Option", file, + slot AS "slot: ChoiceId", file, content_type AS "content_type: FileContentType", size FROM question_image WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#, - question as &ExamQuestionId, - slot.map(ChoiceId::clone), + question.uuid(), + slot.map(ChoiceId::as_str), ) .fetch_optional(db) .await?) @@ -106,10 +106,10 @@ pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result", file, + slot AS "slot: ChoiceId", file, content_type AS "content_type: FileContentType", size FROM question_image WHERE exam = $1"#, - exam as &ExamId, + exam.uuid(), ) .fetch_all(db) .await?) @@ -122,10 +122,10 @@ pub async fn list_for_question( Ok(sqlx::query_as!( QuestionImage, r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", - slot AS "slot: Option", file, + slot AS "slot: ChoiceId", file, content_type AS "content_type: FileContentType", size FROM question_image WHERE question = $1"#, - question as &ExamQuestionId, + question.uuid(), ) .fetch_all(db) .await?) @@ -145,16 +145,19 @@ pub async fn delete_choices_not_in( question: &ExamQuestionId, keep: &[ChoiceId], ) -> Result, AppError> { - let keep = keep.iter().map(ChoiceId::as_str).collect::>(); + let keep = keep + .iter() + .map(|id| id.as_str().to_string()) + .collect::>(); Ok(sqlx::query_as!( QuestionImage, r#"DELETE FROM question_image WHERE question = $1 AND slot IS NOT NULL AND NOT (slot = ANY($2)) RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", - slot AS "slot: Option", file, + slot AS "slot: ChoiceId", file, content_type AS "content_type: FileContentType", size"#, - question as &ExamQuestionId, - keep, + question.uuid(), + &keep, ) .fetch_all(db) .await?) @@ -169,7 +172,7 @@ pub async fn file_keys_for_course( let rows = sqlx::query!( r#"SELECT qi.file FROM question_image qi JOIN exam e ON e.id = qi.exam WHERE e.course = $1"#, - course as &CourseId, + course.uuid(), ) .fetch_all(db) .await?; @@ -186,10 +189,10 @@ pub async fn delete(db: &Database, image: QuestionImage) -> Result", file, + slot AS "slot: ChoiceId", file, content_type AS "content_type: FileContentType", size"#, - image.question as &ExamQuestionId, - image.slot, + image.question.uuid(), + image.slot.as_ref().map(ChoiceId::as_str), ) .fetch_optional(&mut *conn) .await?; diff --git a/src/db/rag_output.rs b/src/db/rag_output.rs index a9c204a..3bd3fb0 100644 --- a/src/db/rag_output.rs +++ b/src/db/rag_output.rs @@ -40,14 +40,20 @@ pub async fn create( RagOutput, r#"INSERT INTO rag_output (id, course_note, course, sources, payload, generated_at) VALUES ($1, $2, $3, $4, $5, $6) - RETURNING id, course_note, course, sources, - payload AS "payload: Json", generated_at"#, - row.id, - row.course_note, - row.course, - &row.sources, - &row.payload, - row.generated_at + RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", + course AS "course: CourseId", + sources AS "sources: Vec", + payload AS "payload: Json", + generated_at AS "generated_at: Timestamp""#, + row.id.uuid(), + row.course_note.uuid(), + row.course.uuid(), + &row.sources + .iter() + .map(CourseNoteFileId::uuid) + .collect::>(), + row.payload.0, + row.generated_at.as_millis() ) .fetch_one(db) .await?; @@ -57,10 +63,13 @@ pub async fn create( pub async fn read(db: &Database, id: &RagOutputId) -> Result, AppError> { let row = sqlx::query_as!( RagOutput, - r#"SELECT id, course_note, course, sources, - payload AS "payload: Json", generated_at + r#"SELECT id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", + course AS "course: CourseId", + sources AS "sources: Vec", + payload AS "payload: Json", + generated_at AS "generated_at: Timestamp" FROM rag_output WHERE id = $1"#, - id + id.uuid() ) .fetch_optional(db) .await?; @@ -84,9 +93,12 @@ pub async fn delete(db: &Database, id: &RagOutputId) -> Result", generated_at"#, - id + RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", + course AS "course: CourseId", + sources AS "sources: Vec", + payload AS "payload: Json", + generated_at AS "generated_at: Timestamp""#, + id.uuid() ) .fetch_optional(db) .await?; @@ -96,7 +108,7 @@ pub async fn delete(db: &Database, id: &RagOutputId) -> Result Result<(), AppError> { - sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note) + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.uuid()) .execute(db) .await?; Ok(()) @@ -119,8 +131,8 @@ pub async fn replace_for_note( let created = create(db, note, course, sources, payload).await?; sqlx::query!( "DELETE FROM rag_output WHERE course_note = $1 AND id < $2", - note, - created.id + note.uuid(), + created.id.uuid() ) .execute(db) .await?; @@ -132,9 +144,12 @@ pub async fn replace_for_note( /// source. The GIN index on `sources` turns the containment test into a /// lookup. pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> { - sqlx::query!("DELETE FROM rag_output WHERE $1 = ANY(sources)", file) - .execute(db) - .await?; + sqlx::query!( + "DELETE FROM rag_output WHERE $1 = ANY(sources)", + file.uuid() + ) + .execute(db) + .await?; Ok(()) } diff --git a/src/db/registration.rs b/src/db/registration.rs index 1dc6d32..ea4634e 100644 --- a/src/db/registration.rs +++ b/src/db/registration.rs @@ -103,7 +103,10 @@ pub async fn remove( user: &UserId, ) -> Result, AppError> { // The seat comes back in the same transaction as the row that held it. - tx_with_retry(db, false, async |tx| { + // Owned captures (`Send` rule of `tx_with_retry` closures). + let event = event.clone(); + let user = *user; + tx_with_retry(db, false, async move |tx| { let gone = query_as!( Registration, "DELETE FROM registration WHERE event = $1 AND app_user = $2 diff --git a/src/db/session.rs b/src/db/session.rs index bc832c7..eed75f6 100644 --- a/src/db/session.rs +++ b/src/db/session.rs @@ -21,8 +21,8 @@ pub async fn create(db: &Database, user: &UserId) -> Result { app_user AS "user: UserId", token AS "token: SessionToken", expires_at AS "expires_at: Timestamp""#, - id.0, - user.0, + id.uuid(), + user.uuid(), token.as_str(), expires_at.as_millis(), ) @@ -57,7 +57,7 @@ pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> /// the new credential means nothing while a cookie minted under the old one /// still authenticates. pub async fn delete_by_user(db: &Database, user: &UserId) -> Result<(), AppError> { - sqlx::query!("DELETE FROM user_session WHERE app_user = $1", user.0) + sqlx::query!("DELETE FROM user_session WHERE app_user = $1", user.uuid()) .execute(db) .await?; Ok(()) @@ -69,7 +69,7 @@ pub async fn delete_by_user(db: &Database, user: &UserId) -> Result<(), AppError /// forever. pub async fn purge_expired(db: &Database) -> Result { let now = Timestamp::now().as_millis(); - let (deleted,) = sqlx::query!( + let row = sqlx::query!( r#"WITH gone AS ( DELETE FROM user_session WHERE expires_at < $1 RETURNING 1 ) @@ -78,7 +78,7 @@ pub async fn purge_expired(db: &Database) -> Result { ) .fetch_one(db) .await?; - Ok(u64::try_from(deleted).unwrap_or(u64::MAX)) + Ok(u64::try_from(row.deleted).unwrap_or(u64::MAX)) } #[cfg(test)] diff --git a/src/db/session_attendance.rs b/src/db/session_attendance.rs index c18781a..c0840c8 100644 --- a/src/db/session_attendance.rs +++ b/src/db/session_attendance.rs @@ -7,6 +7,7 @@ use crate::database::{Database, tx_with_retry}; use crate::db::page::PagedList; use crate::domain::attendance::AttendanceStatus; +use crate::domain::course::CourseId; use crate::domain::course_session::{CourseSession, CourseSessionId}; use crate::domain::session_attendance::SessionAttendance; use crate::domain::timestamp::Timestamp; @@ -93,7 +94,7 @@ pub async fn mark( let sess = sqlx::query!( r#"SELECT teacher, starts_at, held_counted_at FROM course_session WHERE id = $1 FOR NO KEY UPDATE"#, - session.id, + session.id.uuid(), ) .fetch_optional(&mut *tx) .await?; @@ -105,8 +106,8 @@ pub async fn mark( let was = sqlx::query!( r#"SELECT status FROM session_attendance WHERE session = $1 AND app_user = $2"#, - session.id, - user, + session.id.uuid(), + user.uuid(), ) .fetch_optional(&mut *tx) .await? @@ -115,8 +116,8 @@ pub async fn mark( // non-student — no badge to move; the service gate has already // refused a vanished target before this write ran). let is_student = sqlx::query!( - r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#, - user, + r#"SELECT role = 'student' AS "is_student!: bool" FROM app_user WHERE id = $1"#, + user.uuid(), ) .fetch_optional(&mut *tx) .await? @@ -128,12 +129,14 @@ pub async fn mark( VALUES ($1, $2, $3, $4, $5) ON CONFLICT (session, app_user) DO UPDATE SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by - RETURNING session, app_user AS "user", course, status, marked_by"#, - session.id, - user, - session.course, - status, - marked_by, + RETURNING session AS "session: CourseSessionId", app_user AS "user: UserId", + course AS "course: CourseId", status AS "status: AttendanceStatus", + marked_by AS "marked_by: UserId""#, + session.id.uuid(), + user.uuid(), + session.course.uuid(), + status.as_str(), + marked_by.uuid(), ) .fetch_one(&mut *tx) .await?; @@ -146,7 +149,7 @@ pub async fn mark( r#"UPDATE app_user SET lessons_attended_total = GREATEST(lessons_attended_total + $2, 0) WHERE id = $1"#, - user, + user.uuid(), delta, ) .execute(&mut *tx) @@ -156,7 +159,7 @@ pub async fn mark( if sess.held_counted_at.is_none() && sess.starts_at <= now.as_millis() { sqlx::query!( r#"UPDATE course_session SET held_counted_at = $2 WHERE id = $1"#, - session.id, + session.id.uuid(), now.as_millis(), ) .execute(&mut *tx) @@ -202,10 +205,12 @@ pub async fn list_for_user( ) -> Result, AppError> { let rows = sqlx::query_as!( SessionAttendance, - r#"SELECT session, app_user AS "user", course, status, marked_by + r#"SELECT session AS "session: CourseSessionId", app_user AS "user: UserId", + course AS "course: CourseId", status AS "status: AttendanceStatus", + marked_by AS "marked_by: UserId" FROM session_attendance WHERE app_user = $1 ORDER BY session DESC, app_user DESC"#, - user, + user.uuid(), ) .fetch_all(db) .await?; @@ -235,12 +240,14 @@ pub async fn remove( // transaction, and `None` here is simply "nothing to remove". let Some(gone) = sqlx::query_as!( SessionAttendance, - r#"SELECT session, app_user AS "user", course, status, marked_by + r#"SELECT session AS "session: CourseSessionId", app_user AS "user: UserId", + course AS "course: CourseId", status AS "status: AttendanceStatus", + marked_by AS "marked_by: UserId" FROM session_attendance WHERE session = $1 AND app_user = $2 FOR UPDATE"#, - session, - user, + session.uuid(), + user.uuid(), ) .fetch_optional(&mut *tx) .await? @@ -250,8 +257,8 @@ pub async fn remove( if crate::domain::session_attendance::counts_as_attended(&gone.status) { // Student-only, live role: the same rule the mark pays. let student = sqlx::query!( - r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#, - user, + r#"SELECT role = 'student' AS "is_student!: bool" FROM app_user WHERE id = $1"#, + user.uuid(), ) .fetch_optional(&mut *tx) .await? @@ -262,7 +269,7 @@ pub async fn remove( r#"UPDATE app_user SET lessons_attended_total = GREATEST(lessons_attended_total - 1, 0) WHERE id = $1"#, - user, + user.uuid(), ) .execute(&mut *tx) .await?; @@ -270,8 +277,8 @@ pub async fn remove( } sqlx::query!( r#"DELETE FROM session_attendance WHERE session = $1 AND app_user = $2"#, - session, - user, + session.uuid(), + user.uuid(), ) .execute(&mut *tx) .await?; diff --git a/src/db/settings.rs b/src/db/settings.rs index a607410..21978ff 100644 --- a/src/db/settings.rs +++ b/src/db/settings.rs @@ -34,6 +34,16 @@ pub async fn load(db: &Database) -> Result { /// wherever the new policy was merged from a loaded snapshot. pub async fn save(db: &Database, settings: Settings) -> Result { // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged + let exam_kinds = serde_json::to_value(&settings.exam_kinds.0) + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; + let grade_bands = serde_json::to_value(&settings.grade_bands.0) + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; + let meal_slots = settings + .meal_slots + .as_ref() + .map(|slots| serde_json::to_value(&slots.0)) + .transpose() + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; let saved = sqlx::query_as!( Settings, r#"INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands, @@ -63,15 +73,15 @@ pub async fn save(db: &Database, settings: Settings) -> Result>", dietary_tags, meal_cancel_cutoff_minutes"#, - settings.exam_kinds, - settings.attendance_statuses, - settings.grade_bands, + exam_kinds, + settings.attendance_statuses.as_slice(), + grade_bands, settings.max_file_bytes, settings.chatbot_history_turns, settings.max_chatbot_message_len, settings.max_chatbot_threads, - settings.meal_slots, - settings.dietary_tags, + meal_slots, + settings.dietary_tags.as_deref(), settings.meal_cancel_cutoff_minutes, ) .fetch_one(db) @@ -114,6 +124,26 @@ pub async fn save_if_unchanged<'e, E>( where E: sqlx::PgExecutor<'e>, { + let exam_kinds = serde_json::to_value(&settings.exam_kinds.0) + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; + let grade_bands = serde_json::to_value(&settings.grade_bands.0) + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; + let meal_slots = settings + .meal_slots + .as_ref() + .map(|slots| serde_json::to_value(&slots.0)) + .transpose() + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; + let expected_exam_kinds = serde_json::to_value(&expected.exam_kinds.0) + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; + let expected_grade_bands = serde_json::to_value(&expected.grade_bands.0) + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; + let expected_meal_slots = expected + .meal_slots + .as_ref() + .map(|slots| serde_json::to_value(&slots.0)) + .transpose() + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; let saved = sqlx::query_as!( Settings, r#"INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands, @@ -153,25 +183,25 @@ where meal_slots AS "meal_slots: Json>", dietary_tags, meal_cancel_cutoff_minutes"#, - settings.exam_kinds, - settings.attendance_statuses, - settings.grade_bands, + exam_kinds, + settings.attendance_statuses.as_slice(), + grade_bands, settings.max_file_bytes, settings.chatbot_history_turns, settings.max_chatbot_message_len, settings.max_chatbot_threads, - settings.meal_slots, - settings.dietary_tags, + meal_slots, + settings.dietary_tags.as_deref(), settings.meal_cancel_cutoff_minutes, - expected.exam_kinds, - expected.attendance_statuses, - expected.grade_bands, + expected_exam_kinds, + expected.attendance_statuses.as_slice(), + expected_grade_bands, expected.max_file_bytes, expected.chatbot_history_turns, expected.max_chatbot_message_len, expected.max_chatbot_threads, - expected.meal_slots, - expected.dietary_tags, + expected_meal_slots, + expected.dietary_tags.as_deref(), expected.meal_cancel_cutoff_minutes, ) .fetch_optional(db) diff --git a/src/db/solution.rs b/src/db/solution.rs index e12c8ed..c89269a 100644 --- a/src/db/solution.rs +++ b/src/db/solution.rs @@ -11,6 +11,7 @@ use crate::db::page::PagedList; use crate::domain::note_file::FileContentType; use crate::domain::pool_question::PoolQuestionId; use crate::domain::solution::{Solution, SolutionBody, SolutionId}; +use crate::domain::timestamp::Timestamp; use crate::error::AppError; /// Offer the solution. `NotFound` = the question is gone, and nothing was @@ -29,12 +30,16 @@ pub async fn insert(db: &Database, solution: Solution) -> Result", + image_size"#, + solution.id.uuid(), + solution.question.uuid(), + solution.author.uuid(), + solution.body.as_str(), + solution.offered_at.as_millis(), ) .fetch_one(db) .await @@ -60,9 +65,14 @@ pub async fn read_for( ) -> Result, AppError> { let row = sqlx::query_as!( Solution, - "SELECT * FROM solution WHERE id = $1 AND question = $2", - id, - question + r#"SELECT id AS "id: SolutionId", question AS "question: PoolQuestionId", + author AS "author: UserId", body AS "body: SolutionBody", + offered_at AS "offered_at: Timestamp", image_file, + image_content_type AS "image_content_type: Option", + image_size + FROM solution WHERE id = $1 AND question = $2"#, + id.uuid(), + question.uuid() ) .fetch_optional(db) .await?; @@ -100,7 +110,7 @@ pub async fn counts_for( if questions.is_empty() { return Ok(HashMap::new()); } - let ids: Vec = questions.iter().copied().collect(); + let ids: Vec = questions.iter().map(|id| id.uuid()).collect(); let rows = sqlx::query!( r#"SELECT question AS "question: PoolQuestionId", count(*) AS n FROM solution @@ -126,9 +136,14 @@ pub async fn set_body( ) -> Result, AppError> { let row = sqlx::query_as!( Solution, - "UPDATE solution SET body = $2 WHERE id = $1 RETURNING *", - id, - body + r#"UPDATE solution SET body = $2 WHERE id = $1 + RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", + author AS "author: UserId", body AS "body: SolutionBody", + offered_at AS "offered_at: Timestamp", image_file, + image_content_type AS "image_content_type: Option", + image_size"#, + id.uuid(), + body.as_str() ) .fetch_optional(db) .await?; @@ -153,8 +168,13 @@ pub async fn set_image( tx_with_retry(db, false, async |tx| { let before = sqlx::query_as!( Solution, - "SELECT * FROM solution WHERE id = $1 FOR UPDATE", - *id + r#"SELECT id AS "id: SolutionId", question AS "question: PoolQuestionId", + author AS "author: UserId", body AS "body: SolutionBody", + offered_at AS "offered_at: Timestamp", image_file, + image_content_type AS "image_content_type: Option", + image_size + FROM solution WHERE id = $1 FOR UPDATE"#, + id.uuid() ) .fetch_optional(tx) .await?; @@ -165,9 +185,9 @@ pub async fn set_image( r#"UPDATE solution SET image_file = $2, image_content_type = $3, image_size = $4 WHERE id = $1"#, - *id, + id.uuid(), file, - content_type, + content_type.as_str(), size, ) .execute(tx) @@ -183,8 +203,13 @@ pub async fn clear_image(db: &Database, id: &SolutionId) -> Result", + image_size + FROM solution WHERE id = $1 FOR UPDATE"#, + id.uuid() ) .fetch_optional(tx) .await?; @@ -195,7 +220,7 @@ pub async fn clear_image(db: &Database, id: &SolutionId) -> Result Result Result { let deleted = sqlx::query_as!( Solution, - "DELETE FROM solution WHERE id = $1 RETURNING *", - solution.id + r#"DELETE FROM solution WHERE id = $1 + RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", + author AS "author: UserId", body AS "body: SolutionBody", + offered_at AS "offered_at: Timestamp", image_file, + image_content_type AS "image_content_type: Option", + image_size"#, + solution.id.uuid() ) .fetch_optional(db) .await?; diff --git a/src/db/subject.rs b/src/db/subject.rs index de97b83..2875fdf 100644 --- a/src/db/subject.rs +++ b/src/db/subject.rs @@ -33,11 +33,14 @@ pub async fn create( 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, + RETURNING id AS "id: SubjectId", + course AS "course: CourseId", + name AS "name: SubjectName", + description AS "description: SubjectDescription""#, + subject.id.uuid(), + subject.course.uuid(), + subject.name.as_str(), + subject.description.as_str(), ) .fetch_one(db) .await; @@ -51,8 +54,8 @@ pub async fn create( pub async fn read(db: &Database, id: &SubjectId) -> Result, AppError> { let subject = sqlx::query_as!( Subject, - r#"SELECT id, course, name, description FROM subject WHERE id = $1"#, - id, + r#"SELECT id AS "id: SubjectId", course AS "course: CourseId", name AS "name: SubjectName", description AS "description: SubjectDescription" FROM subject WHERE id = $1"#, + id.uuid(), ) .fetch_optional(db) .await?; @@ -65,11 +68,11 @@ pub async fn list_by_ids(db: &Database, ids: &[&SubjectId]) -> Result = ids.iter().map(|id| **id).collect(); + let keys: Vec = ids.iter().map(|id| id.uuid()).collect(); let rows = sqlx::query_as!( Subject, - r#"SELECT id, course, name, description FROM subject WHERE id = ANY($1)"#, - keys, + r#"SELECT id AS "id: SubjectId", course AS "course: CourseId", name AS "name: SubjectName", description AS "description: SubjectDescription" FROM subject WHERE id = ANY($1)"#, + &keys, ) .fetch_all(db) .await?; @@ -139,7 +142,7 @@ pub async fn delete(db: &Database, subject: Subject) -> Result Result Result, AppError> { let term = sqlx::query_as!( Term, - r#"SELECT id, name, starts_at, ends_at, archived_at FROM term WHERE id = $1"#, - id, + r#"SELECT id AS "id: TermId", name AS "name: TermName", + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", + archived_at AS "archived_at: Timestamp" FROM term WHERE id = $1"#, + id.uuid(), ) .fetch_optional(db) .await?; @@ -101,7 +105,7 @@ pub async fn delete(db: &Database, term: Term) -> Result { let gone = sqlx::query!( r#"DELETE FROM term WHERE id = $1 AND course_count = 0 AND class_count = 0"#, - term.id, + term.id.uuid(), ) .execute(db) .await?; @@ -124,9 +128,11 @@ pub async fn archive(db: &Database, term: Term) -> Result { 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(), + RETURNING id AS "id: TermId", name AS "name: TermName", + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", + archived_at AS "archived_at: Timestamp""#, + term.id.uuid(), + Timestamp::now().as_millis(), ) .fetch_optional(db) .await?; @@ -144,8 +150,10 @@ pub async fn unarchive(db: &Database, term: Term) -> Result { 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, + RETURNING id AS "id: TermId", name AS "name: TermName", + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", + archived_at AS "archived_at: Timestamp""#, + term.id.uuid(), ) .fetch_optional(db) .await?; diff --git a/src/db/user.rs b/src/db/user.rs index c3856bc..354e9d9 100644 --- a/src/db/user.rs +++ b/src/db/user.rs @@ -75,7 +75,7 @@ pub async fn create_with_role( id.uuid(), username.as_str(), password_hash.as_str(), - role, + role.as_str(), ) .fetch_one(db) .await @@ -153,7 +153,7 @@ pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result, App avatar_content_type AS "avatar_content_type: FileContentType", avatar_size FROM app_user WHERE id = ANY($1)"#, - ids + &ids ) .fetch_all(db) .await?; @@ -184,7 +184,7 @@ pub async fn list_by_role(db: &Database, role: Role) -> Result, AppErr avatar_content_type AS "avatar_content_type: FileContentType", avatar_size FROM app_user WHERE role = $1 ORDER BY id DESC"#, - role + role.as_str() ) .fetch_all(db) .await?; @@ -344,7 +344,10 @@ pub async fn set_role_cascade( // One wall-clock read for the whole cascade, bound by every stamping // statement — the old batch's single `$now`. let now = Timestamp::now().as_millis(); - tx_with_retry(db, true, async |tx| { + // Owned capture: an `async move` closure holding a `&UserId` fails the + // higher-ranked `Send` check `tx_with_retry`'s future must pass. + let target = *target; + tx_with_retry(db, true, async move |tx| { // The role write, floor guard included. `$2 <> 'admin'` arms the // guard only for a demotion: a promotion or a same-role rewrite can // never orphan the admins. @@ -374,7 +377,7 @@ pub async fn set_role_cascade( avatar_content_type AS "avatar_content_type: FileContentType", avatar_size"#, target.uuid(), - role, + role.as_str(), ) .fetch_optional(&mut *tx) .await?; @@ -591,13 +594,13 @@ pub async fn set_profile( value.map(|inner| Param::OptText(inner.map(str::to_string))) } FieldUpdate::new("app_user", id.uuid()) - .set("name", text(name.map(|n| n.as_str()))) - .set("surname", text(surname.map(|n| n.as_str()))) - .set("email", text(email.map(|n| n.as_str()))) - .set("phone", text(phone.map(|n| n.as_str()))) - .set("birth_date", text(birth_date.map(|n| n.as_str()))) - .set("display_name", text(display_name.map(|n| n.as_str()))) - .set("bio", text(bio.map(|n| n.as_str()))) + .set("name", text(name.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) + .set("surname", text(surname.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) + .set("email", text(email.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) + .set("phone", text(phone.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) + .set("birth_date", text(birth_date.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) + .set("display_name", text(display_name.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) + .set("bio", text(bio.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) .run(db) .await } @@ -622,7 +625,11 @@ pub async fn set_avatar( content_type: &FileContentType, size: i64, ) -> Result, AppError> { - tx_with_retry(db, false, async |tx| { + // Owned captures, same `Send` rule as every `tx_with_retry` closure. + let id = *id; + let file = file.to_string(); + let content_type = content_type.clone(); + tx_with_retry(db, false, async move |tx| { let before = sqlx::query_as!( User, r#"SELECT id AS "id: UserId", @@ -655,7 +662,7 @@ pub async fn set_avatar( SET avatar_file = $2, avatar_content_type = $3, avatar_size = $4 WHERE id = $1"#, id.uuid(), - file, + file.as_str(), content_type.as_str(), size, ) @@ -669,7 +676,8 @@ pub async fn set_avatar( /// Drop the avatar, returning the row as it was so the caller can delete /// the blob. Same pre-image contract as [`set_avatar`]. pub async fn clear_avatar(db: &Database, id: &UserId) -> Result, AppError> { - tx_with_retry(db, false, async |tx| { + let id = *id; + tx_with_retry(db, false, async move |tx| { let before = sqlx::query_as!( User, r#"SELECT id AS "id: UserId", diff --git a/src/db/work_entry.rs b/src/db/work_entry.rs index 79cf2db..1890f88 100644 --- a/src/db/work_entry.rs +++ b/src/db/work_entry.rs @@ -47,10 +47,10 @@ pub async fn check_in(db: &Database, user: &UserId) -> Result Result Result Result, AppError> { let row = sqlx::query_as!( WorkEntryRow, - "SELECT id, app_user, check_in, check_out FROM work_entry WHERE id = $1", - id, + "SELECT id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\" FROM work_entry WHERE id = $1", + id.uuid(), ) .fetch_optional(db) .await?; @@ -111,10 +111,10 @@ pub async fn list_for_user( Some(limit) => { sqlx::query_as!( WorkEntryRow, - "SELECT id, app_user, check_in, check_out FROM work_entry \ + "SELECT id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\" FROM work_entry \ WHERE app_user = $1 ORDER BY check_in DESC, id DESC \ LIMIT $2 OFFSET $3", - user, + user.uuid(), limit, offset, ) @@ -124,10 +124,10 @@ pub async fn list_for_user( None if offset > 0 => { sqlx::query_as!( WorkEntryRow, - "SELECT id, app_user, check_in, check_out FROM work_entry \ + "SELECT id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\" FROM work_entry \ WHERE app_user = $1 ORDER BY check_in DESC, id DESC \ OFFSET $2", - user, + user.uuid(), offset, ) .fetch_all(db) @@ -136,9 +136,9 @@ pub async fn list_for_user( None => { sqlx::query_as!( WorkEntryRow, - "SELECT id, app_user, check_in, check_out FROM work_entry \ + "SELECT id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\" FROM work_entry \ WHERE app_user = $1 ORDER BY check_in DESC, id DESC", - user, + user.uuid(), ) .fetch_all(db) .await? @@ -147,10 +147,10 @@ pub async fn list_for_user( // A window that can hide rows needs the count over the same WHERE; // an unpaged read from row zero already holds every row. let total = if limit.is_some() || offset > 0 { - sqlx::query!("SELECT count(*) FROM work_entry WHERE app_user = $1", user) + sqlx::query_scalar!("SELECT count(*) FROM work_entry WHERE app_user = $1", user.uuid()) .fetch_one(db) .await? - .0 + .unwrap_or(0) } else { rows.len() as i64 }; @@ -185,8 +185,8 @@ pub async fn remove(db: &Database, id: &WorkEntryId) -> Result let row = sqlx::query_as!( WorkEntryRow, "DELETE FROM work_entry WHERE id = $1 \ - RETURNING id, app_user, check_in, check_out", - id, + RETURNING id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\"", + id.uuid(), ) .fetch_optional(db) .await?; diff --git a/src/domain/appointment.rs b/src/domain/appointment.rs index 578bc1c..c4bc3a5 100644 --- a/src/domain/appointment.rs +++ b/src/domain/appointment.rs @@ -25,7 +25,6 @@ //! ([`crate::db::appointment::save_if_unchanged`]), decided by a conditional //! `UPDATE`. -use uuid::Uuid; use crate::constant::{MAX_APPOINTMENT_REASON_LEN}; use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; use crate::domain::monotonic_id::next_uuid; diff --git a/src/domain/appointment_slot.rs b/src/domain/appointment_slot.rs index 1a47ee5..b957ff3 100644 --- a/src/domain/appointment_slot.rs +++ b/src/domain/appointment_slot.rs @@ -19,7 +19,6 @@ //! live in [`crate::db::appointment_slot`]; the publish and delete workflows //! in [`crate::service::appointment_slot`]. -use uuid::Uuid; use crate::constant::{ MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, }; diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index f39044d..b5fe2b5 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -151,6 +151,14 @@ impl BankQuestion { self.correct.as_ref() } + /// The stored options of a choice template (`None` for a text one) — the + /// same shape [`crate::domain::exam_question::ExamQuestion::get_choices`] + /// gives the exam side, so the web layer's response builder reads both + /// alike. + pub fn get_choices(&self) -> Option<&[Choice]> { + self.choices.as_ref().map(|json| json.0.as_slice()) + } + pub fn get_source_exam(&self) -> Option<&ExamId> { self.source_exam.as_ref() } diff --git a/src/domain/chatbot_message.rs b/src/domain/chatbot_message.rs index 2c0c48e..768cde1 100644 --- a/src/domain/chatbot_message.rs +++ b/src/domain/chatbot_message.rs @@ -9,7 +9,6 @@ //! ([`ChatbotMessage::projected`]) — the durable repair for a dead process //! happens once, at mint, in `database.rs`'s school migration sweep. -use uuid::Uuid; use crate::constant::{ CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE, }; diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index 1fe23ca..f47bd47 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -4,7 +4,6 @@ //! [`crate::db::chatbot_message`], and deleting a thread cascades them; the //! threads' own persistence lives in [`crate::db::chatbot_thread`]. -use uuid::Uuid; use crate::constant::{MAX_CHATBOT_THREAD_TITLE_LEN}; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; diff --git a/src/domain/event.rs b/src/domain/event.rs index 5adc698..6ee0aed 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -7,7 +7,6 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_optional, validate_required}; -use uuid::Uuid; #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] #[sqlx(transparent)] @@ -160,8 +159,8 @@ impl EventAudience { Self { kind: event.get_audience_kind(), role: event.get_audience_role(), - course: event.get_audience_course().copied(), - class: event.get_audience_class().copied(), + course: event.get_audience_course().cloned(), + class: event.get_audience_class().cloned(), capacity: event.get_audience_capacity(), } } diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 25aed12..8276cdf 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -5,7 +5,6 @@ use crate::domain::settings::ExamKindDef; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -use uuid::Uuid; /// The one spelling of the re-draft refusal, shared by the update workflow's /// pre-flight gate ([`crate::service::exam::update`]) and the in-transaction diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index aa2feb8..036131f 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -1,5 +1,4 @@ use sqlx::types::Json; -use uuid::Uuid; use crate::constant::{ MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, MIN_QUESTION_CHOICES, diff --git a/src/domain/fee_plan.rs b/src/domain/fee_plan.rs index f5db77d..8cde41b 100644 --- a/src/domain/fee_plan.rs +++ b/src/domain/fee_plan.rs @@ -13,7 +13,6 @@ //! apply here. use sqlx::types::Json; -use uuid::Uuid; use crate::constant::{MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN}; use crate::domain::monotonic_id::next_uuid; diff --git a/src/domain/meal_ledger.rs b/src/domain/meal_ledger.rs index cdf2d0a..6905175 100644 --- a/src/domain/meal_ledger.rs +++ b/src/domain/meal_ledger.rs @@ -333,7 +333,7 @@ impl MealLedger { student: booking.get_student().clone(), kind: MealLedgerKind::Reversal, amount_minor: amount, - source: Some(charge.key()), + source: Some(charge.key().to_string()), method: None, note: None, recorded_by: recorded_by.clone(), diff --git a/src/domain/registration.rs b/src/domain/registration.rs index cb9cce1..3082c9f 100644 --- a/src/domain/registration.rs +++ b/src/domain/registration.rs @@ -15,7 +15,7 @@ pub struct RegistrationId { impl RegistrationId { pub fn composite(event: &EventId, user: &UserId) -> Self { Self { - event: *event, + event: event.clone(), user: *user, } } @@ -38,7 +38,7 @@ impl RegistrationId { } pub fn event(&self) -> EventId { - self.event + self.event.clone() } pub fn user(&self) -> UserId { diff --git a/src/domain/session_attendance.rs b/src/domain/session_attendance.rs index b0b6ee7..2a6b94e 100644 --- a/src/domain/session_attendance.rs +++ b/src/domain/session_attendance.rs @@ -16,7 +16,7 @@ pub struct SessionAttendanceId { impl SessionAttendanceId { pub fn composite(session: &CourseSessionId, user: &UserId) -> Self { Self { - session: *session, + session: session.clone(), user: *user, } } @@ -39,7 +39,7 @@ impl SessionAttendanceId { } pub fn session(&self) -> CourseSessionId { - self.session + self.session.clone() } pub fn user(&self) -> UserId { diff --git a/src/rate_limit.rs b/src/rate_limit.rs index 2dd6a25..ea005de 100644 --- a/src/rate_limit.rs +++ b/src/rate_limit.rs @@ -92,8 +92,8 @@ use axum::response::Response; use tokio::time::Instant; use crate::constant::{ - PURGE_AT, RATE_LIMIT_OVERFLOW_MAX, RATE_LIMIT_TABLE, RATE_SYNC_INTERVAL_SECS, - RATE_SYNC_MAX_KEYS, RATE_SYNC_TIMEOUT_SECS, + PURGE_AT, RATE_LIMIT_OVERFLOW_MAX, RATE_SYNC_INTERVAL_SECS, RATE_SYNC_MAX_KEYS, + RATE_SYNC_TIMEOUT_SECS, }; use crate::database::Database; use crate::domain::timestamp::Timestamp; @@ -474,9 +474,12 @@ where // has passed can never be read again. if swept != epoch { swept = epoch; - let sql = format!("DELETE FROM {RATE_LIMIT_TABLE} WHERE window_start < $1"); - if let Err(err) = - with_deadline(sqlx::query(&sql).bind(epoch).execute(&db)).await + if let Err(err) = with_deadline( + sqlx::query("DELETE FROM rate_limit WHERE window_start < $1") + .bind(epoch) + .execute(&db), + ) + .await { tracing::warn!(%err, "rate-limit sweep failed; retrying next window"); } @@ -549,17 +552,18 @@ async fn sync_once( // (`row_key` folds the epoch in), so a conflict can only be another // limiter of the same tier folding the same client inside the same window // — the ON CONFLICT fold is exactly the replay that must add, not clobber. - let mut fold = sqlx::QueryBuilder::::new(); - fold.push("INSERT INTO ") - .push(RATE_LIMIT_TABLE) - .push(" (id, hits, window_start) "); + let mut fold = sqlx::QueryBuilder::::new( + "INSERT INTO rate_limit (id, hits, window_start) ", + ); fold.push_values(pending.iter(), |mut b, p| { b.push_bind(row_key(tier, &p.key, epoch)) .push_bind(i64::from(p.delta)) .push_bind(epoch); }); - fold.push(" ON CONFLICT (id) DO UPDATE SET hits = rate_limit.hits + EXCLUDED.hits RETURNING id, hits"); - let rows: Vec<(String, i64)> = match with_deadline(fold.build_query_as()).await { + fold.push( + " ON CONFLICT (id) DO UPDATE SET hits = rate_limit.hits + EXCLUDED.hits RETURNING id, hits", + ); + let rows: Vec<(String, i64)> = match with_deadline(fold.build_query_as().fetch_all(db)).await { Ok(rows) => rows, Err(err) => { tracing::warn!(%err, tier, "rate-limit sync failed; counting locally until it recovers"); diff --git a/src/service/appointment.rs b/src/service/appointment.rs index 3579bce..00ecae9 100644 --- a/src/service/appointment.rs +++ b/src/service/appointment.rs @@ -175,7 +175,10 @@ async fn approve_inner( decided_by: &UserId, accepting: Option<(Timestamp, Timestamp)>, ) -> Result { - tx_with_retry(db, false, async |tx| { + // Owned captures (`Send` rule of `tx_with_retry` closures). + let id = id.clone(); + let decided_by = *decided_by; + tx_with_retry(db, false, async move |tx| { // Serializable for the overlap decision below (module doc). `SET // TRANSACTION` is legal only before the first query, so it goes // first; a `40001` from SSI is re-sent by the retry loop, and the @@ -183,7 +186,7 @@ async fn approve_inner( sqlx::query!("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE") .execute(&mut *tx) .await?; - let expected = appointment::read_pending_on(&mut *tx, id).await?; + let expected = appointment::read_pending_on(&mut *tx, &id).await?; match accepting { None if expected.has_proposal() => { return Err(AppError::Conflict( @@ -226,7 +229,7 @@ async fn approve_inner( expected.get_requester(), starts_at, ends_at, - Some(id), + Some(&id), ) .await? { @@ -236,7 +239,7 @@ async fn approve_inner( } let mut approved = expected.clone(); approved.status = AppointmentStatus::Approved; - approved.decided_by = Some(decided_by.clone()); + approved.decided_by = Some(decided_by); match appointment::decision_cas(&mut *tx, &expected, approved).await? { Some(saved) => Ok(saved), // Unreachable under the row lock this transaction holds — kept diff --git a/src/service/exam.rs b/src/service/exam.rs index e5b4a8b..cff995a 100644 --- a/src/service/exam.rs +++ b/src/service/exam.rs @@ -8,6 +8,7 @@ use crate::constant::CAS_UPDATE_RETRIES; use crate::database::Database; use crate::db::exam; +use crate::db::exam_attempt::any_for_exam; use crate::db::exam_result; use crate::domain::course::CourseId; use crate::domain::exam::{ @@ -18,6 +19,7 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; use crate::service::course::require_open; +use crate::service::exam_attempt::course_of; #[expect( clippy::too_many_arguments, diff --git a/src/service/exam_attempt.rs b/src/service/exam_attempt.rs index 17f95a1..805af13 100644 --- a/src/service/exam_attempt.rs +++ b/src/service/exam_attempt.rs @@ -178,7 +178,6 @@ pub async fn start( } }; let attempt = ExamAttempt { - id: ExamAttemptId::composite(exam.get_id(), user, next_seq), exam: exam.get_id().clone(), user: user.clone(), seq: next_seq, diff --git a/src/service/meal_booking.rs b/src/service/meal_booking.rs index deb8359..cfb97ee 100644 --- a/src/service/meal_booking.rs +++ b/src/service/meal_booking.rs @@ -122,7 +122,6 @@ pub async fn book( // booked-but-unbilled row behind. let price = meal_ledger::price_snapshot(db, menu).await?; let fresh_row = MealBooking { - id: id.clone(), menu: menu.clone(), student: student.clone(), booked_by: booked_by.clone(), @@ -227,7 +226,7 @@ pub async fn cancel( cutoff: &MealCutoff, recorded_by: &UserId, ) -> Result { - let fresh = meal_booking::read(db, &cancelled.id) + let fresh = meal_booking::read(db, &cancelled.id()) .await? .ok_or(AppError::NotFound)?; if fresh.status == MealBookingStatus::Cancelled { @@ -245,7 +244,7 @@ pub async fn cancel( let saved = match meal_booking::release_seat(db, &fresh, recorded_by).await? { Some(cancelled) => cancelled, None => { - let live = meal_booking::read(db, &cancelled.id) + let live = meal_booking::read(db, &cancelled.id()) .await? .ok_or(AppError::NotFound)?; if !refundable_after_lost_flip(&fresh, &live)? { diff --git a/src/service/payment_ledger.rs b/src/service/payment_ledger.rs index 564ef64..9604533 100644 --- a/src/service/payment_ledger.rs +++ b/src/service/payment_ledger.rs @@ -170,14 +170,23 @@ async fn against( } .into()); } - tx_with_retry(db, false, async |tx| { + // Owned captures: a closure holding a `&T` fails the higher-ranked + // `Send` check `tx_with_retry`'s future must pass. + let target = target.clone(); + let recorded_by = *recorded_by; + tx_with_retry(db, false, async move |tx| { // Every writer that can move this target's arithmetic holds some row // on this chain; holding the whole walk to the root is what makes // the fold below and the append it authorizes one decision. payment_ledger::lock_for_cap(&mut *tx, &target.id).await?; - if let Some(id) = keyed.clone() - && let Some(existing) = payment_ledger::read(&mut *tx, &id).await? - { + // Awaits sit in match arms, never in a `let`-chain condition: an + // awaited condition poisons the closure future's higher-ranked + // `Send` that `tx_with_retry` requires. + let replay = match keyed.clone() { + Some(id) => payment_ledger::read(&mut *tx, &id).await?, + None => None, + }; + if let Some(existing) = replay { // A replay is answered from the stored line — but only if it is // the same money. The same key for a different amount or a // different target is a client bug, and handing back the old @@ -201,27 +210,29 @@ async fn against( // bursar money had arrived when none ever did. The reversal's // id is derived from its target's, so telling the two apart is // one read, taken only on the refusal path. - if let Some(reversed) = reversed - && payment_ledger::read(&mut *tx, &PaymentLedgerId::for_reversal(&target.id)) - .await? - .is_some() - { - return Err(AppError::Conflict(reversed)); + if let Some(text) = reversed { + let reversed_there = + payment_ledger::read(&mut *tx, &PaymentLedgerId::for_reversal(&target.id)) + .await? + .is_some(); + if reversed_there { + return Err(AppError::Conflict(text)); + } } return Err(AppError::Conflict(over)); } payment_ledger::append( &mut *tx, PaymentLedger { - id: keyed.unwrap_or_else(PaymentLedgerId::generate), + id: keyed.clone().unwrap_or_else(PaymentLedgerId::generate), student: target.student.clone(), kind, amount_minor, - source: Some(target.id.key()), + source: Some(target.id.key().to_string()), due_at: None, - method, - note, - recorded_by: recorded_by.clone(), + method: method.clone(), + note: note.clone(), + recorded_by, created_at: Timestamp::now(), }, ) @@ -262,7 +273,10 @@ pub async fn reversal( } .into()); } - tx_with_retry(db, false, async |tx| { + // Owned captures (`Send` rule of `tx_with_retry` closures). + let line = line.clone(); + let recorded_by = *recorded_by; + tx_with_retry(db, false, async move |tx| { payment_ledger::lock_for_cap(&mut *tx, line.get_id()).await?; payment_ledger::append( &mut *tx, @@ -271,11 +285,11 @@ pub async fn reversal( student: line.student.clone(), kind: PaymentLedgerKind::Reversal, amount_minor: line.amount_minor, - source: Some(line.id.key()), + source: Some(line.id.key().to_string()), due_at: None, method: None, - note, - recorded_by: recorded_by.clone(), + note: note.clone(), + recorded_by, created_at: Timestamp::now(), }, ) diff --git a/src/service/settings.rs b/src/service/settings.rs index a28f7ae..64f4a3f 100644 --- a/src/service/settings.rs +++ b/src/service/settings.rs @@ -172,7 +172,7 @@ pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result Result<(), AppE r#"SELECT retired AS "retired!: bool" FROM kind_ref WHERE name = $1 FOR UPDATE"#, name ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await? .map(|row| row.retired) .unwrap_or(false); @@ -250,7 +250,7 @@ async fn retire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppE RETURNING 1 AS "landed!: i64""#, name ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await? .is_some(); match (landed, was) { @@ -270,7 +270,7 @@ async fn retire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppE r#"SELECT retired AS "retired!: bool" FROM slot_ref WHERE name = $1 FOR UPDATE"#, name ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await? .map(|row| row.retired) .unwrap_or(false); @@ -281,7 +281,7 @@ async fn retire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppE RETURNING 1 AS "landed!: i64""#, name ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await? .is_some(); match (landed, was) { @@ -305,7 +305,7 @@ async fn unretire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), Ap RETURNING 1 AS "landed!: i64""#, name ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await?; Ok(()) } @@ -319,7 +319,7 @@ async fn unretire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), Ap RETURNING 1 AS "landed!: i64""#, name ) - .fetch_optional(tx) + .fetch_optional(&mut *tx) .await?; Ok(()) } diff --git a/src/web/appointments.rs b/src/web/appointments.rs index 90743ec..265a85a 100644 --- a/src/web/appointments.rs +++ b/src/web/appointments.rs @@ -439,7 +439,7 @@ async fn list_slots( .filter(|teacher| teacher.get_role().at_least(Role::Teacher)) .map(|teacher| (teacher.get_id().key().to_string(), PersonRef::new(teacher))) .collect(); - slots.retain(|slot| people.contains_key(slot.get_teacher().key())); + slots.retain(|slot| people.contains_key(slot.get_teacher().key().as_str())); (slots, people) }; let total = slots.len() as i64; diff --git a/src/web/attendance.rs b/src/web/attendance.rs index 8092d33..bcfe05b 100644 --- a/src/web/attendance.rs +++ b/src/web/attendance.rs @@ -119,7 +119,7 @@ async fn build_report( } let courses = crate::service::course::list_by_ids(db, &course_ids).await?; - let course_by_key: HashMap<&str, &Course> = + let course_by_key: HashMap = courses.iter().map(|c| (c.get_id().key(), c)).collect(); let people = person_map(courses.iter().flat_map(course_people), db).await?; @@ -128,13 +128,13 @@ async fn build_report( for course_id in &course_ids { // A row whose course is gone cannot happen given the delete cascade — // skip defensively rather than fabricate a course block. - let Some(course) = course_by_key.get(course_id.key()) else { + let Some(course) = course_by_key.get(course_id.key().as_str()) else { continue; }; if viewer.is_some_and(|viewer| !can_manage_course(course, viewer)) { continue; } - let rows = &by_course[course_id.key()]; + let rows = &by_course[course_id.key().as_str()]; visible_rows.extend(rows.iter().copied()); blocks.push(CourseAttendance { course: CourseResponse::new(course, &people), diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index 9d7b326..b553ceb 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -560,13 +560,13 @@ async fn list_questions( let items = questions .iter() .map(|question| { - let images = buckets.get(question.get_id().key()).unwrap_or(&empty); + let images = buckets.get(&question.get_id().key()).unwrap_or(&empty); let subject_name = question .get_subject() - .and_then(|subject| subject_names.get(subject.key()).cloned()) + .and_then(|subject| subject_names.get(&subject.key()).cloned()) .unwrap_or_default(); let owner_name = people - .get(question.get_owner().key()) + .get(&question.get_owner().key()) .map(|person| { person .display_name @@ -574,7 +574,7 @@ async fn list_questions( .unwrap_or_else(|| person.username.clone()) }) .unwrap_or_default(); - let used_count = used.get(question.get_id().key()).copied().unwrap_or(0); + let used_count = used.get(&question.get_id().key()).copied().unwrap_or(0); BankQuestionResponse::with_names(question, images, subject_name, owner_name, used_count) }) .collect(); @@ -651,7 +651,9 @@ async fn update_question( owned_question(&st, &user, &bid).await?; let patch = bank_question::BankQuestionPatch { subject: match req.subject_id { - Some(ref subject_id) => Some(crate::service::subject::must_exist(&st.db, subject_id).await?), + Some(ref subject_id) => { + Some(crate::service::subject::must_exist(&st.db, subject_id).await?) + } None => None, }, text: match req.text { diff --git a/src/web/board_ws.rs b/src/web/board_ws.rs index e392031..c86dc57 100644 --- a/src/web/board_ws.rs +++ b/src/web/board_ws.rs @@ -152,8 +152,8 @@ async fn room(mut socket: WebSocket, st: AppState, slug: Slug, board: BoardId, u // lands between a replay's read and this subscribe would otherwise be lost // outright, whereas one delivered twice is deduplicated by its id at the // client (which a resync forces anyway). - let _connected = room::Connected::open(&st.metrics, "board", slug.as_str(), board.key()); - let mut feed = st.board_hub.subscribe(&slug, board.key()); + let _connected = room::Connected::open(&st.metrics, "board", slug.as_str(), &board.key()); + let mut feed = st.board_hub.subscribe(&slug, &board.key()); // The ids this socket drew, in the order they were published. The hub has // no idea who is listening, so the room filters its own strokes back out // here — a client that had to ignore the echo of every mark it just drew @@ -193,7 +193,7 @@ async fn room(mut socket: WebSocket, st: AppState, slug: Slug, board: BoardId, u } } room::close(&mut socket).await; - st.board_hub.leave(&slug, board.key()); + st.board_hub.leave(&slug, &board.key()); } type Step = Result<(), RoomClosed>; @@ -475,7 +475,7 @@ async fn handle_message( fanned["type"] = json!("stroke"); fanned["epoch"] = json!(stroke.get_epoch()); mine.push_back(stroke.get_id().key().to_string()); - st.board_hub.publish(slug, board.key(), fanned.to_string()); + st.board_hub.publish(slug, &board.key(), fanned.to_string()); let mut frame = json!({ "type": "saved", "id": stroke.get_id().key() }); with_client_seq(&mut frame, client_seq); send(socket, frame).await @@ -499,7 +499,7 @@ async fn handle_message( Ok(marker) => { st.board_hub.publish( slug, - board.key(), + &board.key(), json!({ "type": "cleared", "epoch": marker.get_epoch() + 1, @@ -518,7 +518,7 @@ async fn handle_message( Ok(_) => { st.board_hub.publish( slug, - board.key(), + &board.key(), json!({ "type": "locked", "locked": locked, "by": user.key() }).to_string(), ); Ok(()) diff --git a/src/web/boards.rs b/src/web/boards.rs index 7925d50..4783931 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -63,7 +63,7 @@ pub fn routes() -> OpenApiRouter { /// Push one frame to whoever is in the room right now. An empty room is the /// normal case, not a failure. fn fan_out(st: &AppState, slug: &Slug, board: &BoardId, frame: serde_json::Value) { - st.board_hub.publish(slug, board.key(), frame.to_string()); + st.board_hub.publish(slug, &board.key(), frame.to_string()); } /// The roster frame every path that changes the invite list must publish. A @@ -677,7 +677,7 @@ impl InviteSource { field: "event", reason: "no such event", }))?; - crate::service::event::members(db, event.get_audience(), event.get_id()).await + crate::service::event::members(db, &event).await } } } diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index 9a3bba7..3485af1 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -386,7 +386,7 @@ async fn send_message( ) -> Result { // Charged first: a rejected turn must cost nothing and leave no row. st.chatbot_limit - .enforce_user(&scoped_key(&slug, user.get_id().key()))?; + .enforce_user(&scoped_key(&slug, user.get_id().key().as_str()))?; let thread = own_thread(&id, user.get_id(), &st.db).await?; let settings = service::settings::load(&st.db).await?; diff --git a/src/web/classes.rs b/src/web/classes.rs index e0ac1ef..f63e00f 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -301,7 +301,7 @@ async fn classes_page( db: &Database, ) -> Result, AppError> { let classes = class_group::list_by_ids(db, ids).await?; - let by_id: std::collections::HashMap<&str, &ClassGroup> = classes + let by_id: std::collections::HashMap = classes .iter() .map(|class| (class.get_id().key(), class)) .collect(); @@ -314,7 +314,7 @@ async fn classes_page( .await?; let items = ids .iter() - .filter_map(|id| by_id.get(id.key())) + .filter_map(|id| by_id.get(id.key().as_str())) .map(|class| ClassResponse::new(class, &people, with_creator)) .collect(); Ok(Page::new(items, total, limit, offset)) diff --git a/src/web/course_notes.rs b/src/web/course_notes.rs index c6c5a40..5677b04 100644 --- a/src/web/course_notes.rs +++ b/src/web/course_notes.rs @@ -313,7 +313,7 @@ async fn delete_one( // pre-read list — an upload that landed in between is in the cascade too. let (_, files) = service::course_note::delete(&st.db, note).await?; for file in &files { - remove_blob(&st.files_path, file.get_id().key()).await; + remove_blob(&st.files_path, &file.get_id().key()).await; } Ok(StatusCode::NO_CONTENT) } @@ -392,7 +392,7 @@ async fn upload_file( // Blob first, row second — a stored row always points at a real blob. If // the row insert fails, take the fresh blob back out. let file = CourseNoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64); - let path = blob_path(&st.files_path, file.get_id().key()); + let path = blob_path(&st.files_path, &file.get_id().key()); crate::web::ensure_files_dir(&st.files_path).await?; tokio::fs::write(&path, &upload.data) .await @@ -484,7 +484,7 @@ async fn download_file( ) .await? .ok_or(AppError::NotFound)?; - let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key())) + let bytes = tokio::fs::read(blob_path(&st.files_path, &file.get_id().key())) .await .map_err(|err| { // The row exists but its blob doesn't — that's server-side damage @@ -553,7 +553,7 @@ async fn delete_file( // blob; the re-index rebuilds from what is left, if a service is connected. service::rag_output::delete_with_source(&st.db, file.get_id()).await?; let file = service::course_note_file::delete(&st.db, file).await?; - remove_blob(&st.files_path, file.get_id().key()).await; + remove_blob(&st.files_path, &file.get_id().key()).await; spawn_index(&st, &tenant, note); Ok(StatusCode::NO_CONTENT) } diff --git a/src/web/courses.rs b/src/web/courses.rs index e3a7375..2f62566 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -273,7 +273,7 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result &str { + fn order_key(&self) -> String { self.get_id().key() } } @@ -723,9 +723,9 @@ async fn roster( let mut members = service::event::members(&st.db, &event).await?; // ULID keys sort by creation instant — a stable order keeps pages coherent. - members.sort_by(|a, b| a.key().cmp(b.key())); + members.sort_by(|a, b| a.key().cmp(&b.key())); let (marks, _) = crate::service::attendance::list_for_event(&st.db, &event_id, None, 0).await?; - let by_user: HashMap<&str, &Attendance> = marks + let by_user: HashMap = marks .iter() .map(|attendance| (attendance.get_user().key(), attendance)) .collect(); @@ -736,14 +736,14 @@ async fn roster( let window = paginate(&members, limit, offset); let ids = window.iter().cloned().chain(window.iter().filter_map(|m| { by_user - .get(m.key()) + .get(m.key().as_str()) .map(|attendance| attendance.get_marked_by().clone()) })); let people = person_map(ids, &st.db).await?; let items = window .iter() .map(|member| { - let mark = by_user.get(member.key()); + let mark = by_user.get(member.key().as_str()); RosterEntry { user: PersonRef::resolve(&people, member), status: mark.map(|attendance| attendance.get_status().as_str().to_string()), diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 49d4f8b..4b27e2f 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -166,7 +166,12 @@ async fn room( let attempt_id = attempt.get_id().clone(); // The exam, not the attempt: an attempt names one student, and telemetry // never names a person. - let _connected = room::Connected::open(&st.metrics, "exam_room", slug.as_str(), exam_id.key()); + let _connected = room::Connected::open( + &st.metrics, + "exam_room", + slug.as_str(), + exam_id.key().as_str(), + ); // Join: this socket counts as presence in the sitting's room until it // closes, and joining clears the walk-out marker — the clear is one // unconditional statement against the sitting's row, so it always @@ -174,7 +179,7 @@ async fn room( // predate a stamp that raced the upgrade; clearing regardless is what // keeps a reconnecting student unmarked. Best-effort — a failed clear // leaves the stamp for the next join or the teacher's door. - st.exam_presence.enter(&slug, attempt_id.key()); + st.exam_presence.enter(&slug, attempt_id.key().as_str()); if let Err(err) = set_left(&st.db, attempt, None).await { tracing::warn!("exam room could not clear left_at on join: {err}"); } @@ -211,7 +216,7 @@ async fn room( // stamped. With `allow_rejoin` off this is what locks further // answering. Best-effort: a failed stamp only means it goes // unrecorded. - if st.exam_presence.leave(&slug, attempt_id.key()) { + if st.exam_presence.leave(&slug, attempt_id.key().as_str()) { crate::db::exam_attempt::stamp_left_if_running(&st.db, &attempt_id, Timestamp::now()) .await .unwrap_or_else(|err| { @@ -233,7 +238,7 @@ async fn writable_room_attempt( db: &Database, ) -> Result { let attempt = writable_attempt(exam, user, db).await?; - if attempt.get_id() != attempt_id { + if &attempt.get_id() != attempt_id { return Err(AppError::Conflict( "this room's sitting is over — reconnect to continue in the new attempt", )); diff --git a/src/web/exams/attempts.rs b/src/web/exams/attempts.rs index 04f7f15..722a2c9 100644 --- a/src/web/exams/attempts.rs +++ b/src/web/exams/attempts.rs @@ -386,7 +386,7 @@ pub(crate) async fn live_snapshot( .iter() .map(|enrollment| { let key = enrollment.get_user().key(); - let attempt = attempts.get(key); + let attempt = attempts.get(&key); let status = attempt.map(|a| a.status(exam, now)); let deadline = attempt.and_then(|a| a.deadline(exam)); LiveStudentResponse { @@ -398,7 +398,7 @@ pub(crate) async fn live_snapshot( } .to_string(), attempt: attempt.map(ExamAttempt::get_seq), - attempts_used: used.get(key).copied().unwrap_or(0), + attempts_used: used.get(&key).copied().unwrap_or(0), started_at: attempt.map(|a| a.get_started_at().as_millis()), finished_at: attempt .and_then(|a| a.get_finished_at()) @@ -408,9 +408,9 @@ pub(crate) async fn live_snapshot( remaining_ms: (status == Some(AttemptStatus::InProgress)) .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0))) .flatten(), - mark: marks.get(key).copied(), - answered: progress.get(key).map_or(0, |p| p.0), - last_activity: progress.get(key).map(|p| p.1), + mark: marks.get(&key).copied(), + answered: progress.get(&key).map_or(0, |p| p.0), + last_activity: progress.get(&key).map(|p| p.1), } }) .collect(); @@ -604,7 +604,7 @@ pub(crate) async fn attempt_questions( .iter() .map(|question| { let question_images = images - .get(question.get_id().key()) + .get(question.get_id().key().as_str()) .map_or(&[][..], Vec::as_slice); AttemptQuestionResponse { id: question.get_id().key().to_string(), @@ -615,11 +615,11 @@ pub(crate) async fn attempt_questions( choices: ChoiceResponse::list(question.get_choices()), image: image_meta(question_images, None), choice_images: choice_image_metas(question, question_images), - answer: answers.get(question.get_id().key()).map(|answer| { + answer: answers.get(question.get_id().key().as_str()).map(|answer| { AnswerStateResponse::new( answer, answer_images - .get(question.get_id().key()) + .get(question.get_id().key().as_str()) .map(ImageMetaResponse::from_answer), ) }), @@ -747,7 +747,7 @@ pub(crate) async fn answer_sheet( ) -> Result { let (mut questions, _) = crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0).await?; - questions.retain(|question| !hidden.contains(question.get_id().key())); + questions.retain(|question| !hidden.contains(question.get_id().key().as_str())); let answers = crate::service::exam_answer::list_for_exam_user(db, exam.get_id(), target, seq).await?; let answer_images: HashMap = @@ -756,7 +756,7 @@ pub(crate) async fn answer_sheet( .into_iter() .map(|image| (image.get_question().key().to_string(), image)) .collect(); - let by_question: HashMap<&str, &ExamQuestion> = questions + let by_question: HashMap = questions .iter() .map(|question| (question.get_id().key(), question)) .collect(); @@ -773,10 +773,10 @@ pub(crate) async fn answer_sheet( text: answer.get_text().map(|t| t.as_str().to_string()), updated_at: answer.get_updated_at().as_millis(), is_correct: by_question - .get(answer.get_question().key()) + .get(answer.get_question().key().as_str()) .and_then(|question| answer.is_correct(question)), answer_image: answer_images - .get(answer.get_question().key()) + .get(answer.get_question().key().as_str()) .map(ImageMetaResponse::from_answer), }) .collect(), diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index 4ae321c..b2b472a 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -59,7 +59,7 @@ impl Scheduled for Exam { self.get_ends_at().map(|at| at.as_millis()) } - fn order_key(&self) -> &str { + fn order_key(&self) -> String { self.get_id().key() } } @@ -268,7 +268,7 @@ async fn list_exams( let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect(); // Drafts show only where the caller manages the course (as its // creator — the manager+ path above already saw everything). - let managed: Vec<&str> = courses + let managed: Vec = courses .iter() .filter(|c| can_manage_course(c, &user)) .map(|c| c.get_id().key()) diff --git a/src/web/exams/questions.rs b/src/web/exams/questions.rs index bc3a05e..d4f2fed 100644 --- a/src/web/exams/questions.rs +++ b/src/web/exams/questions.rs @@ -261,10 +261,10 @@ pub(crate) async fn question_page( let mut item = QuestionResponse::new( question, images - .get(question.get_id().key()) + .get(question.get_id().key().as_str()) .map_or(&[][..], Vec::as_slice), ); - if hidden.contains(question.get_id().key()) { + if hidden.contains(question.get_id().key().as_str()) { item.correct = None; } item diff --git a/src/web/marks.rs b/src/web/marks.rs index 4d2e4fe..8a8e7f9 100644 --- a/src/web/marks.rs +++ b/src/web/marks.rs @@ -108,7 +108,7 @@ async fn build_report( let mut blocks = Vec::with_capacity(courses.len()); for course in &courses { let exams = crate::service::exam::list_for_course(db, course.get_id()).await?; - let by_key: HashMap<&str, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect(); + let by_key: HashMap = exams.iter().map(|e| (e.get_id().key(), e)).collect(); let results = crate::service::exam_result::list_for_user_in_course(db, course.get_id(), user).await?; @@ -117,7 +117,7 @@ async fn build_report( for result in &results { // A result whose exam is gone cannot happen given the delete // cascade — skip defensively rather than corrupt the average. - let Some(exam) = by_key.get(result.get_exam().key()) else { + let Some(exam) = by_key.get(result.get_exam().key().as_str()) else { continue; }; // The kind's current settings weight; an exam keeps a retired diff --git a/src/web/meals.rs b/src/web/meals.rs index 0ccbf96..0a4c10e 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -20,7 +20,7 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::dietary_profile::{DietaryNote, DietaryTags, conflicts}; -use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; +use crate::domain::meal_attendance::{MealAttendance, MealAttendanceId, MealAttendanceStatus}; use crate::domain::meal_booking::{MealBooking, MealBookingId, MealCutoff}; use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger}; use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, validate_capacity}; @@ -726,7 +726,7 @@ struct BookingResponse { impl BookingResponse { fn new(booking: &MealBooking, people: &std::collections::HashMap) -> Self { Self { - id: booking.get_id().key().to_string(), + id: booking.id().key(), menu_id: booking.get_menu().key().to_string(), student: PersonRef::resolve(people, booking.get_student()), booked_by: PersonRef::resolve(people, booking.get_booked_by()), @@ -1005,10 +1005,8 @@ async fn cancel_booking( // gets the same 403 either way, and learns nothing. // // Same door as booking: whoever may take the seat may give it back. - let student = id - .student() - .ok_or(AppError::Forbidden("not your booking"))?; - let target = booking_target(&user, Some(student.key()), &st.db).await?; + let student = id.student(); + let target = booking_target(&user, Some(student.key().as_str()), &st.db).await?; if target != student { return Err(AppError::Forbidden("not your booking")); } @@ -1067,7 +1065,7 @@ struct MealAttendanceResponse { impl MealAttendanceResponse { fn new(row: &MealAttendance, people: &std::collections::HashMap) -> Self { Self { - id: row.get_id().key().to_string(), + id: MealAttendanceId::composite(row.get_menu(), &row.get_student()).key(), menu_id: row.get_menu().key().to_string(), student: PersonRef::resolve(people, row.get_student()), status: row.get_status().as_str().to_string(), diff --git a/src/web/messages.rs b/src/web/messages.rs index 10a6bfb..5e95b11 100644 --- a/src/web/messages.rs +++ b/src/web/messages.rs @@ -127,7 +127,7 @@ async fn load_people(messages: &[Message], db: &Database) -> Result Self { - let resolve = |id: &UserId| match people.get(id.key()) { + let resolve = |id: &UserId| match people.get(id.key().as_str()) { Some((person, role)) => (person.clone(), Some(*role)), None => ( PersonRef { diff --git a/src/web/notes.rs b/src/web/notes.rs index d562fab..640e35f 100644 --- a/src/web/notes.rs +++ b/src/web/notes.rs @@ -211,7 +211,7 @@ async fn delete_one( // pre-read list — an upload that landed in between is in the cascade too. let (_, files) = service::note::delete(&st.db, note).await?; for file in &files { - remove_blob(&st.files_path, file.get_id().key()).await; + remove_blob(&st.files_path, &file.get_id().key()).await; } Ok(StatusCode::NO_CONTENT) } @@ -284,7 +284,7 @@ async fn upload_file( // Blob first, row second — a stored row always points at a real blob. If // the row insert fails, take the fresh blob back out. let file = NoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64); - let path = blob_path(&st.files_path, file.get_id().key()); + let path = blob_path(&st.files_path, &file.get_id().key()); crate::web::ensure_files_dir(&st.files_path).await?; tokio::fs::write(&path, &upload.data) .await @@ -356,7 +356,7 @@ async fn download_file( let file = service::note_file::read_for(&st.db, &NoteFileId::from_key(&file_id), note.get_id()) .await? .ok_or(AppError::NotFound)?; - let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key())) + let bytes = tokio::fs::read(blob_path(&st.files_path, &file.get_id().key())) .await .map_err(|err| { // The row exists but its blob doesn't — that's server-side damage @@ -410,7 +410,7 @@ async fn delete_file( .await? .ok_or(AppError::NotFound)?; let file = service::note_file::delete(&st.db, file).await?; - remove_blob(&st.files_path, file.get_id().key()).await; + remove_blob(&st.files_path, &file.get_id().key()).await; Ok(StatusCode::NO_CONTENT) } diff --git a/src/web/page.rs b/src/web/page.rs index 2769ad5..ef266af 100644 --- a/src/web/page.rs +++ b/src/web/page.rs @@ -61,7 +61,7 @@ impl PageParams { pub trait Scheduled { fn starts_at_ms(&self) -> Option; fn ends_at_ms(&self) -> Option; - fn order_key(&self) -> &str; + fn order_key(&self) -> String; } /// The optional `?starts_after=&ends_after=` schedule window on a list of @@ -116,7 +116,7 @@ impl WindowParams { let key = |item: &T| item.starts_at_ms().or_else(|| item.ends_at_ms()); key(a) .cmp(&key(b)) - .then_with(|| a.order_key().cmp(b.order_key())) + .then_with(|| a.order_key().cmp(&b.order_key())) }); Ok(items) } diff --git a/src/web/payments.rs b/src/web/payments.rs index 7c031c3..006e354 100644 --- a/src/web/payments.rs +++ b/src/web/payments.rs @@ -546,7 +546,8 @@ async fn appended( } async fn require_line(id: &str, db: &Database) -> Result { - service::payment_ledger::read(db, &PaymentLedgerId::from_key(id)) + let id = PaymentLedgerId::from_key(id); + service::payment_ledger::read(db, &id) .await? .ok_or(AppError::NotFound) } @@ -877,10 +878,10 @@ async fn statement_response( let (assignments, _) = service::fee_plan_assignment::list_for_student(db, student, None, 0).await?; let mut plan_names: HashMap> = HashMap::new(); - let mut plan_of: HashMap<&str, &FeePlanId> = HashMap::new(); + let mut plan_of: HashMap = HashMap::new(); for assignment in &assignments { let plan = assignment.get_plan(); - if !plan_names.contains_key(plan.key()) { + if !plan_names.contains_key(plan.key().as_str()) { let name = service::fee_plan::read(db, plan) .await? .map(|plan| plan.get_name().as_str().to_string()); @@ -935,7 +936,7 @@ async fn statement_response( StatementEntry { charge_id: charge.get_id().key().to_string(), plan: plan.map(|plan| plan.key().to_string()), - plan_name: plan.and_then(|plan| plan_names.get(plan.key()).cloned().flatten()), + plan_name: plan.and_then(|plan| plan_names.get(plan.key().as_str()).cloned().flatten()), amount_minor: charge.get_amount_minor().as_minor(), due_at, credited_minor: credited, diff --git a/src/web/questions.rs b/src/web/questions.rs index 367ba17..7e5c7c0 100644 --- a/src/web/questions.rs +++ b/src/web/questions.rs @@ -232,7 +232,7 @@ async fn question_responses( Ok(questions .iter() .map(|question| { - let count = counts.get(question.get_id().key()).copied().unwrap_or(0); + let count = counts.get(&question.get_id().key()).copied().unwrap_or(0); PoolQuestionResponse::new(question, &people, count) }) .collect()) diff --git a/src/web/sessions.rs b/src/web/sessions.rs index d846510..ce1097d 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -15,7 +15,7 @@ use crate::domain::course::Course; use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; use crate::domain::role::Role; -use crate::domain::session_attendance::SessionAttendance; +use crate::domain::session_attendance::{SessionAttendance, SessionAttendanceId}; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse}; @@ -77,7 +77,7 @@ struct SessionAttendanceResponse { impl SessionAttendanceResponse { fn new(attendance: &SessionAttendance, people: &HashMap) -> Self { Self { - id: attendance.get_id().key().to_string(), + id: SessionAttendanceId::composite(attendance.get_session(), &attendance.get_user()).key(), session: attendance.get_session().key().to_string(), course: attendance.get_course().key().to_string(), user: PersonRef::resolve(people, attendance.get_user()), diff --git a/src/web/users.rs b/src/web/users.rs index 81fac68..e3cf60c 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -490,7 +490,7 @@ async fn set_role( for board in boards { st.board_hub.publish( &slug, - board.get_id().key(), + board.get_id().key().as_str(), json!({ "type": "participants", "creator": board.get_creator().key(), @@ -505,7 +505,7 @@ async fn set_role( if let Some(closed_at) = board.get_closed_at() { st.board_hub.publish( &slug, - board.get_id().key(), + board.get_id().key().as_str(), json!({"type": "closed", "closed_at": closed_at.as_millis()}).to_string(), ); }