🚧 wip: macro repair round 1 (R1-R4 partial; 269 errors left)
Browse files at this commitec9e1313bbfbf6be4ea2892a3c6b9fd8f1e21712Parent: b26cabb94 changed files +1628 -1168
- src/ai/server.rs +1 -1
- src/db/answer_image.rs +20 -20
- src/db/appointment.rs +8 -4
- src/db/appointment_slot.rs +19 -11
- src/db/attendance.rs +1 -1
- src/db/badge.rs +7 -5
- src/db/bank_question.rs +72 -35
- src/db/bank_question_image.rs +34 -18
- src/db/board.rs +85 -35
- src/db/board_stroke.rs +34 -19
- src/db/chatbot_thread.rs +6 -6
- src/db/class_blueprint.rs +2 -2
- src/db/class_group.rs +23 -13
- src/db/class_pump.rs +39 -54
- src/db/course.rs +108 -69
- src/db/course_note.rs +24 -14
- src/db/course_note_file.rs +25 -15
- src/db/course_session.rs +18 -12
- src/db/dietary_profile.rs +8 -8
- src/db/enrollment.rs +21 -16
- src/db/event.rs +6 -6
- src/db/exam.rs +76 -76
- src/db/exam_answer.rs +27 -27
- src/db/exam_attempt.rs +46 -46
- src/db/exam_question.rs +64 -53
- src/db/exam_result.rs +24 -24
- src/db/fee_plan.rs +19 -12
- src/db/fee_plan_assignment.rs +13 -13
- src/db/field_update.rs +68 -60
- src/db/meal_attendance.rs +12 -8
- src/db/meal_booking.rs +64 -42
- src/db/meal_ledger.rs +17 -14
- src/db/menu.rs +9 -9
- src/db/menu_dish.rs +21 -24
- src/db/message.rs +10 -10
- src/db/note.rs +19 -14
- src/db/note_file.rs +15 -12
- src/db/parent_link.rs +1 -1
- src/db/payment_ledger.rs +32 -23
- src/db/pomodoro.rs +5 -2
- src/db/pool_question.rs +83 -29
- src/db/question_image.rs +26 -23
- src/db/rag_output.rs +35 -20
- src/db/registration.rs +4 -1
- src/db/session.rs +5 -5
- src/db/session_attendance.rs +30 -23
- src/db/settings.rs +45 -15
- src/db/solution.rs +52 -22
- src/db/subject.rs +20 -14
- src/db/term.rs +21 -13
- src/db/user.rs +23 -15
- src/db/work_entry.rs +19 -19
- src/domain/appointment.rs +0 -1
- src/domain/appointment_slot.rs +0 -1
- src/domain/bank_question.rs +8 -0
- src/domain/chatbot_message.rs +0 -1
- src/domain/chatbot_thread.rs +0 -1
- src/domain/event.rs +2 -3
- src/domain/exam.rs +0 -1
- src/domain/exam_question.rs +0 -1
- src/domain/fee_plan.rs +0 -1
- src/domain/meal_ledger.rs +1 -1
- src/domain/registration.rs +2 -2
- src/domain/session_attendance.rs +2 -2
- src/rate_limit.rs +15 -11
- src/service/appointment.rs +7 -4
- src/service/exam.rs +2 -0
- src/service/exam_attempt.rs +0 -1
- src/service/meal_booking.rs +2 -3
- src/service/payment_ledger.rs +33 -19
- src/service/settings.rs +7 -7
- src/web/appointments.rs +1 -1
- src/web/attendance.rs +3 -3
- src/web/bank_questions.rs +7 -5
- src/web/board_ws.rs +6 -6
- src/web/boards.rs +2 -2
- src/web/chatbot.rs +1 -1
- src/web/classes.rs +2 -2
- src/web/course_notes.rs +4 -4
- src/web/courses.rs +1 -1
- src/web/events.rs +5 -5
- src/web/exam_ws.rs +9 -4
- src/web/exams/attempts.rs +12 -12
- src/web/exams/mod.rs +2 -2
- src/web/exams/questions.rs +2 -2
- src/web/marks.rs +2 -2
- src/web/meals.rs +5 -7
- src/web/messages.rs +1 -1
- src/web/notes.rs +4 -4
- src/web/page.rs +2 -2
- src/web/payments.rs +5 -4
- src/web/questions.rs +1 -1
- src/web/sessions.rs +2 -2
- src/web/users.rs +2 -2
src/ai/server.rsmodified+1 -1
| @@ -646,7 +646,7 @@ async fn open_blob( | |||
| 646 | 646 | ||
| 647 | // The row exists but its blob does not: server-side damage (a lost volume | 647 | // The row exists but its blob does not: server-side damage (a lost volume |
| 648 | // path), exactly as `download_file` reads it — not the service's `404`. | 648 | // path), exactly as `download_file` reads it — not the service's `404`. |
| 649 | - let path = blob_path(&api.files_dir(&slug), file.get_id().key()); | 649 | + let path = blob_path(&api.files_dir(&slug), &file.get_id().key()); |
| 650 | let handle = tokio::fs::File::open(&path).await.map_err(|e| { | 650 | let handle = tokio::fs::File::open(&path).await.map_err(|e| { |
| 651 | ( | 651 | ( |
| 652 | "unavailable", | 652 | "unavailable", |
src/db/answer_image.rsmodified+20 -20
| @@ -44,7 +44,7 @@ pub async fn upsert( | |||
| 44 | db: &Database, | 44 | db: &Database, |
| 45 | image: AnswerImage, | 45 | image: AnswerImage, |
| 46 | ) -> Result<(AnswerImage, Option<String>), AppError> { | 46 | ) -> Result<(AnswerImage, Option<String>), AppError> { |
| 47 | - tx_with_retry(db, false, async |conn| upsert_in(conn, image).await).await | 47 | + tx_with_retry(db, false, async |conn| upsert_in(conn, &image).await).await |
| 48 | } | 48 | } |
| 49 | 49 | ||
| 50 | /// The locked exam-row probe plus the upsert, on one connection. | 50 | /// The locked exam-row probe plus the upsert, on one connection. |
| @@ -54,7 +54,7 @@ pub(crate) async fn upsert_in( | |||
| 54 | ) -> Result<(AnswerImage, Option<String>), AppError> { | 54 | ) -> Result<(AnswerImage, Option<String>), AppError> { |
| 55 | let touched = sqlx::query!( | 55 | let touched = sqlx::query!( |
| 56 | r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, | 56 | r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, |
| 57 | - image.exam as &ExamId, | 57 | + image.exam.uuid(), |
| 58 | ) | 58 | ) |
| 59 | .fetch_optional(&mut *conn) | 59 | .fetch_optional(&mut *conn) |
| 60 | .await?; | 60 | .await?; |
| @@ -64,8 +64,8 @@ pub(crate) async fn upsert_in( | |||
| 64 | let replaced = sqlx::query!( | 64 | let replaced = sqlx::query!( |
| 65 | r#"SELECT file FROM answer_image | 65 | r#"SELECT file FROM answer_image |
| 66 | WHERE question = $1 AND app_user = $2 AND seq = $3"#, | 66 | WHERE question = $1 AND app_user = $2 AND seq = $3"#, |
| 67 | - image.question as &ExamQuestionId, | 67 | + image.question.uuid(), |
| 68 | - image.user as &UserId, | 68 | + image.user.uuid(), |
| 69 | image.seq, | 69 | image.seq, |
| 70 | ) | 70 | ) |
| 71 | .fetch_optional(&mut *conn) | 71 | .fetch_optional(&mut *conn) |
| @@ -81,11 +81,11 @@ pub(crate) async fn upsert_in( | |||
| 81 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", | 81 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 82 | app_user AS "user: UserId", seq, file, | 82 | app_user AS "user: UserId", seq, file, |
| 83 | content_type AS "content_type: FileContentType", size"#, | 83 | content_type AS "content_type: FileContentType", size"#, |
| 84 | - image.exam as &ExamId, | 84 | + image.exam.uuid(), |
| 85 | - image.question as &ExamQuestionId, | 85 | + image.question.uuid(), |
| 86 | - image.user as &UserId, | 86 | + image.user.uuid(), |
| 87 | image.file, | 87 | image.file, |
| 88 | - image.content_type, | 88 | + image.content_type.as_str(), |
| 89 | image.size, | 89 | image.size, |
| 90 | image.seq, | 90 | image.seq, |
| 91 | ) | 91 | ) |
| @@ -108,8 +108,8 @@ pub async fn read( | |||
| 108 | content_type AS "content_type: FileContentType", size | 108 | content_type AS "content_type: FileContentType", size |
| 109 | FROM answer_image | 109 | FROM answer_image |
| 110 | WHERE question = $1 AND app_user = $2 AND seq = $3"#, | 110 | WHERE question = $1 AND app_user = $2 AND seq = $3"#, |
| 111 | - question as &ExamQuestionId, | 111 | + question.uuid(), |
| 112 | - user as &UserId, | 112 | + user.uuid(), |
| 113 | seq, | 113 | seq, |
| 114 | ) | 114 | ) |
| 115 | .fetch_optional(db) | 115 | .fetch_optional(db) |
| @@ -124,7 +124,7 @@ pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<AnswerIma | |||
| 124 | app_user AS "user: UserId", seq, file, | 124 | app_user AS "user: UserId", seq, file, |
| 125 | content_type AS "content_type: FileContentType", size | 125 | content_type AS "content_type: FileContentType", size |
| 126 | FROM answer_image WHERE exam = $1"#, | 126 | FROM answer_image WHERE exam = $1"#, |
| 127 | - exam as &ExamId, | 127 | + exam.uuid(), |
| 128 | ) | 128 | ) |
| 129 | .fetch_all(db) | 129 | .fetch_all(db) |
| 130 | .await?) | 130 | .await?) |
| @@ -145,8 +145,8 @@ pub async fn list_for_exam_user( | |||
| 145 | app_user AS "user: UserId", seq, file, | 145 | app_user AS "user: UserId", seq, file, |
| 146 | content_type AS "content_type: FileContentType", size | 146 | content_type AS "content_type: FileContentType", size |
| 147 | FROM answer_image WHERE exam = $1 AND app_user = $2 AND seq = $3"#, | 147 | FROM answer_image WHERE exam = $1 AND app_user = $2 AND seq = $3"#, |
| 148 | - exam as &ExamId, | 148 | + exam.uuid(), |
| 149 | - user as &UserId, | 149 | + user.uuid(), |
| 150 | seq, | 150 | seq, |
| 151 | ) | 151 | ) |
| 152 | .fetch_all(db) | 152 | .fetch_all(db) |
| @@ -163,8 +163,8 @@ pub async fn list_seqs_for_user( | |||
| 163 | let rows = sqlx::query!( | 163 | let rows = sqlx::query!( |
| 164 | r#"SELECT DISTINCT seq FROM answer_image | 164 | r#"SELECT DISTINCT seq FROM answer_image |
| 165 | WHERE exam = $1 AND app_user = $2 ORDER BY seq ASC"#, | 165 | WHERE exam = $1 AND app_user = $2 ORDER BY seq ASC"#, |
| 166 | - exam as &ExamId, | 166 | + exam.uuid(), |
| 167 | - user as &UserId, | 167 | + user.uuid(), |
| 168 | ) | 168 | ) |
| 169 | .fetch_all(db) | 169 | .fetch_all(db) |
| 170 | .await?; | 170 | .await?; |
| @@ -180,7 +180,7 @@ pub async fn file_keys_for_course( | |||
| 180 | let rows = sqlx::query!( | 180 | let rows = sqlx::query!( |
| 181 | r#"SELECT ai.file FROM answer_image ai | 181 | r#"SELECT ai.file FROM answer_image ai |
| 182 | JOIN exam e ON e.id = ai.exam WHERE e.course = $1"#, | 182 | JOIN exam e ON e.id = ai.exam WHERE e.course = $1"#, |
| 183 | - course as &CourseId, | 183 | + course.uuid(), |
| 184 | ) | 184 | ) |
| 185 | .fetch_all(db) | 185 | .fetch_all(db) |
| 186 | .await?; | 186 | .await?; |
| @@ -194,8 +194,8 @@ pub async fn delete(db: &Database, image: AnswerImage) -> Result<AnswerImage, Ap | |||
| 194 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", | 194 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 195 | app_user AS "user: UserId", seq, file, | 195 | app_user AS "user: UserId", seq, file, |
| 196 | content_type AS "content_type: FileContentType", size"#, | 196 | content_type AS "content_type: FileContentType", size"#, |
| 197 | - image.question as &ExamQuestionId, | 197 | + image.question.uuid(), |
| 198 | - image.user as &UserId, | 198 | + image.user.uuid(), |
| 199 | image.seq, | 199 | image.seq, |
| 200 | ) | 200 | ) |
| 201 | .fetch_optional(db) | 201 | .fetch_optional(db) |
| @@ -215,8 +215,8 @@ pub async fn delete_for_exam_user( | |||
| 215 | ) -> Result<(), AppError> { | 215 | ) -> Result<(), AppError> { |
| 216 | sqlx::query!( | 216 | sqlx::query!( |
| 217 | r#"DELETE FROM answer_image WHERE exam = $1 AND app_user = $2"#, | 217 | r#"DELETE FROM answer_image WHERE exam = $1 AND app_user = $2"#, |
| 218 | - exam as &ExamId, | 218 | + exam.uuid(), |
| 219 | - user as &UserId, | 219 | + user.uuid(), |
| 220 | ) | 220 | ) |
| 221 | .execute(db) | 221 | .execute(db) |
| 222 | .await?; | 222 | .await?; |
src/db/appointment.rsmodified+8 -4
| @@ -177,7 +177,8 @@ pub async fn list_for_teacher( | |||
| 177 | ) | 177 | ) |
| 178 | .fetch_all(db) | 178 | .fetch_all(db) |
| 179 | .await?; | 179 | .await?; |
| 180 | - Ok((rows, rows.len() as i64)) | 180 | + let total = rows.len() as i64; |
| 181 | + Ok((rows, total)) | ||
| 181 | } | 182 | } |
| 182 | Some(limit) => { | 183 | Some(limit) => { |
| 183 | let rows = query_as!( | 184 | let rows = query_as!( |
| @@ -208,7 +209,8 @@ pub async fn list_for_teacher( | |||
| 208 | ) | 209 | ) |
| 209 | .fetch_one(db) | 210 | .fetch_one(db) |
| 210 | .await? | 211 | .await? |
| 211 | - .total; | 212 | + .total |
| 213 | + .unwrap_or(0); | ||
| 212 | Ok((rows, total)) | 214 | Ok((rows, total)) |
| 213 | } | 215 | } |
| 214 | } | 216 | } |
| @@ -313,8 +315,10 @@ pub async fn save_if_unchanged( | |||
| 313 | expected: &Appointment, | 315 | expected: &Appointment, |
| 314 | new: Appointment, | 316 | new: Appointment, |
| 315 | ) -> Result<Option<Appointment>, AppError> { | 317 | ) -> Result<Option<Appointment>, AppError> { |
| 316 | - tx_with_retry(db, false, async |tx| { | 318 | + // Owned capture (`Send` rule of `tx_with_retry` closures). |
| 317 | - decision_cas(&mut *tx, expected, new.clone()).await | 319 | + let expected = expected.clone(); |
| 320 | + tx_with_retry(db, false, async move |tx| { | ||
| 321 | + decision_cas(&mut *tx, &expected, new.clone()).await | ||
| 318 | }) | 322 | }) |
| 319 | .await | 323 | .await |
| 320 | } | 324 | } |
src/db/appointment_slot.rsmodified+19 -11
| @@ -47,7 +47,12 @@ pub async fn insert_claimed( | |||
| 47 | rows: Vec<AppointmentSlot>, | 47 | rows: Vec<AppointmentSlot>, |
| 48 | overlap_refusal: AppError, | 48 | overlap_refusal: AppError, |
| 49 | ) -> Result<Vec<AppointmentSlot>, AppError> { | 49 | ) -> Result<Vec<AppointmentSlot>, AppError> { |
| 50 | - tx_with_retry(db, false, async |tx| { | 50 | + // `Option::take` makes the FnMut move legal: a refusal is terminal |
| 51 | + // (never retried), so the value is taken at most once. | ||
| 52 | + let mut overlap_refusal = Some(overlap_refusal); | ||
| 53 | + // Owned capture (`Send` rule of `tx_with_retry` closures). | ||
| 54 | + let teacher = *teacher; | ||
| 55 | + tx_with_retry(db, false, async move |tx| { | ||
| 51 | // The role handshake. The bar is read off the hierarchy rather than | 56 | // The role handshake. The bar is read off the hierarchy rather than |
| 52 | // spelled out, so a new role cannot drift out of it. | 57 | // spelled out, so a new role cannot drift out of it. |
| 53 | let held = sqlx::query!( | 58 | let held = sqlx::query!( |
| @@ -69,7 +74,7 @@ pub async fn insert_claimed( | |||
| 69 | )); | 74 | )); |
| 70 | } | 75 | } |
| 71 | let mut saved = Vec::with_capacity(rows.len()); | 76 | let mut saved = Vec::with_capacity(rows.len()); |
| 72 | - for row in rows { | 77 | + for row in &rows { |
| 73 | match query_as!( | 78 | match query_as!( |
| 74 | AppointmentSlot, | 79 | AppointmentSlot, |
| 75 | "INSERT INTO appointment_slot (id, teacher, starts_at, ends_at, note, series, created_at) | 80 | "INSERT INTO appointment_slot (id, teacher, starts_at, ends_at, note, series, created_at) |
| @@ -92,7 +97,9 @@ pub async fn insert_claimed( | |||
| 92 | // A teacher cannot publish two overlapping windows: the | 97 | // A teacher cannot publish two overlapping windows: the |
| 93 | // exclusion constraint, answering the caller's overlap 409. | 98 | // exclusion constraint, answering the caller's overlap 409. |
| 94 | Err(err) if unique_violation(&err) == Some("appointment_slot_teacher_span") => { | 99 | Err(err) if unique_violation(&err) == Some("appointment_slot_teacher_span") => { |
| 95 | - return Err(overlap_refusal); | 100 | + return Err(overlap_refusal.take().unwrap_or_else(|| { |
| 101 | + AppError::Internal("overlap refusal re-raised".into()) | ||
| 102 | + })); | ||
| 96 | } | 103 | } |
| 97 | Err(err) => return Err(err.into()), | 104 | Err(err) => return Err(err.into()), |
| 98 | } | 105 | } |
| @@ -246,21 +253,22 @@ pub async fn list_for_series( | |||
| 246 | /// occupied rows are still there, a vanished one is not — which is the | 253 | /// occupied rows are still there, a vanished one is not — which is the |
| 247 | /// 409/404 the caller expects. | 254 | /// 409/404 the caller expects. |
| 248 | pub async fn delete_free(db: &Database, ids: &[AppointmentSlotId]) -> Result<(), AppError> { | 255 | pub async fn delete_free(db: &Database, ids: &[AppointmentSlotId]) -> Result<(), AppError> { |
| 249 | - tx_with_retry(db, false, async |tx| { | 256 | + let ids: Vec<uuid::Uuid> = ids.iter().map(|id| id.uuid()).collect(); |
| 257 | + tx_with_retry(db, false, async move |tx| { | ||
| 250 | // The settled bookings of the *free* slots go first; a booked slot's | 258 | // The settled bookings of the *free* slots go first; a booked slot's |
| 251 | // rows survive (its occupied counter excludes it from both sweeps). | 259 | // rows survive (its occupied counter excludes it from both sweeps). |
| 252 | sqlx::query!( | 260 | sqlx::query!( |
| 253 | "DELETE FROM appointment a | 261 | "DELETE FROM appointment a |
| 254 | USING appointment_slot s | 262 | USING appointment_slot s |
| 255 | WHERE a.slot = s.id AND s.id = ANY($1) AND s.occupied < 1", | 263 | WHERE a.slot = s.id AND s.id = ANY($1) AND s.occupied < 1", |
| 256 | - ids | 264 | + &ids |
| 257 | ) | 265 | ) |
| 258 | .execute(&mut *tx) | 266 | .execute(&mut *tx) |
| 259 | .await?; | 267 | .await?; |
| 260 | - let gone: Vec<AppointmentSlotId> = query_as!( | 268 | + let gone: Vec<AppointmentSlotId> = sqlx::query_scalar!( |
| 261 | - AppointmentSlotId, | 269 | + "DELETE FROM appointment_slot WHERE id = ANY($1) AND occupied < 1 \ |
| 262 | - "DELETE FROM appointment_slot WHERE id = ANY($1) AND occupied < 1 RETURNING id", | 270 | + RETURNING id AS \"id: AppointmentSlotId\"", |
| 263 | - ids | 271 | + &ids |
| 264 | ) | 272 | ) |
| 265 | .fetch_all(&mut *tx) | 273 | .fetch_all(&mut *tx) |
| 266 | .await?; | 274 | .await?; |
| @@ -270,8 +278,8 @@ pub async fn delete_free(db: &Database, ids: &[AppointmentSlotId]) -> Result<(), | |||
| 270 | // Shortfall: distinguish "a live booking holds one" from "one was | 278 | // Shortfall: distinguish "a live booking holds one" from "one was |
| 271 | // never there" off what still exists. | 279 | // never there" off what still exists. |
| 272 | let remaining = sqlx::query!( | 280 | let remaining = sqlx::query!( |
| 273 | - "SELECT count(*) AS standing FROM appointment_slot WHERE id = ANY($1)", | 281 | + "SELECT count(*) AS \"standing!\" FROM appointment_slot WHERE id = ANY($1)", |
| 274 | - ids | 282 | + &ids |
| 275 | ) | 283 | ) |
| 276 | .fetch_one(&mut *tx) | 284 | .fetch_one(&mut *tx) |
| 277 | .await? | 285 | .await? |
src/db/attendance.rsmodified+1 -1
| @@ -32,7 +32,7 @@ pub async fn mark( | |||
| 32 | VALUES ($1, $2, $3, $4) | 32 | VALUES ($1, $2, $3, $4) |
| 33 | ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4 | 33 | ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4 |
| 34 | RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \ | 34 | RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \ |
| 35 | - status, marked_by AS \"marked_by: UserId\"", | 35 | + status AS \"status: AttendanceStatus\", marked_by AS \"marked_by: UserId\"", |
| 36 | event.uuid(), | 36 | event.uuid(), |
| 37 | user.uuid(), | 37 | user.uuid(), |
| 38 | status.as_str(), | 38 | status.as_str(), |
src/db/badge.rsmodified+7 -5
| @@ -4,6 +4,8 @@ | |||
| 4 | //! those are is [`crate::domain::badge::earned`] — pure, no I/O — and the | 4 | //! those are is [`crate::domain::badge::earned`] — pure, no I/O — and the |
| 5 | //! service wrappers the web layer calls live in [`crate::service::badge`]. | 5 | //! service wrappers the web layer calls live in [`crate::service::badge`]. |
| 6 | 6 | ||
| 7 | +use sqlx::AssertSqlSafe; | ||
| 8 | + | ||
| 7 | use crate::constant::{BADGE_AWARD_TABLE, BADGES}; | 9 | use crate::constant::{BADGE_AWARD_TABLE, BADGES}; |
| 8 | use crate::database::Database; | 10 | use crate::database::Database; |
| 9 | use crate::domain::badge::{BadgeAward, BadgeStats}; | 11 | use crate::domain::badge::{BadgeAward, BadgeStats}; |
| @@ -55,17 +57,17 @@ pub async fn load(db: &Database, user: &UserId) -> Result<BadgeStats, AppError> | |||
| 55 | /// but spelled as the projected column on purpose, because it is the | 57 | /// but spelled as the projected column on purpose, because it is the |
| 56 | /// *served* order, not an internal one. | 58 | /// *served* order, not an internal one. |
| 57 | pub async fn list_for(db: &Database, user: &UserId) -> Result<Vec<BadgeAward>, AppError> { | 59 | pub async fn list_for(db: &Database, user: &UserId) -> Result<Vec<BadgeAward>, AppError> { |
| 58 | - let ids: Vec<&str> = BADGES.iter().map(|(id, ..)| *id).collect(); | 60 | + let ids: Vec<String> = BADGES.iter().map(|(id, ..)| (*id).to_string()).collect(); |
| 59 | let awards = sqlx::query_as!( | 61 | let awards = sqlx::query_as!( |
| 60 | BadgeAward, | 62 | BadgeAward, |
| 61 | r#"SELECT badge, | 63 | r#"SELECT badge, |
| 62 | - earned_at AS "earned_at: Timestamp" | 64 | + earned_at AS "earned_at!: Timestamp" |
| 63 | FROM badge_award | 65 | FROM badge_award |
| 64 | WHERE app_user = $1 AND badge = ANY($2) | 66 | WHERE app_user = $1 AND badge = ANY($2) |
| 65 | ORDER BY earned_at ASC, badge ASC | 67 | ORDER BY earned_at ASC, badge ASC |
| 66 | LIMIT $3"#, | 68 | LIMIT $3"#, |
| 67 | user.uuid(), | 69 | user.uuid(), |
| 68 | - ids, | 70 | + &ids, |
| 69 | BADGES.len() as i64, | 71 | BADGES.len() as i64, |
| 70 | ) | 72 | ) |
| 71 | .fetch_all(db) | 73 | .fetch_all(db) |
| @@ -102,13 +104,13 @@ pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> { | |||
| 102 | } | 104 | } |
| 103 | let now = Timestamp::now().as_millis(); | 105 | let now = Timestamp::now().as_millis(); |
| 104 | for badge in earned { | 106 | for badge in earned { |
| 105 | - sqlx::query(&format!( | 107 | + sqlx::query(AssertSqlSafe(format!( |
| 106 | "INSERT INTO {BADGE_AWARD_TABLE} (app_user, badge, earned_at) \ | 108 | "INSERT INTO {BADGE_AWARD_TABLE} (app_user, badge, earned_at) \ |
| 107 | VALUES ($1, $2, $3) \ | 109 | VALUES ($1, $2, $3) \ |
| 108 | ON CONFLICT (app_user, badge) DO UPDATE \ | 110 | ON CONFLICT (app_user, badge) DO UPDATE \ |
| 109 | SET earned_at = badge_award.earned_at \ | 111 | SET earned_at = badge_award.earned_at \ |
| 110 | WHERE badge_award.earned_at IS NULL" | 112 | WHERE badge_award.earned_at IS NULL" |
| 111 | - )) | 113 | + ))) |
| 112 | .bind(user.uuid()) | 114 | .bind(user.uuid()) |
| 113 | .bind(badge) | 115 | .bind(badge) |
| 114 | .bind(now) | 116 | .bind(now) |
src/db/bank_question.rsmodified+72 -35
| @@ -14,7 +14,10 @@ use crate::db::page::{PagedList, Param}; | |||
| 14 | use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; | 14 | use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; |
| 15 | use crate::domain::bank_question_image::BankQuestionImage; | 15 | use crate::domain::bank_question_image::BankQuestionImage; |
| 16 | use crate::domain::exam::ExamId; | 16 | use crate::domain::exam::ExamId; |
| 17 | -use crate::domain::exam_question::{QuestionPoints, QuestionSpec, QuestionText}; | 17 | +use crate::domain::exam_question::{ |
| 18 | + Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | ||
| 19 | +}; | ||
| 20 | +use crate::domain::note_file::FileContentType; | ||
| 18 | use crate::domain::subject::SubjectId; | 21 | use crate::domain::subject::SubjectId; |
| 19 | use crate::domain::text_fold::{search_fold, search_fold_sql}; | 22 | use crate::domain::text_fold::{search_fold, search_fold_sql}; |
| 20 | use crate::domain::timestamp::Timestamp; | 23 | use crate::domain::timestamp::Timestamp; |
| @@ -76,18 +79,25 @@ async fn insert( | |||
| 76 | (id, owner, subject, text, kind, points, choices, correct, | 79 | (id, owner, subject, text, kind, points, choices, correct, |
| 77 | source_exam, visibility, created_at) | 80 | source_exam, visibility, created_at) |
| 78 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) | 81 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) |
| 79 | - RETURNING *"#, | 82 | + RETURNING id AS "id: BankQuestionId", owner AS "owner: UserId", |
| 80 | - question.id, | 83 | + subject AS "subject: Option<SubjectId>", text AS "text: QuestionText", |
| 81 | - question.owner, | 84 | + kind AS "kind: QuestionKind", points AS "points: QuestionPoints", |
| 82 | - question.subject, | 85 | + choices AS "choices: Option<Json<Vec<Choice>>>", |
| 83 | - question.text, | 86 | + correct AS "correct: Option<ChoiceId>", |
| 84 | - question.kind, | 87 | + source_exam AS "source_exam: Option<ExamId>", |
| 85 | - question.points, | 88 | + visibility AS "visibility: BankVisibility", |
| 89 | + created_at AS "created_at: Timestamp""#, | ||
| 90 | + question.id.uuid(), | ||
| 91 | + question.owner.uuid(), | ||
| 92 | + question.subject.as_ref().map(SubjectId::uuid), | ||
| 93 | + question.text.as_str(), | ||
| 94 | + question.kind.as_str(), | ||
| 95 | + question.points.as_i64(), | ||
| 86 | question.choices, | 96 | question.choices, |
| 87 | - question.correct, | 97 | + question.correct.as_ref().map(ChoiceId::as_str), |
| 88 | - question.source_exam, | 98 | + question.source_exam.as_ref().map(ExamId::uuid), |
| 89 | - question.visibility, | 99 | + question.visibility.as_str(), |
| 90 | - question.created_at, | 100 | + question.created_at.as_millis(), |
| 91 | ) | 101 | ) |
| 92 | .fetch_one(db) | 102 | .fetch_one(db) |
| 93 | .await?; | 103 | .await?; |
| @@ -97,8 +107,16 @@ async fn insert( | |||
| 97 | pub async fn read(db: &Database, id: &BankQuestionId) -> Result<Option<BankQuestion>, AppError> { | 107 | pub async fn read(db: &Database, id: &BankQuestionId) -> Result<Option<BankQuestion>, AppError> { |
| 98 | let row = sqlx::query_as!( | 108 | let row = sqlx::query_as!( |
| 99 | BankQuestion, | 109 | BankQuestion, |
| 100 | - "SELECT * FROM bank_question WHERE id = $1", | 110 | + r#"SELECT id AS "id: BankQuestionId", owner AS "owner: UserId", |
| 101 | - id | 111 | + subject AS "subject: Option<SubjectId>", text AS "text: QuestionText", |
| 112 | + kind AS "kind: QuestionKind", points AS "points: QuestionPoints", | ||
| 113 | + choices AS "choices: Option<Json<Vec<Choice>>>", | ||
| 114 | + correct AS "correct: Option<ChoiceId>", | ||
| 115 | + source_exam AS "source_exam: Option<ExamId>", | ||
| 116 | + visibility AS "visibility: BankVisibility", | ||
| 117 | + created_at AS "created_at: Timestamp" | ||
| 118 | + FROM bank_question WHERE id = $1"#, | ||
| 119 | + id.uuid() | ||
| 102 | ) | 120 | ) |
| 103 | .fetch_optional(db) | 121 | .fetch_optional(db) |
| 104 | .await?; | 122 | .await?; |
| @@ -205,7 +223,7 @@ pub async fn usage_counts( | |||
| 205 | if ids.is_empty() { | 223 | if ids.is_empty() { |
| 206 | return Ok(HashMap::new()); | 224 | return Ok(HashMap::new()); |
| 207 | } | 225 | } |
| 208 | - let ids: Vec<BankQuestionId> = ids.iter().map(|id| (*id).clone()).collect(); | 226 | + let ids: Vec<uuid::Uuid> = ids.iter().map(|id| id.uuid()).collect(); |
| 209 | let rows = sqlx::query!( | 227 | let rows = sqlx::query!( |
| 210 | r#"SELECT from_bank AS "from_bank: BankQuestionId", count(*) AS n | 228 | r#"SELECT from_bank AS "from_bank: BankQuestionId", count(*) AS n |
| 211 | FROM exam_question | 229 | FROM exam_question |
| @@ -263,22 +281,29 @@ pub async fn update_if_unchanged( | |||
| 263 | AND choices IS NOT DISTINCT FROM $13 | 281 | AND choices IS NOT DISTINCT FROM $13 |
| 264 | AND correct IS NOT DISTINCT FROM $14 | 282 | AND correct IS NOT DISTINCT FROM $14 |
| 265 | AND visibility = $15 | 283 | AND visibility = $15 |
| 266 | - RETURNING *"#, | 284 | + RETURNING id AS "id: BankQuestionId", owner AS "owner: UserId", |
| 267 | - expected.id, | 285 | + subject AS "subject: Option<SubjectId>", text AS "text: QuestionText", |
| 268 | - subject, | 286 | + kind AS "kind: QuestionKind", points AS "points: QuestionPoints", |
| 269 | - text, | 287 | + choices AS "choices: Option<Json<Vec<Choice>>>", |
| 270 | - points, | 288 | + correct AS "correct: Option<ChoiceId>", |
| 271 | - kind, | 289 | + source_exam AS "source_exam: Option<ExamId>", |
| 290 | + visibility AS "visibility: BankVisibility", | ||
| 291 | + created_at AS "created_at: Timestamp""#, | ||
| 292 | + expected.id.uuid(), | ||
| 293 | + subject.as_ref().map(SubjectId::uuid), | ||
| 294 | + text.as_str(), | ||
| 295 | + points.as_i64(), | ||
| 296 | + kind.as_str(), | ||
| 272 | choices, | 297 | choices, |
| 273 | - correct, | 298 | + correct.as_ref().map(ChoiceId::as_str), |
| 274 | - visibility, | 299 | + visibility.as_str(), |
| 275 | - expected.subject, | 300 | + expected.subject.as_ref().map(SubjectId::uuid), |
| 276 | - expected.text, | 301 | + expected.text.as_str(), |
| 277 | - expected.points, | 302 | + expected.points.as_i64(), |
| 278 | - expected.kind, | 303 | + expected.kind.as_str(), |
| 279 | expected.choices, | 304 | expected.choices, |
| 280 | - expected.correct, | 305 | + expected.correct.as_ref().map(ChoiceId::as_str), |
| 281 | - expected.visibility, | 306 | + expected.visibility.as_str(), |
| 282 | ) | 307 | ) |
| 283 | .fetch_optional(db) | 308 | .fetch_optional(db) |
| 284 | .await?; | 309 | .await?; |
| @@ -309,27 +334,39 @@ pub async fn delete( | |||
| 309 | let id = target.id.clone(); | 334 | let id = target.id.clone(); |
| 310 | sqlx::query!( | 335 | sqlx::query!( |
| 311 | "UPDATE exam_question SET from_bank = NULL WHERE from_bank = $1", | 336 | "UPDATE exam_question SET from_bank = NULL WHERE from_bank = $1", |
| 312 | - id | 337 | + id.uuid() |
| 313 | ) | 338 | ) |
| 314 | .execute(tx) | 339 | .execute(tx) |
| 315 | .await?; | 340 | .await?; |
| 316 | sqlx::query!( | 341 | sqlx::query!( |
| 317 | "UPDATE exam_question SET banked_as = NULL WHERE banked_as = $1", | 342 | "UPDATE exam_question SET banked_as = NULL WHERE banked_as = $1", |
| 318 | - id | 343 | + id.uuid() |
| 319 | ) | 344 | ) |
| 320 | .execute(tx) | 345 | .execute(tx) |
| 321 | .await?; | 346 | .await?; |
| 322 | let images = sqlx::query_as!( | 347 | let images = sqlx::query_as!( |
| 323 | BankQuestionImage, | 348 | BankQuestionImage, |
| 324 | - "DELETE FROM bank_question_image WHERE bank_question = $1 RETURNING *", | 349 | + r#"DELETE FROM bank_question_image WHERE bank_question = $1 |
| 325 | - id | 350 | + RETURNING bank_question AS "bank_question: BankQuestionId", |
| 351 | + slot AS "slot: Option<ChoiceId>", file, | ||
| 352 | + content_type AS "content_type: FileContentType", size"#, | ||
| 353 | + id.uuid() | ||
| 326 | ) | 354 | ) |
| 327 | .fetch_all(tx) | 355 | .fetch_all(tx) |
| 328 | .await?; | 356 | .await?; |
| 329 | let question = sqlx::query_as!( | 357 | let question = sqlx::query_as!( |
| 330 | BankQuestion, | 358 | BankQuestion, |
| 331 | - "DELETE FROM bank_question WHERE id = $1 RETURNING *", | 359 | + r#"DELETE FROM bank_question WHERE id = $1 |
| 332 | - id | 360 | + RETURNING id AS "id: BankQuestionId", owner AS "owner: UserId", |
| 361 | + subject AS "subject: Option<SubjectId>", | ||
| 362 | + text AS "text: QuestionText", kind AS "kind: QuestionKind", | ||
| 363 | + points AS "points: QuestionPoints", | ||
| 364 | + choices AS "choices: Option<Json<Vec<Choice>>>", | ||
| 365 | + correct AS "correct: Option<ChoiceId>", | ||
| 366 | + source_exam AS "source_exam: Option<ExamId>", | ||
| 367 | + visibility AS "visibility: BankVisibility", | ||
| 368 | + created_at AS "created_at: Timestamp""#, | ||
| 369 | + id.uuid() | ||
| 333 | ) | 370 | ) |
| 334 | .fetch_optional(tx) | 371 | .fetch_optional(tx) |
| 335 | .await? | 372 | .await? |
src/db/bank_question_image.rsmodified+34 -18
| @@ -7,6 +7,7 @@ use crate::database::{Database, foreign_key_violation, tx_with_retry}; | |||
| 7 | use crate::domain::bank_question::BankQuestionId; | 7 | use crate::domain::bank_question::BankQuestionId; |
| 8 | use crate::domain::bank_question_image::BankQuestionImage; | 8 | use crate::domain::bank_question_image::BankQuestionImage; |
| 9 | use crate::domain::exam_question::ChoiceId; | 9 | use crate::domain::exam_question::ChoiceId; |
| 10 | +use crate::domain::note_file::FileContentType; | ||
| 10 | use crate::error::AppError; | 11 | use crate::error::AppError; |
| 11 | 12 | ||
| 12 | /// Create or replace the slot's image row — the table's `NULLS NOT DISTINCT` | 13 | /// Create or replace the slot's image row — the table's `NULLS NOT DISTINCT` |
| @@ -33,8 +34,8 @@ pub async fn upsert( | |||
| 33 | r#"SELECT file FROM bank_question_image | 34 | r#"SELECT file FROM bank_question_image |
| 34 | WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2 | 35 | WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2 |
| 35 | FOR UPDATE"#, | 36 | FOR UPDATE"#, |
| 36 | - image.bank_question.clone(), | 37 | + image.bank_question.uuid(), |
| 37 | - image.slot.clone(), | 38 | + image.slot.as_ref().map(ChoiceId::as_str), |
| 38 | ) | 39 | ) |
| 39 | .fetch_optional(tx) | 40 | .fetch_optional(tx) |
| 40 | .await? | 41 | .await? |
| @@ -46,11 +47,13 @@ pub async fn upsert( | |||
| 46 | VALUES ($1, $2, $3, $4, $5) | 47 | VALUES ($1, $2, $3, $4, $5) |
| 47 | ON CONFLICT (bank_question, slot) DO UPDATE | 48 | ON CONFLICT (bank_question, slot) DO UPDATE |
| 48 | SET file = $3, content_type = $4, size = $5 | 49 | SET file = $3, content_type = $4, size = $5 |
| 49 | - RETURNING *"#, | 50 | + RETURNING bank_question AS "bank_question: BankQuestionId", |
| 50 | - image.bank_question.clone(), | 51 | + slot AS "slot: Option<ChoiceId>", file, |
| 51 | - image.slot.clone(), | 52 | + content_type AS "content_type: FileContentType", size"#, |
| 53 | + image.bank_question.uuid(), | ||
| 54 | + image.slot.as_ref().map(ChoiceId::as_str), | ||
| 52 | image.file.clone(), | 55 | image.file.clone(), |
| 53 | - image.content_type, | 56 | + image.content_type.as_str(), |
| 54 | image.size, | 57 | image.size, |
| 55 | ) | 58 | ) |
| 56 | .fetch_one(tx) | 59 | .fetch_one(tx) |
| @@ -73,10 +76,13 @@ pub async fn read_slot( | |||
| 73 | ) -> Result<Option<BankQuestionImage>, AppError> { | 76 | ) -> Result<Option<BankQuestionImage>, AppError> { |
| 74 | let row = sqlx::query_as!( | 77 | let row = sqlx::query_as!( |
| 75 | BankQuestionImage, | 78 | BankQuestionImage, |
| 76 | - r#"SELECT * FROM bank_question_image | 79 | + r#"SELECT bank_question AS "bank_question: BankQuestionId", |
| 80 | + slot AS "slot: Option<ChoiceId>", file, | ||
| 81 | + content_type AS "content_type: FileContentType", size | ||
| 82 | + FROM bank_question_image | ||
| 77 | WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2"#, | 83 | WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2"#, |
| 78 | - question, | 84 | + question.uuid(), |
| 79 | - slot.cloned(), | 85 | + slot.map(ChoiceId::as_str), |
| 80 | ) | 86 | ) |
| 81 | .fetch_optional(db) | 87 | .fetch_optional(db) |
| 82 | .await?; | 88 | .await?; |
| @@ -89,8 +95,11 @@ pub async fn list_for_question( | |||
| 89 | ) -> Result<Vec<BankQuestionImage>, AppError> { | 95 | ) -> Result<Vec<BankQuestionImage>, AppError> { |
| 90 | let rows = sqlx::query_as!( | 96 | let rows = sqlx::query_as!( |
| 91 | BankQuestionImage, | 97 | BankQuestionImage, |
| 92 | - "SELECT * FROM bank_question_image WHERE bank_question = $1", | 98 | + r#"SELECT bank_question AS "bank_question: BankQuestionId", |
| 93 | - question | 99 | + slot AS "slot: Option<ChoiceId>", file, |
| 100 | + content_type AS "content_type: FileContentType", size | ||
| 101 | + FROM bank_question_image WHERE bank_question = $1"#, | ||
| 102 | + question.uuid() | ||
| 94 | ) | 103 | ) |
| 95 | .fetch_all(db) | 104 | .fetch_all(db) |
| 96 | .await?; | 105 | .await?; |
| @@ -106,10 +115,13 @@ pub async fn list_for_questions( | |||
| 106 | if questions.is_empty() { | 115 | if questions.is_empty() { |
| 107 | return Ok(Vec::new()); | 116 | return Ok(Vec::new()); |
| 108 | } | 117 | } |
| 109 | - let ids: Vec<BankQuestionId> = questions.iter().map(|q| (*q).clone()).collect(); | 118 | + let ids: Vec<uuid::Uuid> = questions.iter().map(|q| q.uuid()).collect(); |
| 110 | let rows = sqlx::query_as!( | 119 | let rows = sqlx::query_as!( |
| 111 | BankQuestionImage, | 120 | BankQuestionImage, |
| 112 | - "SELECT * FROM bank_question_image WHERE bank_question = ANY($1)", | 121 | + r#"SELECT bank_question AS "bank_question: BankQuestionId", |
| 122 | + slot AS "slot: Option<ChoiceId>", file, | ||
| 123 | + content_type AS "content_type: FileContentType", size | ||
| 124 | + FROM bank_question_image WHERE bank_question = ANY($1)"#, | ||
| 113 | ids | 125 | ids |
| 114 | ) | 126 | ) |
| 115 | .fetch_all(db) | 127 | .fetch_all(db) |
| @@ -138,8 +150,10 @@ pub async fn delete_choices_not_in( | |||
| 138 | WHERE bank_question = $1 | 150 | WHERE bank_question = $1 |
| 139 | AND slot IS NOT NULL | 151 | AND slot IS NOT NULL |
| 140 | AND NOT (slot = ANY($2)) | 152 | AND NOT (slot = ANY($2)) |
| 141 | - RETURNING *"#, | 153 | + RETURNING bank_question AS "bank_question: BankQuestionId", |
| 142 | - question, | 154 | + slot AS "slot: Option<ChoiceId>", file, |
| 155 | + content_type AS "content_type: FileContentType", size"#, | ||
| 156 | + question.uuid(), | ||
| 143 | keep | 157 | keep |
| 144 | ) | 158 | ) |
| 145 | .fetch_all(db) | 159 | .fetch_all(db) |
| @@ -155,9 +169,11 @@ pub async fn delete( | |||
| 155 | BankQuestionImage, | 169 | BankQuestionImage, |
| 156 | r#"DELETE FROM bank_question_image | 170 | r#"DELETE FROM bank_question_image |
| 157 | WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2 | 171 | WHERE bank_question = $1 AND slot IS NOT DISTINCT FROM $2 |
| 158 | - RETURNING *"#, | 172 | + RETURNING bank_question AS "bank_question: BankQuestionId", |
| 159 | - image.bank_question, | 173 | + slot AS "slot: Option<ChoiceId>", file, |
| 160 | - image.slot | 174 | + content_type AS "content_type: FileContentType", size"#, |
| 175 | + image.bank_question.uuid(), | ||
| 176 | + image.slot.as_ref().map(ChoiceId::as_str) | ||
| 161 | ) | 177 | ) |
| 162 | .fetch_optional(db) | 178 | .fetch_optional(db) |
| 163 | .await?; | 179 | .await?; |
src/db/board.rsmodified+85 -35
| @@ -41,14 +41,23 @@ pub async fn create( | |||
| 41 | epoch, closed_at, created_at) | 41 | epoch, closed_at, created_at) |
| 42 | SELECT $3, $1, $4, $5, false, NULL, NULL, 0, NULL, $6 | 42 | SELECT $3, $1, $4, $5, false, NULL, NULL, 0, NULL, $6 |
| 43 | WHERE EXISTS (SELECT 1 FROM seat) | 43 | WHERE EXISTS (SELECT 1 FROM seat) |
| 44 | - RETURNING id, creator, title, participants, locked, locked_by, locked_at, | 44 | + RETURNING id AS "id: BoardId", creator AS "creator: UserId", |
| 45 | - epoch, closed_at, created_at"#, | 45 | + title AS "title: BoardTitle", |
| 46 | - board.creator, | 46 | + participants AS "participants: Vec<UserId>", locked, |
| 47 | + locked_by AS "locked_by: Option<UserId>", | ||
| 48 | + locked_at AS "locked_at: Option<Timestamp>", epoch, | ||
| 49 | + closed_at AS "closed_at: Option<Timestamp>", | ||
| 50 | + created_at AS "created_at: Timestamp""#, | ||
| 51 | + board.creator.uuid(), | ||
| 47 | MAX_BOARDS_PER_CREATOR, | 52 | MAX_BOARDS_PER_CREATOR, |
| 48 | - board.id, | 53 | + board.id.uuid(), |
| 49 | - board.title, | 54 | + board.title.as_str(), |
| 50 | - &board.participants, | 55 | + &board |
| 51 | - board.created_at | 56 | + .participants |
| 57 | + .iter() | ||
| 58 | + .map(UserId::uuid) | ||
| 59 | + .collect::<Vec<uuid::Uuid>>(), | ||
| 60 | + board.created_at.as_millis() | ||
| 52 | ) | 61 | ) |
| 53 | .fetch_optional(db) | 62 | .fetch_optional(db) |
| 54 | .await; | 63 | .await; |
| @@ -71,10 +80,15 @@ pub async fn create( | |||
| 71 | pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError> { | 80 | pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError> { |
| 72 | let board = sqlx::query_as!( | 81 | let board = sqlx::query_as!( |
| 73 | Board, | 82 | Board, |
| 74 | - r#"SELECT id, creator, title, participants, locked, locked_by, locked_at, | 83 | + r#"SELECT id AS "id: BoardId", creator AS "creator: UserId", |
| 75 | - epoch, closed_at, created_at | 84 | + title AS "title: BoardTitle", |
| 85 | + participants AS "participants: Vec<UserId>", locked, | ||
| 86 | + locked_by AS "locked_by: Option<UserId>", | ||
| 87 | + locked_at AS "locked_at: Option<Timestamp>", epoch, | ||
| 88 | + closed_at AS "closed_at: Option<Timestamp>", | ||
| 89 | + created_at AS "created_at: Timestamp" | ||
| 76 | FROM board WHERE id = $1"#, | 90 | FROM board WHERE id = $1"#, |
| 77 | - id | 91 | + id.uuid() |
| 78 | ) | 92 | ) |
| 79 | .fetch_optional(db) | 93 | .fetch_optional(db) |
| 80 | .await?; | 94 | .await?; |
| @@ -122,10 +136,18 @@ pub async fn set_participants( | |||
| 122 | let updated = sqlx::query_as!( | 136 | let updated = sqlx::query_as!( |
| 123 | Board, | 137 | Board, |
| 124 | r#"UPDATE board SET participants = $2 WHERE id = $1 | 138 | r#"UPDATE board SET participants = $2 WHERE id = $1 |
| 125 | - RETURNING id, creator, title, participants, locked, locked_by, locked_at, | 139 | + RETURNING id AS "id: BoardId", creator AS "creator: UserId", |
| 126 | - epoch, closed_at, created_at"#, | 140 | + title AS "title: BoardTitle", |
| 127 | - board.id, | 141 | + participants AS "participants: Vec<UserId>", locked, |
| 142 | + locked_by AS "locked_by: Option<UserId>", | ||
| 143 | + locked_at AS "locked_at: Option<Timestamp>", epoch, | ||
| 144 | + closed_at AS "closed_at: Option<Timestamp>", | ||
| 145 | + created_at AS "created_at: Timestamp""#, | ||
| 146 | + board.id.uuid(), | ||
| 128 | &participants | 147 | &participants |
| 148 | + .iter() | ||
| 149 | + .map(UserId::uuid) | ||
| 150 | + .collect::<Vec<uuid::Uuid>>() | ||
| 129 | ) | 151 | ) |
| 130 | .fetch_optional(db) | 152 | .fetch_optional(db) |
| 131 | .await?; | 153 | .await?; |
| @@ -136,10 +158,15 @@ pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Resul | |||
| 136 | let updated = sqlx::query_as!( | 158 | let updated = sqlx::query_as!( |
| 137 | Board, | 159 | Board, |
| 138 | r#"UPDATE board SET title = $2 WHERE id = $1 | 160 | r#"UPDATE board SET title = $2 WHERE id = $1 |
| 139 | - RETURNING id, creator, title, participants, locked, locked_by, locked_at, | 161 | + RETURNING id AS "id: BoardId", creator AS "creator: UserId", |
| 140 | - epoch, closed_at, created_at"#, | 162 | + title AS "title: BoardTitle", |
| 141 | - board.id, | 163 | + participants AS "participants: Vec<UserId>", locked, |
| 142 | - title | 164 | + locked_by AS "locked_by: Option<UserId>", |
| 165 | + locked_at AS "locked_at: Option<Timestamp>", epoch, | ||
| 166 | + closed_at AS "closed_at: Option<Timestamp>", | ||
| 167 | + created_at AS "created_at: Timestamp""#, | ||
| 168 | + board.id.uuid(), | ||
| 169 | + title.as_str() | ||
| 143 | ) | 170 | ) |
| 144 | .fetch_optional(db) | 171 | .fetch_optional(db) |
| 145 | .await?; | 172 | .await?; |
| @@ -158,12 +185,17 @@ pub async fn set_locked( | |||
| 158 | let updated = sqlx::query_as!( | 185 | let updated = sqlx::query_as!( |
| 159 | Board, | 186 | Board, |
| 160 | r#"UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1 | 187 | r#"UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1 |
| 161 | - RETURNING id, creator, title, participants, locked, locked_by, locked_at, | 188 | + RETURNING id AS "id: BoardId", creator AS "creator: UserId", |
| 162 | - epoch, closed_at, created_at"#, | 189 | + title AS "title: BoardTitle", |
| 163 | - board.id, | 190 | + participants AS "participants: Vec<UserId>", locked, |
| 191 | + locked_by AS "locked_by: Option<UserId>", | ||
| 192 | + locked_at AS "locked_at: Option<Timestamp>", epoch, | ||
| 193 | + closed_at AS "closed_at: Option<Timestamp>", | ||
| 194 | + created_at AS "created_at: Timestamp""#, | ||
| 195 | + board.id.uuid(), | ||
| 164 | locked, | 196 | locked, |
| 165 | - locked.then(|| by.clone()), | 197 | + locked.then(|| by.uuid()), |
| 166 | - locked.then(|| now) | 198 | + locked.then(|| now.as_millis()) |
| 167 | ) | 199 | ) |
| 168 | .fetch_optional(db) | 200 | .fetch_optional(db) |
| 169 | .await?; | 201 | .await?; |
| @@ -193,10 +225,18 @@ pub(crate) async fn invite_group( | |||
| 193 | WHERE id = $1 | 225 | WHERE id = $1 |
| 194 | AND cardinality((SELECT coalesce(array_agg(DISTINCT x), '{}') | 226 | AND cardinality((SELECT coalesce(array_agg(DISTINCT x), '{}') |
| 195 | FROM unnest(participants || $2::uuid[]) AS x)) <= $3 | 227 | FROM unnest(participants || $2::uuid[]) AS x)) <= $3 |
| 196 | - RETURNING id, creator, title, participants, locked, locked_by, locked_at, | 228 | + RETURNING id AS "id: BoardId", creator AS "creator: UserId", |
| 197 | - epoch, closed_at, created_at"#, | 229 | + title AS "title: BoardTitle", |
| 198 | - board.clone(), | 230 | + participants AS "participants: Vec<UserId>", locked, |
| 199 | - &invited, | 231 | + locked_by AS "locked_by: Option<UserId>", |
| 232 | + locked_at AS "locked_at: Option<Timestamp>", epoch, | ||
| 233 | + closed_at AS "closed_at: Option<Timestamp>", | ||
| 234 | + created_at AS "created_at: Timestamp""#, | ||
| 235 | + board.uuid(), | ||
| 236 | + &invited | ||
| 237 | + .iter() | ||
| 238 | + .map(UserId::uuid) | ||
| 239 | + .collect::<Vec<uuid::Uuid>>(), | ||
| 200 | MAX_BOARD_PARTICIPANTS as i64 | 240 | MAX_BOARD_PARTICIPANTS as i64 |
| 201 | ) | 241 | ) |
| 202 | .fetch_optional(db) | 242 | .fetch_optional(db) |
| @@ -216,10 +256,15 @@ pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> { | |||
| 216 | let closed = sqlx::query_as!( | 256 | let closed = sqlx::query_as!( |
| 217 | Board, | 257 | Board, |
| 218 | r#"UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL | 258 | r#"UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL |
| 219 | - RETURNING id, creator, title, participants, locked, locked_by, locked_at, | 259 | + RETURNING id AS "id: BoardId", creator AS "creator: UserId", |
| 220 | - epoch, closed_at, created_at"#, | 260 | + title AS "title: BoardTitle", |
| 221 | - board.id, | 261 | + participants AS "participants: Vec<UserId>", locked, |
| 222 | - Timestamp::now() | 262 | + locked_by AS "locked_by: Option<UserId>", |
| 263 | + locked_at AS "locked_at: Option<Timestamp>", epoch, | ||
| 264 | + closed_at AS "closed_at: Option<Timestamp>", | ||
| 265 | + created_at AS "created_at: Timestamp""#, | ||
| 266 | + board.id.uuid(), | ||
| 267 | + Timestamp::now().as_millis() | ||
| 223 | ) | 268 | ) |
| 224 | .fetch_optional(db) | 269 | .fetch_optional(db) |
| 225 | .await?; | 270 | .await?; |
| @@ -241,15 +286,20 @@ pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> { | |||
| 241 | /// under a record that no longer exists. | 286 | /// under a record that no longer exists. |
| 242 | pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> { | 287 | pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> { |
| 243 | tx_with_retry(db, true, async |conn| { | 288 | tx_with_retry(db, true, async |conn| { |
| 244 | - sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id) | 289 | + sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id.uuid()) |
| 245 | .execute(&mut *conn) | 290 | .execute(&mut *conn) |
| 246 | .await?; | 291 | .await?; |
| 247 | let gone = sqlx::query_as!( | 292 | let gone = sqlx::query_as!( |
| 248 | Board, | 293 | Board, |
| 249 | r#"DELETE FROM board WHERE id = $1 | 294 | r#"DELETE FROM board WHERE id = $1 |
| 250 | - RETURNING id, creator, title, participants, locked, locked_by, locked_at, | 295 | + RETURNING id AS "id: BoardId", creator AS "creator: UserId", |
| 251 | - epoch, closed_at, created_at"#, | 296 | + title AS "title: BoardTitle", |
| 252 | - board.id | 297 | + participants AS "participants: Vec<UserId>", locked, |
| 298 | + locked_by AS "locked_by: Option<UserId>", | ||
| 299 | + locked_at AS "locked_at: Option<Timestamp>", epoch, | ||
| 300 | + closed_at AS "closed_at: Option<Timestamp>", | ||
| 301 | + created_at AS "created_at: Timestamp""#, | ||
| 302 | + board.id.uuid() | ||
| 253 | ) | 303 | ) |
| 254 | .fetch_optional(&mut *conn) | 304 | .fetch_optional(&mut *conn) |
| 255 | .await?; | 305 | .await?; |
| @@ -259,7 +309,7 @@ pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> { | |||
| 259 | // the limit shut. | 309 | // the limit shut. |
| 260 | sqlx::query!( | 310 | sqlx::query!( |
| 261 | "UPDATE app_user SET board_count = GREATEST(board_count - 1, 0) WHERE id = $1", | 311 | "UPDATE app_user SET board_count = GREATEST(board_count - 1, 0) WHERE id = $1", |
| 262 | - board.creator | 312 | + board.creator.uuid() |
| 263 | ) | 313 | ) |
| 264 | .execute(&mut *conn) | 314 | .execute(&mut *conn) |
| 265 | .await?; | 315 | .await?; |
src/db/board_stroke.rsmodified+34 -19
| @@ -56,16 +56,18 @@ pub async fn append( | |||
| 56 | INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at) | 56 | INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at) |
| 57 | SELECT $5, $1, $6, $7, $8, NULL, $3, $9 | 57 | SELECT $5, $1, $6, $7, $8, NULL, $3, $9 |
| 58 | WHERE EXISTS (SELECT 1 FROM bump) | 58 | WHERE EXISTS (SELECT 1 FROM bump) |
| 59 | - RETURNING id, board, author, kind, payload, count, epoch, created_at"#, | 59 | + RETURNING id AS "id: BoardStrokeId", board AS "board: BoardId", |
| 60 | - board.clone(), | 60 | + author AS "author: UserId", kind, payload, count, epoch, |
| 61 | + created_at AS "created_at: Timestamp""#, | ||
| 62 | + board.uuid(), | ||
| 61 | MAX_BOARD_STROKES, | 63 | MAX_BOARD_STROKES, |
| 62 | epoch, | 64 | epoch, |
| 63 | MAX_EPOCH_STROKES, | 65 | MAX_EPOCH_STROKES, |
| 64 | - BoardStrokeId::generate(), | 66 | + BoardStrokeId::generate().uuid(), |
| 65 | - author.clone(), | 67 | + author.uuid(), |
| 66 | KIND_STROKE, | 68 | KIND_STROKE, |
| 67 | payload, | 69 | payload, |
| 68 | - Timestamp::now() | 70 | + Timestamp::now().as_millis() |
| 69 | ) | 71 | ) |
| 70 | .fetch_optional(db) | 72 | .fetch_optional(db) |
| 71 | .await?; | 73 | .await?; |
| @@ -169,8 +171,13 @@ pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result<BoardS | |||
| 169 | // guarded bump below. | 171 | // guarded bump below. |
| 170 | let live = sqlx::query_as!( | 172 | let live = sqlx::query_as!( |
| 171 | Board, | 173 | Board, |
| 172 | - r#"SELECT id, creator, title, participants, locked, locked_by, locked_at, | 174 | + r#"SELECT id AS "id: BoardId", creator AS "creator: UserId", |
| 173 | - epoch, closed_at, created_at | 175 | + title AS "title: BoardTitle", |
| 176 | + participants AS "participants: Vec<UserId>", locked, | ||
| 177 | + locked_by AS "locked_by: Option<UserId>", | ||
| 178 | + locked_at AS "locked_at: Option<Timestamp>", epoch, | ||
| 179 | + closed_at AS "closed_at: Option<Timestamp>", | ||
| 180 | + created_at AS "created_at: Timestamp" | ||
| 174 | FROM board WHERE id = $1 FOR UPDATE"#, | 181 | FROM board WHERE id = $1 FOR UPDATE"#, |
| 175 | board.uuid() | 182 | board.uuid() |
| 176 | ) | 183 | ) |
| @@ -224,14 +231,16 @@ pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result<BoardS | |||
| 224 | BoardStroke, | 231 | BoardStroke, |
| 225 | r#"INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at) | 232 | r#"INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at) |
| 226 | VALUES ($1, $2, $3, $4, NULL, $5, $6, $7) | 233 | VALUES ($1, $2, $3, $4, NULL, $5, $6, $7) |
| 227 | - RETURNING id, board, author, kind, payload, count, epoch, created_at"#, | 234 | + RETURNING id AS "id: BoardStrokeId", board AS "board: BoardId", |
| 228 | - BoardStrokeId::generate(), | 235 | + author AS "author: UserId", kind, payload, count, epoch, |
| 229 | - board.clone(), | 236 | + created_at AS "created_at: Timestamp""#, |
| 230 | - by.clone(), | 237 | + BoardStrokeId::generate().uuid(), |
| 238 | + board.uuid(), | ||
| 239 | + by.uuid(), | ||
| 231 | KIND_CLEAR, | 240 | KIND_CLEAR, |
| 232 | epoch_count, | 241 | epoch_count, |
| 233 | epoch, | 242 | epoch, |
| 234 | - Timestamp::now() | 243 | + Timestamp::now().as_millis() |
| 235 | ) | 244 | ) |
| 236 | .fetch_one(&mut *conn) | 245 | .fetch_one(&mut *conn) |
| 237 | .await?; | 246 | .await?; |
| @@ -258,25 +267,29 @@ pub async fn replay_current( | |||
| 258 | match after.map(BoardStrokeId::from_key) { | 267 | match after.map(BoardStrokeId::from_key) { |
| 259 | Some(after) => Ok(sqlx::query_as!( | 268 | Some(after) => Ok(sqlx::query_as!( |
| 260 | BoardStroke, | 269 | BoardStroke, |
| 261 | - r#"SELECT id, board, author, kind, payload, count, epoch, created_at | 270 | + r#"SELECT id AS "id: BoardStrokeId", board AS "board: BoardId", |
| 271 | + author AS "author: UserId", kind, payload, count, epoch, | ||
| 272 | + created_at AS "created_at: Timestamp" | ||
| 262 | FROM board_stroke | 273 | FROM board_stroke |
| 263 | WHERE board = $1 AND epoch = $2 AND kind = $3 AND id > $4 | 274 | WHERE board = $1 AND epoch = $2 AND kind = $3 AND id > $4 |
| 264 | ORDER BY id LIMIT $5"#, | 275 | ORDER BY id LIMIT $5"#, |
| 265 | - board.clone(), | 276 | + board.uuid(), |
| 266 | epoch, | 277 | epoch, |
| 267 | KIND_STROKE, | 278 | KIND_STROKE, |
| 268 | - after, | 279 | + after.uuid(), |
| 269 | chunk | 280 | chunk |
| 270 | ) | 281 | ) |
| 271 | .fetch_all(db) | 282 | .fetch_all(db) |
| 272 | .await?), | 283 | .await?), |
| 273 | None => Ok(sqlx::query_as!( | 284 | None => Ok(sqlx::query_as!( |
| 274 | BoardStroke, | 285 | BoardStroke, |
| 275 | - r#"SELECT id, board, author, kind, payload, count, epoch, created_at | 286 | + r#"SELECT id AS "id: BoardStrokeId", board AS "board: BoardId", |
| 287 | + author AS "author: UserId", kind, payload, count, epoch, | ||
| 288 | + created_at AS "created_at: Timestamp" | ||
| 276 | FROM board_stroke | 289 | FROM board_stroke |
| 277 | WHERE board = $1 AND epoch = $2 AND kind = $3 | 290 | WHERE board = $1 AND epoch = $2 AND kind = $3 |
| 278 | ORDER BY id LIMIT $4"#, | 291 | ORDER BY id LIMIT $4"#, |
| 279 | - board.clone(), | 292 | + board.uuid(), |
| 280 | epoch, | 293 | epoch, |
| 281 | KIND_STROKE, | 294 | KIND_STROKE, |
| 282 | chunk | 295 | chunk |
| @@ -332,9 +345,11 @@ pub async fn history( | |||
| 332 | pub async fn epochs(db: &Database, board: &BoardId) -> Result<Vec<BoardStroke>, AppError> { | 345 | pub async fn epochs(db: &Database, board: &BoardId) -> Result<Vec<BoardStroke>, AppError> { |
| 333 | Ok(sqlx::query_as!( | 346 | Ok(sqlx::query_as!( |
| 334 | BoardStroke, | 347 | BoardStroke, |
| 335 | - r#"SELECT id, board, author, kind, payload, count, epoch, created_at | 348 | + r#"SELECT id AS "id: BoardStrokeId", board AS "board: BoardId", |
| 349 | + author AS "author: UserId", kind, payload, count, epoch, | ||
| 350 | + created_at AS "created_at: Timestamp" | ||
| 336 | FROM board_stroke WHERE board = $1 AND kind = $2 ORDER BY id"#, | 351 | FROM board_stroke WHERE board = $1 AND kind = $2 ORDER BY id"#, |
| 337 | - board.clone(), | 352 | + board.uuid(), |
| 338 | KIND_CLEAR | 353 | KIND_CLEAR |
| 339 | ) | 354 | ) |
| 340 | .fetch_all(db) | 355 | .fetch_all(db) |
src/db/chatbot_thread.rsmodified+6 -6
| @@ -45,7 +45,7 @@ pub async fn create_capped( | |||
| 45 | (SELECT max_chatbot_threads FROM settings WHERE id = 'school'), | 45 | (SELECT max_chatbot_threads FROM settings WHERE id = 'school'), |
| 46 | $2) | 46 | $2) |
| 47 | RETURNING 1) | 47 | RETURNING 1) |
| 48 | - INSERT INTO chatbot_thread (id, user_id, title AS \"title: ChatbotThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\") | 48 | + INSERT INTO chatbot_thread (id, user_id, title, created_at, updated_at) |
| 49 | SELECT $3, $1, $4, $5, $5 | 49 | SELECT $3, $1, $4, $5, $5 |
| 50 | WHERE EXISTS (SELECT 1 FROM seat) | 50 | WHERE EXISTS (SELECT 1 FROM seat) |
| 51 | RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \ | 51 | RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \ |
| @@ -105,8 +105,8 @@ pub async fn read_for( | |||
| 105 | ) -> Result<Option<ChatbotThread>, AppError> { | 105 | ) -> Result<Option<ChatbotThread>, AppError> { |
| 106 | let thread = query_as!( | 106 | let thread = query_as!( |
| 107 | ChatbotThread, | 107 | ChatbotThread, |
| 108 | - "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", | 108 | + "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", |
| 109 | - id | 109 | + id.uuid() |
| 110 | ) | 110 | ) |
| 111 | .fetch_optional(db) | 111 | .fetch_optional(db) |
| 112 | .await?; | 112 | .await?; |
| @@ -159,7 +159,7 @@ pub async fn rename( | |||
| 159 | /// thread. On a re-sent round the thread is already gone, so the caller | 159 | /// thread. On a re-sent round the thread is already gone, so the caller |
| 160 | /// gets the `404` that is the truth. | 160 | /// gets the `404` that is the truth. |
| 161 | pub async fn delete(db: &Database, thread: ChatbotThread) -> Result<ChatbotThread, AppError> { | 161 | pub async fn delete(db: &Database, thread: ChatbotThread) -> Result<ChatbotThread, AppError> { |
| 162 | - tx_with_retry(db, false, async |tx| { | 162 | + tx_with_retry(db, false, async move |tx| { |
| 163 | // Children first: the foreign key would refuse the parent while a | 163 | // Children first: the foreign key would refuse the parent while a |
| 164 | // turn still names it. | 164 | // turn still names it. |
| 165 | sqlx::query!( | 165 | sqlx::query!( |
| @@ -171,7 +171,7 @@ pub async fn delete(db: &Database, thread: ChatbotThread) -> Result<ChatbotThrea | |||
| 171 | let gone = query_as!( | 171 | let gone = query_as!( |
| 172 | ChatbotThread, | 172 | ChatbotThread, |
| 173 | "DELETE FROM chatbot_thread WHERE id = $1 \ | 173 | "DELETE FROM chatbot_thread WHERE id = $1 \ |
| 174 | - RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title, \ | 174 | + RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \ |
| 175 | created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", | 175 | created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", |
| 176 | thread.get_id().uuid() | 176 | thread.get_id().uuid() |
| 177 | ) | 177 | ) |
| @@ -181,7 +181,7 @@ pub async fn delete(db: &Database, thread: ChatbotThread) -> Result<ChatbotThrea | |||
| 181 | sqlx::query!( | 181 | sqlx::query!( |
| 182 | "UPDATE app_user SET chatbot_thread_count = GREATEST(chatbot_thread_count - 1, 0) \ | 182 | "UPDATE app_user SET chatbot_thread_count = GREATEST(chatbot_thread_count - 1, 0) \ |
| 183 | WHERE id = $1", | 183 | WHERE id = $1", |
| 184 | - gone.get_user_id() | 184 | + gone.get_user_id().uuid() |
| 185 | ) | 185 | ) |
| 186 | .execute(&mut *tx) | 186 | .execute(&mut *tx) |
| 187 | .await?; | 187 | .await?; |
src/db/class_blueprint.rsmodified+2 -2
| @@ -94,7 +94,7 @@ pub async fn create( | |||
| 94 | .execute(&mut *tx) | 94 | .execute(&mut *tx) |
| 95 | .await; | 95 | .await; |
| 96 | match inserted { | 96 | match inserted { |
| 97 | - Ok(_) => Ok(blueprint), | 97 | + Ok(_) => Ok(blueprint.clone()), |
| 98 | Err(e) if unique_violation(&e) == Some("class_blueprint_pkey") => Err( | 98 | Err(e) if unique_violation(&e) == Some("class_blueprint_pkey") => Err( |
| 99 | AppError::Conflict("a blueprint already exists for that grade"), | 99 | AppError::Conflict("a blueprint already exists for that grade"), |
| 100 | ), | 100 | ), |
| @@ -166,7 +166,7 @@ pub async fn set_courses_if_unchanged( | |||
| 166 | Ok(updated.map(|row| ClassBlueprint { | 166 | Ok(updated.map(|row| ClassBlueprint { |
| 167 | id: id.clone(), | 167 | id: id.clone(), |
| 168 | grade: row.grade, | 168 | grade: row.grade, |
| 169 | - courses: wanted, | 169 | + courses: wanted.clone(), |
| 170 | creator: row.creator, | 170 | creator: row.creator, |
| 171 | })) | 171 | })) |
| 172 | }) | 172 | }) |
src/db/class_group.rsmodified+23 -13
| @@ -41,13 +41,15 @@ pub async fn create( | |||
| 41 | RETURNING 1) | 41 | RETURNING 1) |
| 42 | INSERT INTO class_group (id, creator, name, grade, term, teacher) | 42 | INSERT INTO class_group (id, creator, name, grade, term, teacher) |
| 43 | SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat) | 43 | SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat) |
| 44 | - RETURNING id, creator, name, grade, term, teacher"#, | 44 | + RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 45 | + name AS "name: ClassName", grade AS "grade: ClassGrade", | ||
| 46 | + term AS "term: TermId", teacher AS "teacher: UserId""#, | ||
| 45 | term.uuid(), | 47 | term.uuid(), |
| 46 | id.uuid(), | 48 | id.uuid(), |
| 47 | creator.uuid(), | 49 | creator.uuid(), |
| 48 | name.as_str(), | 50 | name.as_str(), |
| 49 | - grade.as_deref(), | 51 | + grade.as_ref().map(ClassGrade::as_str), |
| 50 | - teacher.as_ref() | 52 | + teacher.as_ref().map(UserId::uuid) |
| 51 | ) | 53 | ) |
| 52 | .fetch_optional(db) | 54 | .fetch_optional(db) |
| 53 | .await; | 55 | .await; |
| @@ -72,13 +74,15 @@ pub async fn create( | |||
| 72 | ClassGroup, | 74 | ClassGroup, |
| 73 | r#"INSERT INTO class_group (id, creator, name, grade, term, teacher) | 75 | r#"INSERT INTO class_group (id, creator, name, grade, term, teacher) |
| 74 | VALUES ($1, $2, $3, $4, $5, $6) | 76 | VALUES ($1, $2, $3, $4, $5, $6) |
| 75 | - RETURNING id, creator, name, grade, term, teacher"#, | 77 | + RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 78 | + name AS "name: ClassName", grade AS "grade: ClassGrade", | ||
| 79 | + term AS "term: TermId", teacher AS "teacher: UserId""#, | ||
| 76 | id.uuid(), | 80 | id.uuid(), |
| 77 | creator.uuid(), | 81 | creator.uuid(), |
| 78 | name.as_str(), | 82 | name.as_str(), |
| 79 | - grade.as_deref(), | 83 | + grade.as_ref().map(ClassGrade::as_str), |
| 80 | - term.as_ref(), | 84 | + term.as_ref().map(TermId::uuid), |
| 81 | - teacher.as_ref() | 85 | + teacher.as_ref().map(UserId::uuid) |
| 82 | ) | 86 | ) |
| 83 | .fetch_optional(db) | 87 | .fetch_optional(db) |
| 84 | .await?; | 88 | .await?; |
| @@ -91,7 +95,9 @@ pub async fn create( | |||
| 91 | pub async fn read(db: &Database, id: &ClassGroupId) -> Result<Option<ClassGroup>, AppError> { | 95 | pub async fn read(db: &Database, id: &ClassGroupId) -> Result<Option<ClassGroup>, AppError> { |
| 92 | let class = sqlx::query_as!( | 96 | let class = sqlx::query_as!( |
| 93 | ClassGroup, | 97 | ClassGroup, |
| 94 | - r#"SELECT id, creator, name, grade, term, teacher | 98 | + r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 99 | + name AS "name: ClassName", grade AS "grade: ClassGrade", | ||
| 100 | + term AS "term: TermId", teacher AS "teacher: UserId" | ||
| 95 | FROM class_group WHERE id = $1"#, | 101 | FROM class_group WHERE id = $1"#, |
| 96 | id.uuid() | 102 | id.uuid() |
| 97 | ) | 103 | ) |
| @@ -183,12 +189,14 @@ pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result<Vec<Clas | |||
| 183 | if ids.is_empty() { | 189 | if ids.is_empty() { |
| 184 | return Ok(Vec::new()); | 190 | return Ok(Vec::new()); |
| 185 | } | 191 | } |
| 186 | - let ids: Vec<ClassGroupId> = ids.to_vec(); | 192 | + let ids: Vec<uuid::Uuid> = ids.iter().map(ClassGroupId::uuid).collect(); |
| 187 | let classes = sqlx::query_as!( | 193 | let classes = sqlx::query_as!( |
| 188 | ClassGroup, | 194 | ClassGroup, |
| 189 | - r#"SELECT id, creator, name, grade, term, teacher | 195 | + r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 196 | + name AS "name: ClassName", grade AS "grade: ClassGrade", | ||
| 197 | + term AS "term: TermId", teacher AS "teacher: UserId" | ||
| 190 | FROM class_group WHERE id = ANY($1)"#, | 198 | FROM class_group WHERE id = ANY($1)"#, |
| 191 | - ids as _ | 199 | + &ids |
| 192 | ) | 200 | ) |
| 193 | .fetch_all(db) | 201 | .fetch_all(db) |
| 194 | .await?; | 202 | .await?; |
| @@ -204,7 +212,9 @@ pub async fn list_for_grade( | |||
| 204 | ) -> Result<Vec<ClassGroup>, AppError> { | 212 | ) -> Result<Vec<ClassGroup>, AppError> { |
| 205 | let classes = sqlx::query_as!( | 213 | let classes = sqlx::query_as!( |
| 206 | ClassGroup, | 214 | ClassGroup, |
| 207 | - r#"SELECT id, creator, name, grade, term, teacher | 215 | + r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 216 | + name AS "name: ClassName", grade AS "grade: ClassGrade", | ||
| 217 | + term AS "term: TermId", teacher AS "teacher: UserId" | ||
| 208 | FROM class_group WHERE grade = $1"#, | 218 | FROM class_group WHERE grade = $1"#, |
| 209 | grade.as_str() | 219 | grade.as_str() |
| 210 | ) | 220 | ) |
| @@ -243,7 +253,7 @@ pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError> | |||
| 243 | r#"DELETE FROM class_group | 253 | r#"DELETE FROM class_group |
| 244 | WHERE id = $1 | 254 | WHERE id = $1 |
| 245 | AND class_member_count = 0 AND class_course_count = 0 | 255 | AND class_member_count = 0 AND class_course_count = 0 |
| 246 | - RETURNING term AS "term: Option<uuid::Uuid>""#, | 256 | + RETURNING term AS "term: uuid::Uuid""#, |
| 247 | class.id.uuid() | 257 | class.id.uuid() |
| 248 | ) | 258 | ) |
| 249 | .fetch_optional(&mut *tx) | 259 | .fetch_optional(&mut *tx) |
src/db/class_pump.rsmodified+39 -54
| @@ -277,7 +277,7 @@ async fn early_verdicts( | |||
| 277 | class as _, | 277 | class as _, |
| 278 | user as _ | 278 | user as _ |
| 279 | ) | 279 | ) |
| 280 | - .fetch_optional(tx) | 280 | + .fetch_optional(&mut *tx) |
| 281 | .await? | 281 | .await? |
| 282 | .is_some(), | 282 | .is_some(), |
| 283 | Pivot::Course(course) => sqlx::query_scalar!( | 283 | Pivot::Course(course) => sqlx::query_scalar!( |
| @@ -285,7 +285,7 @@ async fn early_verdicts( | |||
| 285 | class as _, | 285 | class as _, |
| 286 | course as _ | 286 | course as _ |
| 287 | ) | 287 | ) |
| 288 | - .fetch_optional(tx) | 288 | + .fetch_optional(&mut *tx) |
| 289 | .await? | 289 | .await? |
| 290 | .is_some(), | 290 | .is_some(), |
| 291 | }; | 291 | }; |
| @@ -297,7 +297,7 @@ async fn early_verdicts( | |||
| 297 | r#"SELECT 1 AS "one" FROM class_blueprint WHERE grade = $1 FOR KEY SHARE"#, | 297 | r#"SELECT 1 AS "one" FROM class_blueprint WHERE grade = $1 FOR KEY SHARE"#, |
| 298 | source as _ | 298 | source as _ |
| 299 | ) | 299 | ) |
| 300 | - .fetch_optional(tx) | 300 | + .fetch_optional(&mut *tx) |
| 301 | .await? | 301 | .await? |
| 302 | .is_some(); | 302 | .is_some(); |
| 303 | if !alive { | 303 | if !alive { |
| @@ -310,7 +310,7 @@ async fn early_verdicts( | |||
| 310 | r#"SELECT role AS "role: Role" FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#, | 310 | r#"SELECT role AS "role: Role" FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#, |
| 311 | user as _ | 311 | user as _ |
| 312 | ) | 312 | ) |
| 313 | - .fetch_optional(tx) | 313 | + .fetch_optional(&mut *tx) |
| 314 | .await?; | 314 | .await?; |
| 315 | if row.map(|row| row.role) != Some(Role::Student) { | 315 | if row.map(|row| row.role) != Some(Role::Student) { |
| 316 | return Ok(Some(Early::PivotGone)); | 316 | return Ok(Some(Early::PivotGone)); |
| @@ -321,7 +321,7 @@ async fn early_verdicts( | |||
| 321 | r#"SELECT 1 AS "one" FROM course WHERE id = $1 FOR KEY SHARE"#, | 321 | r#"SELECT 1 AS "one" FROM course WHERE id = $1 FOR KEY SHARE"#, |
| 322 | course as _ | 322 | course as _ |
| 323 | ) | 323 | ) |
| 324 | - .fetch_optional(tx) | 324 | + .fetch_optional(&mut *tx) |
| 325 | .await? | 325 | .await? |
| 326 | .is_some(); | 326 | .is_some(); |
| 327 | if !alive { | 327 | if !alive { |
| @@ -338,7 +338,7 @@ async fn early_verdicts( | |||
| 338 | class as _, | 338 | class as _, |
| 339 | Axis::Member.cap(), | 339 | Axis::Member.cap(), |
| 340 | ) | 340 | ) |
| 341 | - .fetch_optional(tx) | 341 | + .fetch_optional(&mut *tx) |
| 342 | .await? | 342 | .await? |
| 343 | .is_some(), | 343 | .is_some(), |
| 344 | Axis::Course => sqlx::query_scalar!( | 344 | Axis::Course => sqlx::query_scalar!( |
| @@ -347,7 +347,7 @@ async fn early_verdicts( | |||
| 347 | class as _, | 347 | class as _, |
| 348 | Axis::Course.cap(), | 348 | Axis::Course.cap(), |
| 349 | ) | 349 | ) |
| 350 | - .fetch_optional(tx) | 350 | + .fetch_optional(&mut *tx) |
| 351 | .await? | 351 | .await? |
| 352 | .is_some(), | 352 | .is_some(), |
| 353 | }; | 353 | }; |
| @@ -386,7 +386,7 @@ pub(crate) async fn add_member( | |||
| 386 | // The claim and the link are one statement (the cap recipe's CTE): the | 386 | // The claim and the link are one statement (the cap recipe's CTE): the |
| 387 | // conditional `UPDATE` on the class row gates the `INSERT`, so a full | 387 | // conditional `UPDATE` on the class row gates the `INSERT`, so a full |
| 388 | // or gone class writes nothing at all. | 388 | // or gone class writes nothing at all. |
| 389 | - let inserted = match sqlx::query_scalar!( | 389 | + let inserted = match sqlx::query!( |
| 390 | r#"WITH seat AS ( | 390 | r#"WITH seat AS ( |
| 391 | UPDATE class_group SET class_member_count = class_member_count + 1 | 391 | UPDATE class_group SET class_member_count = class_member_count + 1 |
| 392 | WHERE id = $1 AND class_member_count < $2 | 392 | WHERE id = $1 AND class_member_count < $2 |
| @@ -400,7 +400,7 @@ pub(crate) async fn add_member( | |||
| 400 | by as _, | 400 | by as _, |
| 401 | added_at as _ | 401 | added_at as _ |
| 402 | ) | 402 | ) |
| 403 | - .execute(tx) | 403 | + .execute(&mut *tx) |
| 404 | .await | 404 | .await |
| 405 | { | 405 | { |
| 406 | Ok(result) => result, | 406 | Ok(result) => result, |
| @@ -435,10 +435,7 @@ pub(crate) async fn add_member( | |||
| 435 | class as _ | 435 | class as _ |
| 436 | ) | 436 | ) |
| 437 | .fetch_all(&mut *tx) | 437 | .fetch_all(&mut *tx) |
| 438 | - .await? | 438 | + .await?; |
| 439 | - .into_iter() | ||
| 440 | - .map(|row| row.course) | ||
| 441 | - .collect(); | ||
| 442 | let pairs = courses.into_iter().map(|course| (course, user.uuid())); | 439 | let pairs = courses.into_iter().map(|course| (course, user.uuid())); |
| 443 | match enroll_pairs(tx, class, pairs, by).await? { | 440 | match enroll_pairs(tx, class, pairs, by).await? { |
| 444 | Sweep::Done => {} | 441 | Sweep::Done => {} |
| @@ -481,7 +478,7 @@ pub(crate) async fn attach_course( | |||
| 481 | { | 478 | { |
| 482 | return Ok(refusal_of(early)); | 479 | return Ok(refusal_of(early)); |
| 483 | } | 480 | } |
| 484 | - let inserted = match sqlx::query_scalar!( | 481 | + let inserted = match sqlx::query!( |
| 485 | r#"WITH seat AS ( | 482 | r#"WITH seat AS ( |
| 486 | UPDATE class_group SET class_course_count = class_course_count + 1 | 483 | UPDATE class_group SET class_course_count = class_course_count + 1 |
| 487 | WHERE id = $1 AND class_course_count < $2 | 484 | WHERE id = $1 AND class_course_count < $2 |
| @@ -496,7 +493,7 @@ pub(crate) async fn attach_course( | |||
| 496 | attached_at as _, | 493 | attached_at as _, |
| 497 | source as _ | 494 | source as _ |
| 498 | ) | 495 | ) |
| 499 | - .execute(tx) | 496 | + .execute(&mut *tx) |
| 500 | .await | 497 | .await |
| 501 | { | 498 | { |
| 502 | Ok(result) => result, | 499 | Ok(result) => result, |
| @@ -525,10 +522,7 @@ pub(crate) async fn attach_course( | |||
| 525 | class as _ | 522 | class as _ |
| 526 | ) | 523 | ) |
| 527 | .fetch_all(&mut *tx) | 524 | .fetch_all(&mut *tx) |
| 528 | - .await? | 525 | + .await?; |
| 529 | - .into_iter() | ||
| 530 | - .map(|row| row.app_user) | ||
| 531 | - .collect(); | ||
| 532 | let pairs = members.into_iter().map(|user| (course.uuid(), user)); | 526 | let pairs = members.into_iter().map(|user| (course.uuid(), user)); |
| 533 | match enroll_pairs(tx, class, pairs, by).await? { | 527 | match enroll_pairs(tx, class, pairs, by).await? { |
| 534 | Sweep::Done => {} | 528 | Sweep::Done => {} |
| @@ -707,7 +701,7 @@ pub(crate) async fn remove_member( | |||
| 707 | class as _, | 701 | class as _, |
| 708 | user as _ | 702 | user as _ |
| 709 | ) | 703 | ) |
| 710 | - .fetch_optional(tx) | 704 | + .fetch_optional(&mut *tx) |
| 711 | .await?; | 705 | .await?; |
| 712 | let Some(_) = gone else { | 706 | let Some(_) = gone else { |
| 713 | return Ok(0); | 707 | return Ok(0); |
| @@ -720,22 +714,18 @@ pub(crate) async fn remove_member( | |||
| 720 | ) | 714 | ) |
| 721 | .execute(&mut *tx) | 715 | .execute(&mut *tx) |
| 722 | .await?; | 716 | .await?; |
| 723 | - sweep_enrollments( | 717 | + let rows = sqlx::query!( |
| 724 | - tx, | 718 | + r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid" |
| 725 | - class, | 719 | + FROM enrollment WHERE app_user = $1 AND source = $2"#, |
| 726 | - sqlx::query!( | 720 | + user as _, |
| 727 | - r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid" | 721 | + class as _ |
| 728 | - FROM enrollment WHERE app_user = $1 AND source = $2"#, | ||
| 729 | - user as _, | ||
| 730 | - class as _ | ||
| 731 | - ) | ||
| 732 | - .fetch_all(&mut *tx) | ||
| 733 | - .await? | ||
| 734 | - .into_iter() | ||
| 735 | - .map(|row| (row.course, row.app_user)) | ||
| 736 | - .collect::<Vec<_>>(), | ||
| 737 | ) | 722 | ) |
| 738 | - .await?; | 723 | + .fetch_all(&mut *tx) |
| 724 | + .await? | ||
| 725 | + .into_iter() | ||
| 726 | + .map(|row| (row.course, row.app_user)) | ||
| 727 | + .collect::<Vec<_>>(); | ||
| 728 | + sweep_enrollments(tx, class, rows).await?; | ||
| 739 | Ok(1) | 729 | Ok(1) |
| 740 | }) | 730 | }) |
| 741 | .await | 731 | .await |
| @@ -763,7 +753,7 @@ pub(crate) async fn detach_course( | |||
| 763 | course as _, | 753 | course as _, |
| 764 | source as _ | 754 | source as _ |
| 765 | ) | 755 | ) |
| 766 | - .fetch_optional(tx) | 756 | + .fetch_optional(&mut *tx) |
| 767 | .await? | 757 | .await? |
| 768 | } | 758 | } |
| 769 | None => { | 759 | None => { |
| @@ -773,7 +763,7 @@ pub(crate) async fn detach_course( | |||
| 773 | class as _, | 763 | class as _, |
| 774 | course as _ | 764 | course as _ |
| 775 | ) | 765 | ) |
| 776 | - .fetch_optional(tx) | 766 | + .fetch_optional(&mut *tx) |
| 777 | .await? | 767 | .await? |
| 778 | } | 768 | } |
| 779 | }; | 769 | }; |
| @@ -788,22 +778,18 @@ pub(crate) async fn detach_course( | |||
| 788 | ) | 778 | ) |
| 789 | .execute(&mut *tx) | 779 | .execute(&mut *tx) |
| 790 | .await?; | 780 | .await?; |
| 791 | - sweep_enrollments( | 781 | + let rows = sqlx::query!( |
| 792 | - tx, | 782 | + r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid" |
| 793 | - class, | 783 | + FROM enrollment WHERE course = $1 AND source = $2"#, |
| 794 | - sqlx::query!( | 784 | + course as _, |
| 795 | - r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid" | 785 | + class as _ |
| 796 | - FROM enrollment WHERE course = $1 AND source = $2"#, | ||
| 797 | - course as _, | ||
| 798 | - class as _ | ||
| 799 | - ) | ||
| 800 | - .fetch_all(&mut *tx) | ||
| 801 | - .await? | ||
| 802 | - .into_iter() | ||
| 803 | - .map(|row| (row.course, row.app_user)) | ||
| 804 | - .collect::<Vec<_>>(), | ||
| 805 | ) | 786 | ) |
| 806 | - .await?; | 787 | + .fetch_all(&mut *tx) |
| 788 | + .await? | ||
| 789 | + .into_iter() | ||
| 790 | + .map(|row| (row.course, row.app_user)) | ||
| 791 | + .collect::<Vec<_>>(); | ||
| 792 | + sweep_enrollments(tx, class, rows).await?; | ||
| 807 | Ok(1) | 793 | Ok(1) |
| 808 | }) | 794 | }) |
| 809 | .await | 795 | .await |
| @@ -838,8 +824,7 @@ async fn sweep_enrollments( | |||
| 838 | class as _ | 824 | class as _ |
| 839 | ) | 825 | ) |
| 840 | .fetch_optional(&mut *tx) | 826 | .fetch_optional(&mut *tx) |
| 841 | - .await? | 827 | + .await?; |
| 842 | - .map(|row| row.class); | ||
| 843 | let Some(heir) = heir else { | 828 | let Some(heir) = heir else { |
| 844 | release(tx, course, user).await?; | 829 | release(tx, course, user).await?; |
| 845 | continue; | 830 | continue; |
src/db/course.rsmodified+108 -69
| @@ -27,13 +27,16 @@ pub async fn create( | |||
| 27 | Course, | 27 | Course, |
| 28 | r#"INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity) | 28 | r#"INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity) |
| 29 | VALUES ($1, $2, $3, $4, $5, $6, NULL, $7) | 29 | VALUES ($1, $2, $3, $4, $5, $6, NULL, $7) |
| 30 | - RETURNING id, creator, teachers, title, description, kind, term, capacity"#, | 30 | + RETURNING id AS "id: CourseId", creator AS "creator: UserId", |
| 31 | - id, | 31 | + teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle", |
| 32 | - creator, | 32 | + description AS "description: CourseDescription", |
| 33 | - Vec::<UserId>::new(), | 33 | + kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, |
| 34 | - title, | 34 | + id.uuid(), |
| 35 | - description, | 35 | + creator.uuid(), |
| 36 | - kind, | 36 | + &Vec::<uuid::Uuid>::new(), |
| 37 | + title.as_str(), | ||
| 38 | + description.as_str(), | ||
| 39 | + kind.as_str(), | ||
| 37 | capacity, | 40 | capacity, |
| 38 | ) | 41 | ) |
| 39 | .fetch_one(db) | 42 | .fetch_one(db) |
| @@ -55,15 +58,18 @@ pub async fn create( | |||
| 55 | RETURNING 1) | 58 | RETURNING 1) |
| 56 | INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity) | 59 | INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity) |
| 57 | SELECT $1, $2, $3, $4, $5, $6, $8, $7 WHERE EXISTS (SELECT 1 FROM seat) | 60 | SELECT $1, $2, $3, $4, $5, $6, $8, $7 WHERE EXISTS (SELECT 1 FROM seat) |
| 58 | - RETURNING id, creator, teachers, title, description, kind, term, capacity"#, | 61 | + RETURNING id AS "id: CourseId", creator AS "creator: UserId", |
| 59 | - id, | 62 | + teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle", |
| 60 | - creator, | 63 | + description AS "description: CourseDescription", |
| 61 | - Vec::<UserId>::new(), | 64 | + kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, |
| 62 | - title, | 65 | + id.uuid(), |
| 63 | - description, | 66 | + creator.uuid(), |
| 64 | - kind, | 67 | + &Vec::<uuid::Uuid>::new(), |
| 68 | + title.as_str(), | ||
| 69 | + description.as_str(), | ||
| 70 | + kind.as_str(), | ||
| 65 | capacity, | 71 | capacity, |
| 66 | - term, | 72 | + term.uuid(), |
| 67 | cap::UNLIMITED, | 73 | cap::UNLIMITED, |
| 68 | ) | 74 | ) |
| 69 | .fetch_one(db) | 75 | .fetch_one(db) |
| @@ -84,9 +90,12 @@ pub async fn create( | |||
| 84 | pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> { | 90 | pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> { |
| 85 | let course = sqlx::query_as!( | 91 | let course = sqlx::query_as!( |
| 86 | Course, | 92 | Course, |
| 87 | - r#"SELECT id, creator, teachers, title, description, kind, term, capacity | 93 | + r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", |
| 94 | + teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle", | ||
| 95 | + description AS "description: CourseDescription", | ||
| 96 | + kind AS "kind: CourseKind", term AS "term: TermId", capacity | ||
| 88 | FROM course WHERE id = $1"#, | 97 | FROM course WHERE id = $1"#, |
| 89 | - id, | 98 | + id.uuid(), |
| 90 | ) | 99 | ) |
| 91 | .fetch_optional(db) | 100 | .fetch_optional(db) |
| 92 | .await?; | 101 | .await?; |
| @@ -96,7 +105,10 @@ pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppErr | |||
| 96 | pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> { | 105 | pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> { |
| 97 | let rows = sqlx::query_as!( | 106 | let rows = sqlx::query_as!( |
| 98 | Course, | 107 | Course, |
| 99 | - r#"SELECT id, creator, teachers, title, description, kind, term, capacity | 108 | + r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", |
| 109 | + teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle", | ||
| 110 | + description AS "description: CourseDescription", | ||
| 111 | + kind AS "kind: CourseKind", term AS "term: TermId", capacity | ||
| 100 | FROM course ORDER BY id DESC"#, | 112 | FROM course ORDER BY id DESC"#, |
| 101 | ) | 113 | ) |
| 102 | .fetch_all(db) | 114 | .fetch_all(db) |
| @@ -137,10 +149,13 @@ pub async fn list_enrolled( | |||
| 137 | pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> { | 149 | pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> { |
| 138 | let rows = sqlx::query_as!( | 150 | let rows = sqlx::query_as!( |
| 139 | Course, | 151 | Course, |
| 140 | - r#"SELECT id, creator, teachers, title, description, kind, term, capacity | 152 | + r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", |
| 153 | + teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle", | ||
| 154 | + description AS "description: CourseDescription", | ||
| 155 | + kind AS "kind: CourseKind", term AS "term: TermId", capacity | ||
| 141 | FROM course WHERE creator = $1 OR $2 = ANY(teachers) ORDER BY id DESC"#, | 156 | FROM course WHERE creator = $1 OR $2 = ANY(teachers) ORDER BY id DESC"#, |
| 142 | - user, | 157 | + user.uuid(), |
| 143 | - user, | 158 | + user.uuid(), |
| 144 | ) | 159 | ) |
| 145 | .fetch_all(db) | 160 | .fetch_all(db) |
| 146 | .await?; | 161 | .await?; |
| @@ -153,12 +168,15 @@ pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result<Vec<Course>, | |||
| 153 | if ids.is_empty() { | 168 | if ids.is_empty() { |
| 154 | return Ok(Vec::new()); | 169 | return Ok(Vec::new()); |
| 155 | } | 170 | } |
| 156 | - let keys: Vec<CourseId> = ids.to_vec(); | 171 | + let keys: Vec<uuid::Uuid> = ids.iter().map(CourseId::uuid).collect(); |
| 157 | let rows = sqlx::query_as!( | 172 | let rows = sqlx::query_as!( |
| 158 | Course, | 173 | Course, |
| 159 | - r#"SELECT id, creator, teachers, title, description, kind, term, capacity | 174 | + r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", |
| 175 | + teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle", | ||
| 176 | + description AS "description: CourseDescription", | ||
| 177 | + kind AS "kind: CourseKind", term AS "term: TermId", capacity | ||
| 160 | FROM course WHERE id = ANY($1)"#, | 178 | FROM course WHERE id = ANY($1)"#, |
| 161 | - keys, | 179 | + &keys, |
| 162 | ) | 180 | ) |
| 163 | .fetch_all(db) | 181 | .fetch_all(db) |
| 164 | .await?; | 182 | .await?; |
| @@ -235,11 +253,14 @@ pub async fn assign_teacher( | |||
| 235 | Course, | 253 | Course, |
| 236 | r#"UPDATE course | 254 | r#"UPDATE course |
| 237 | SET teachers = (SELECT array_agg(DISTINCT x) | 255 | SET teachers = (SELECT array_agg(DISTINCT x) |
| 238 | - FROM unnest(course.teachers || $2) AS x) | 256 | + FROM unnest(course.teachers || $2::uuid) AS x) |
| 239 | WHERE id = $1 | 257 | WHERE id = $1 |
| 240 | - RETURNING id, creator, teachers, title, description, kind, term, capacity"#, | 258 | + RETURNING id AS "id: CourseId", creator AS "creator: UserId", |
| 241 | - course.id, | 259 | + teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle", |
| 242 | - teacher, | 260 | + description AS "description: CourseDescription", |
| 261 | + kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, | ||
| 262 | + course.id.uuid(), | ||
| 263 | + teacher.uuid(), | ||
| 243 | ) | 264 | ) |
| 244 | .fetch_optional(db) | 265 | .fetch_optional(db) |
| 245 | .await?; | 266 | .await?; |
| @@ -263,9 +284,12 @@ pub async fn unassign_teacher( | |||
| 263 | Course, | 284 | Course, |
| 264 | r#"UPDATE course SET teachers = array_remove(teachers, $2) | 285 | r#"UPDATE course SET teachers = array_remove(teachers, $2) |
| 265 | WHERE id = $1 | 286 | WHERE id = $1 |
| 266 | - RETURNING id, creator, teachers, title, description, kind, term, capacity"#, | 287 | + RETURNING id AS "id: CourseId", creator AS "creator: UserId", |
| 267 | - course.id, | 288 | + teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle", |
| 268 | - teacher, | 289 | + description AS "description: CourseDescription", |
| 290 | + kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, | ||
| 291 | + course.id.uuid(), | ||
| 292 | + teacher.uuid(), | ||
| 269 | ) | 293 | ) |
| 270 | .fetch_optional(db) | 294 | .fetch_optional(db) |
| 271 | .await?; | 295 | .await?; |
| @@ -278,7 +302,7 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App | |||
| 278 | sqlx::query!( | 302 | sqlx::query!( |
| 279 | r#"UPDATE course SET teachers = array_remove(teachers, $1) | 303 | r#"UPDATE course SET teachers = array_remove(teachers, $1) |
| 280 | WHERE $1 = ANY(teachers)"#, | 304 | WHERE $1 = ANY(teachers)"#, |
| 281 | - user, | 305 | + user.uuid(), |
| 282 | ) | 306 | ) |
| 283 | .execute(db) | 307 | .execute(db) |
| 284 | .await?; | 308 | .await?; |
| @@ -352,7 +376,7 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> { | |||
| 352 | // this very row, so check and cascade are one decision. | 376 | // this very row, so check and cascade are one decision. |
| 353 | let guard = sqlx::query!( | 377 | let guard = sqlx::query!( |
| 354 | r#"SELECT enrollment_count, term FROM course WHERE id = $1 FOR UPDATE"#, | 378 | r#"SELECT enrollment_count, term FROM course WHERE id = $1 FOR UPDATE"#, |
| 355 | - course.id, | 379 | + course.id.uuid(), |
| 356 | ) | 380 | ) |
| 357 | .fetch_optional(&mut *tx) | 381 | .fetch_optional(&mut *tx) |
| 358 | .await?; | 382 | .await?; |
| @@ -366,7 +390,7 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> { | |||
| 366 | // source_exam clear — and must be collected before the sweeps take | 390 | // source_exam clear — and must be collected before the sweeps take |
| 367 | // the rows they name. | 391 | // the rows they name. |
| 368 | let exams: Vec<uuid::Uuid> = | 392 | let exams: Vec<uuid::Uuid> = |
| 369 | - sqlx::query!(r#"SELECT id FROM exam WHERE course = $1"#, course.id,) | 393 | + sqlx::query!(r#"SELECT id FROM exam WHERE course = $1"#, course.id.uuid(),) |
| 370 | .fetch_all(&mut *tx) | 394 | .fetch_all(&mut *tx) |
| 371 | .await? | 395 | .await? |
| 372 | .into_iter() | 396 | .into_iter() |
| @@ -382,7 +406,7 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> { | |||
| 382 | JOIN exam e ON r.exam = e.id | 406 | JOIN exam e ON r.exam = e.id |
| 383 | WHERE r.exam = ANY($1) GROUP BY e.kind) s | 407 | WHERE r.exam = ANY($1) GROUP BY e.kind) s |
| 384 | WHERE k.name = s.kind"#, | 408 | WHERE k.name = s.kind"#, |
| 385 | - exams, | 409 | + &exams, |
| 386 | ) | 410 | ) |
| 387 | .execute(&mut *tx) | 411 | .execute(&mut *tx) |
| 388 | .await?; | 412 | .await?; |
| @@ -399,27 +423,27 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> { | |||
| 399 | // Events aimed at this course keep standing, audience cleared. | 423 | // Events aimed at this course keep standing, audience cleared. |
| 400 | sqlx::query!( | 424 | sqlx::query!( |
| 401 | r#"UPDATE event SET audience_course = NULL WHERE audience_course = $1"#, | 425 | r#"UPDATE event SET audience_course = NULL WHERE audience_course = $1"#, |
| 402 | - course.id, | 426 | + course.id.uuid(), |
| 403 | ) | 427 | ) |
| 404 | .execute(&mut *tx) | 428 | .execute(&mut *tx) |
| 405 | .await?; | 429 | .await?; |
| 406 | // The exam subtree, deepest children first. | 430 | // The exam subtree, deepest children first. |
| 407 | - sqlx::query!(r#"DELETE FROM exam_result WHERE exam = ANY($1)"#, exams) | 431 | + sqlx::query!(r#"DELETE FROM exam_result WHERE exam = ANY($1)"#, &exams) |
| 408 | .execute(&mut *tx) | 432 | .execute(&mut *tx) |
| 409 | .await?; | 433 | .await?; |
| 410 | - sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = ANY($1)"#, exams) | 434 | + sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = ANY($1)"#, &exams) |
| 411 | .execute(&mut *tx) | 435 | .execute(&mut *tx) |
| 412 | .await?; | 436 | .await?; |
| 413 | - sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = ANY($1)"#, exams) | 437 | + sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = ANY($1)"#, &exams) |
| 414 | .execute(&mut *tx) | 438 | .execute(&mut *tx) |
| 415 | .await?; | 439 | .await?; |
| 416 | - sqlx::query!(r#"DELETE FROM answer_image WHERE exam = ANY($1)"#, exams) | 440 | + sqlx::query!(r#"DELETE FROM answer_image WHERE exam = ANY($1)"#, &exams) |
| 417 | .execute(&mut *tx) | 441 | .execute(&mut *tx) |
| 418 | .await?; | 442 | .await?; |
| 419 | - sqlx::query!(r#"DELETE FROM question_image WHERE exam = ANY($1)"#, exams) | 443 | + sqlx::query!(r#"DELETE FROM question_image WHERE exam = ANY($1)"#, &exams) |
| 420 | .execute(&mut *tx) | 444 | .execute(&mut *tx) |
| 421 | .await?; | 445 | .await?; |
| 422 | - sqlx::query!(r#"DELETE FROM exam_question WHERE exam = ANY($1)"#, exams) | 446 | + sqlx::query!(r#"DELETE FROM exam_question WHERE exam = ANY($1)"#, &exams) |
| 423 | .execute(&mut *tx) | 447 | .execute(&mut *tx) |
| 424 | .await?; | 448 | .await?; |
| 425 | // The homework subtree: files, then submissions (whose graded_by | 449 | // The homework subtree: files, then submissions (whose graded_by |
| @@ -428,39 +452,45 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> { | |||
| 428 | r#"DELETE FROM homework_file WHERE submission IN ( | 452 | r#"DELETE FROM homework_file WHERE submission IN ( |
| 429 | SELECT id FROM homework_submission | 453 | SELECT id FROM homework_submission |
| 430 | WHERE homework IN (SELECT id FROM homework WHERE course = $1))"#, | 454 | WHERE homework IN (SELECT id FROM homework WHERE course = $1))"#, |
| 431 | - course.id, | 455 | + course.id.uuid(), |
| 432 | ) | 456 | ) |
| 433 | .execute(&mut *tx) | 457 | .execute(&mut *tx) |
| 434 | .await?; | 458 | .await?; |
| 435 | sqlx::query!( | 459 | sqlx::query!( |
| 436 | r#"DELETE FROM homework_submission WHERE homework IN ( | 460 | r#"DELETE FROM homework_submission WHERE homework IN ( |
| 437 | SELECT id FROM homework WHERE course = $1)"#, | 461 | SELECT id FROM homework WHERE course = $1)"#, |
| 438 | - course.id, | 462 | + course.id.uuid(), |
| 439 | ) | 463 | ) |
| 440 | .execute(&mut *tx) | 464 | .execute(&mut *tx) |
| 441 | .await?; | 465 | .await?; |
| 442 | sqlx::query!( | 466 | sqlx::query!( |
| 443 | r#"DELETE FROM homework_result WHERE homework IN ( | 467 | r#"DELETE FROM homework_result WHERE homework IN ( |
| 444 | SELECT id FROM homework WHERE course = $1)"#, | 468 | SELECT id FROM homework WHERE course = $1)"#, |
| 445 | - course.id, | 469 | + course.id.uuid(), |
| 446 | ) | 470 | ) |
| 447 | .execute(&mut *tx) | 471 | .execute(&mut *tx) |
| 448 | .await?; | 472 | .await?; |
| 449 | // Derived AI rows for this course's notes. | 473 | // Derived AI rows for this course's notes. |
| 450 | - sqlx::query!(r#"DELETE FROM rag_output WHERE course = $1"#, course.id) | 474 | + sqlx::query!( |
| 451 | - .execute(&mut *tx) | 475 | + r#"DELETE FROM rag_output WHERE course = $1"#, |
| 452 | - .await?; | 476 | + course.id.uuid() |
| 477 | + ) | ||
| 478 | + .execute(&mut *tx) | ||
| 479 | + .await?; | ||
| 453 | // Notes: files before their notes. | 480 | // Notes: files before their notes. |
| 454 | sqlx::query!( | 481 | sqlx::query!( |
| 455 | r#"DELETE FROM course_note_file WHERE course_note IN ( | 482 | r#"DELETE FROM course_note_file WHERE course_note IN ( |
| 456 | SELECT id FROM course_note WHERE course = $1)"#, | 483 | SELECT id FROM course_note WHERE course = $1)"#, |
| 457 | - course.id, | 484 | + course.id.uuid(), |
| 485 | + ) | ||
| 486 | + .execute(&mut *tx) | ||
| 487 | + .await?; | ||
| 488 | + sqlx::query!( | ||
| 489 | + r#"DELETE FROM course_note WHERE course = $1"#, | ||
| 490 | + course.id.uuid() | ||
| 458 | ) | 491 | ) |
| 459 | .execute(&mut *tx) | 492 | .execute(&mut *tx) |
| 460 | .await?; | 493 | .await?; |
| 461 | - sqlx::query!(r#"DELETE FROM course_note WHERE course = $1"#, course.id) | ||
| 462 | - .execute(&mut *tx) | ||
| 463 | - .await?; | ||
| 464 | // Class attachments: detach and hand each class its count back in | 494 | // Class attachments: detach and hand each class its count back in |
| 465 | // one statement, then strike the course out of every blueprint. | 495 | // one statement, then strike the course out of every blueprint. |
| 466 | sqlx::query!( | 496 | sqlx::query!( |
| @@ -469,58 +499,67 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> { | |||
| 469 | UPDATE class_group g | 499 | UPDATE class_group g |
| 470 | SET class_course_count = GREATEST(g.class_course_count - 1, 0) | 500 | SET class_course_count = GREATEST(g.class_course_count - 1, 0) |
| 471 | FROM detached WHERE g.id = detached.class"#, | 501 | FROM detached WHERE g.id = detached.class"#, |
| 472 | - course.id, | 502 | + course.id.uuid(), |
| 473 | ) | 503 | ) |
| 474 | .execute(&mut *tx) | 504 | .execute(&mut *tx) |
| 475 | .await?; | 505 | .await?; |
| 476 | sqlx::query!( | 506 | sqlx::query!( |
| 477 | r#"UPDATE class_blueprint SET courses = array_remove(courses, $1) | 507 | r#"UPDATE class_blueprint SET courses = array_remove(courses, $1) |
| 478 | WHERE $1 = ANY(courses)"#, | 508 | WHERE $1 = ANY(courses)"#, |
| 479 | - course.id, | 509 | + course.id.uuid(), |
| 480 | ) | 510 | ) |
| 481 | .execute(&mut *tx) | 511 | .execute(&mut *tx) |
| 482 | .await?; | 512 | .await?; |
| 483 | // Sessions with their roll call, then the roster itself. | 513 | // Sessions with their roll call, then the roster itself. |
| 484 | sqlx::query!( | 514 | sqlx::query!( |
| 485 | r#"DELETE FROM session_attendance WHERE course = $1"#, | 515 | r#"DELETE FROM session_attendance WHERE course = $1"#, |
| 486 | - course.id, | 516 | + course.id.uuid(), |
| 517 | + ) | ||
| 518 | + .execute(&mut *tx) | ||
| 519 | + .await?; | ||
| 520 | + sqlx::query!( | ||
| 521 | + r#"DELETE FROM course_session WHERE course = $1"#, | ||
| 522 | + course.id.uuid() | ||
| 523 | + ) | ||
| 524 | + .execute(&mut *tx) | ||
| 525 | + .await?; | ||
| 526 | + sqlx::query!( | ||
| 527 | + r#"DELETE FROM enrollment WHERE course = $1"#, | ||
| 528 | + course.id.uuid() | ||
| 487 | ) | 529 | ) |
| 488 | .execute(&mut *tx) | 530 | .execute(&mut *tx) |
| 489 | .await?; | 531 | .await?; |
| 490 | - sqlx::query!(r#"DELETE FROM course_session WHERE course = $1"#, course.id) | ||
| 491 | - .execute(&mut *tx) | ||
| 492 | - .await?; | ||
| 493 | - sqlx::query!(r#"DELETE FROM enrollment WHERE course = $1"#, course.id) | ||
| 494 | - .execute(&mut *tx) | ||
| 495 | - .await?; | ||
| 496 | // The bank keeps its templates; their links to this course's | 532 | // The bank keeps its templates; their links to this course's |
| 497 | // content go first, so the subject/exam deletes below cannot trip | 533 | // content go first, so the subject/exam deletes below cannot trip |
| 498 | // a foreign key behind them. | 534 | // a foreign key behind them. |
| 499 | sqlx::query!( | 535 | sqlx::query!( |
| 500 | r#"UPDATE bank_question SET subject = NULL | 536 | r#"UPDATE bank_question SET subject = NULL |
| 501 | WHERE subject IN (SELECT id FROM subject WHERE course = $1)"#, | 537 | WHERE subject IN (SELECT id FROM subject WHERE course = $1)"#, |
| 502 | - course.id, | 538 | + course.id.uuid(), |
| 503 | ) | 539 | ) |
| 504 | .execute(&mut *tx) | 540 | .execute(&mut *tx) |
| 505 | .await?; | 541 | .await?; |
| 506 | sqlx::query!( | 542 | sqlx::query!( |
| 507 | r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = ANY($1)"#, | 543 | r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = ANY($1)"#, |
| 508 | - exams, | 544 | + &exams, |
| 509 | ) | 545 | ) |
| 510 | .execute(&mut *tx) | 546 | .execute(&mut *tx) |
| 511 | .await?; | 547 | .await?; |
| 512 | // Subjects before exams would trip `exam.subject` — exams go first. | 548 | // Subjects before exams would trip `exam.subject` — exams go first. |
| 513 | - sqlx::query!(r#"DELETE FROM exam WHERE course = $1"#, course.id) | 549 | + sqlx::query!(r#"DELETE FROM exam WHERE course = $1"#, course.id.uuid()) |
| 514 | - .execute(&mut *tx) | ||
| 515 | - .await?; | ||
| 516 | - sqlx::query!(r#"DELETE FROM homework WHERE course = $1"#, course.id) | ||
| 517 | .execute(&mut *tx) | 550 | .execute(&mut *tx) |
| 518 | .await?; | 551 | .await?; |
| 519 | - sqlx::query!(r#"DELETE FROM subject WHERE course = $1"#, course.id) | 552 | + sqlx::query!( |
| 553 | + r#"DELETE FROM homework WHERE course = $1"#, | ||
| 554 | + course.id.uuid() | ||
| 555 | + ) | ||
| 556 | + .execute(&mut *tx) | ||
| 557 | + .await?; | ||
| 558 | + sqlx::query!(r#"DELETE FROM subject WHERE course = $1"#, course.id.uuid()) | ||
| 520 | .execute(&mut *tx) | 559 | .execute(&mut *tx) |
| 521 | .await?; | 560 | .await?; |
| 522 | // Last: the course itself, now FK-silent. | 561 | // Last: the course itself, now FK-silent. |
| 523 | - sqlx::query!(r#"DELETE FROM course WHERE id = $1"#, course.id) | 562 | + sqlx::query!(r#"DELETE FROM course WHERE id = $1"#, course.id.uuid()) |
| 524 | .execute(&mut *tx) | 563 | .execute(&mut *tx) |
| 525 | .await?; | 564 | .await?; |
| 526 | Ok(true) | 565 | Ok(true) |
src/db/course_note.rsmodified+24 -14
| @@ -6,7 +6,9 @@ use crate::db::field_update::FieldUpdate; | |||
| 6 | use crate::db::page::PagedList; | 6 | use crate::db::page::PagedList; |
| 7 | use crate::domain::course::CourseId; | 7 | use crate::domain::course::CourseId; |
| 8 | use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle}; | 8 | use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle}; |
| 9 | -use crate::domain::course_note_file::CourseNoteFile; | 9 | +use crate::domain::course_note_file::{ |
| 10 | + CourseNoteFile, CourseNoteFileId, FileContentType, FileName, | ||
| 11 | +}; | ||
| 10 | use crate::domain::user::UserId; | 12 | use crate::domain::user::UserId; |
| 11 | use crate::error::AppError; | 13 | use crate::error::AppError; |
| 12 | 14 | ||
| @@ -34,12 +36,14 @@ pub async fn create( | |||
| 34 | CourseNote, | 36 | CourseNote, |
| 35 | r#"INSERT INTO course_note (id, course, author, title, content) | 37 | r#"INSERT INTO course_note (id, course, author, title, content) |
| 36 | VALUES ($1, $2, $3, $4, $5) | 38 | VALUES ($1, $2, $3, $4, $5) |
| 37 | - RETURNING id, course, author, title, content"#, | 39 | + RETURNING id AS "id: CourseNoteId", course AS "course: CourseId", |
| 38 | - note.id, | 40 | + author AS "author: UserId", title AS "title: CourseNoteTitle", |
| 39 | - note.course, | 41 | + content AS "content: CourseNoteContent""#, |
| 40 | - note.author, | 42 | + note.id.uuid(), |
| 41 | - note.title, | 43 | + note.course.uuid(), |
| 42 | - note.content | 44 | + note.author.uuid(), |
| 45 | + note.title.as_str(), | ||
| 46 | + note.content.as_str() | ||
| 43 | ) | 47 | ) |
| 44 | .fetch_one(db) | 48 | .fetch_one(db) |
| 45 | .await; | 49 | .await; |
| @@ -53,8 +57,10 @@ pub async fn create( | |||
| 53 | pub async fn read(db: &Database, id: &CourseNoteId) -> Result<Option<CourseNote>, AppError> { | 57 | pub async fn read(db: &Database, id: &CourseNoteId) -> Result<Option<CourseNote>, AppError> { |
| 54 | let note = sqlx::query_as!( | 58 | let note = sqlx::query_as!( |
| 55 | CourseNote, | 59 | CourseNote, |
| 56 | - r#"SELECT id, course, author, title, content FROM course_note WHERE id = $1"#, | 60 | + r#"SELECT id AS "id: CourseNoteId", course AS "course: CourseId", |
| 57 | - id | 61 | + author AS "author: UserId", title AS "title: CourseNoteTitle", |
| 62 | + content AS "content: CourseNoteContent" FROM course_note WHERE id = $1"#, | ||
| 63 | + id.uuid() | ||
| 58 | ) | 64 | ) |
| 59 | .fetch_optional(db) | 65 | .fetch_optional(db) |
| 60 | .await?; | 66 | .await?; |
| @@ -112,21 +118,25 @@ pub async fn delete( | |||
| 112 | note: CourseNote, | 118 | note: CourseNote, |
| 113 | ) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> { | 119 | ) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> { |
| 114 | tx_with_retry(db, true, async |conn| { | 120 | tx_with_retry(db, true, async |conn| { |
| 115 | - sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id) | 121 | + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id.uuid()) |
| 116 | .execute(&mut *conn) | 122 | .execute(&mut *conn) |
| 117 | .await?; | 123 | .await?; |
| 118 | let files = sqlx::query_as!( | 124 | let files = sqlx::query_as!( |
| 119 | CourseNoteFile, | 125 | CourseNoteFile, |
| 120 | r#"DELETE FROM course_note_file WHERE course_note = $1 | 126 | r#"DELETE FROM course_note_file WHERE course_note = $1 |
| 121 | - RETURNING id, course_note, name, content_type, size"#, | 127 | + RETURNING id AS "id: CourseNoteFileId", |
| 122 | - note.id | 128 | + course_note AS "course_note: CourseNoteId", name AS "name: FileName", |
| 129 | + content_type AS "content_type: FileContentType", size"#, | ||
| 130 | + note.id.uuid() | ||
| 123 | ) | 131 | ) |
| 124 | .fetch_all(&mut *conn) | 132 | .fetch_all(&mut *conn) |
| 125 | .await?; | 133 | .await?; |
| 126 | let gone = sqlx::query_as!( | 134 | let gone = sqlx::query_as!( |
| 127 | CourseNote, | 135 | CourseNote, |
| 128 | - r#"DELETE FROM course_note WHERE id = $1 RETURNING id, course, author, title, content"#, | 136 | + r#"DELETE FROM course_note WHERE id = $1 RETURNING id AS "id: CourseNoteId", course AS "course: CourseId", |
| 129 | - note.id | 137 | + author AS "author: UserId", title AS "title: CourseNoteTitle", |
| 138 | + content AS "content: CourseNoteContent""#, | ||
| 139 | + note.id.uuid() | ||
| 130 | ) | 140 | ) |
| 131 | .fetch_optional(&mut *conn) | 141 | .fetch_optional(&mut *conn) |
| 132 | .await?; | 142 | .await?; |
src/db/course_note_file.rsmodified+25 -15
| @@ -7,7 +7,9 @@ use crate::database::{Database, tx_with_retry, unique_violation}; | |||
| 7 | use crate::db::page::PagedList; | 7 | use crate::db::page::PagedList; |
| 8 | use crate::domain::course::CourseId; | 8 | use crate::domain::course::CourseId; |
| 9 | use crate::domain::course_note::CourseNoteId; | 9 | use crate::domain::course_note::CourseNoteId; |
| 10 | -use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; | 10 | +use crate::domain::course_note_file::{ |
| 11 | + CourseNoteFile, CourseNoteFileId, FileContentType, FileName, | ||
| 12 | +}; | ||
| 11 | use crate::error::AppError; | 13 | use crate::error::AppError; |
| 12 | 14 | ||
| 13 | /// Persist the row assembled by [`CourseNoteFile::new`], refusing once its | 15 | /// Persist the row assembled by [`CourseNoteFile::new`], refusing once its |
| @@ -26,12 +28,14 @@ pub async fn insert(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFil | |||
| 26 | RETURNING 1) | 28 | RETURNING 1) |
| 27 | INSERT INTO course_note_file (id, course_note, name, content_type, size) | 29 | INSERT INTO course_note_file (id, course_note, name, content_type, size) |
| 28 | SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) | 30 | SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) |
| 29 | - RETURNING id, course_note, name, content_type, size"#, | 31 | + RETURNING id AS "id: CourseNoteFileId", |
| 30 | - file.course_note, | 32 | + course_note AS "course_note: CourseNoteId", name AS "name: FileName", |
| 33 | + content_type AS "content_type: FileContentType", size"#, | ||
| 34 | + file.course_note.uuid(), | ||
| 31 | MAX_COURSE_NOTE_FILES as i64, | 35 | MAX_COURSE_NOTE_FILES as i64, |
| 32 | - file.id, | 36 | + file.id.uuid(), |
| 33 | - file.name, | 37 | + file.name.as_str(), |
| 34 | - file.content_type, | 38 | + file.content_type.as_str(), |
| 35 | file.size | 39 | file.size |
| 36 | ) | 40 | ) |
| 37 | .fetch_optional(db) | 41 | .fetch_optional(db) |
| @@ -61,8 +65,10 @@ pub async fn read( | |||
| 61 | ) -> Result<Option<CourseNoteFile>, AppError> { | 65 | ) -> Result<Option<CourseNoteFile>, AppError> { |
| 62 | let file = sqlx::query_as!( | 66 | let file = sqlx::query_as!( |
| 63 | CourseNoteFile, | 67 | CourseNoteFile, |
| 64 | - r#"SELECT id, course_note, name, content_type, size FROM course_note_file WHERE id = $1"#, | 68 | + r#"SELECT id AS "id: CourseNoteFileId", |
| 65 | - id | 69 | + course_note AS "course_note: CourseNoteId", name AS "name: FileName", |
| 70 | + content_type AS "content_type: FileContentType", size FROM course_note_file WHERE id = $1"#, | ||
| 71 | + id.uuid() | ||
| 66 | ) | 72 | ) |
| 67 | .fetch_optional(db) | 73 | .fetch_optional(db) |
| 68 | .await?; | 74 | .await?; |
| @@ -78,10 +84,12 @@ pub async fn read_for( | |||
| 78 | ) -> Result<Option<CourseNoteFile>, AppError> { | 84 | ) -> Result<Option<CourseNoteFile>, AppError> { |
| 79 | let file = sqlx::query_as!( | 85 | let file = sqlx::query_as!( |
| 80 | CourseNoteFile, | 86 | CourseNoteFile, |
| 81 | - r#"SELECT id, course_note, name, content_type, size FROM course_note_file | 87 | + r#"SELECT id AS "id: CourseNoteFileId", |
| 88 | + course_note AS "course_note: CourseNoteId", name AS "name: FileName", | ||
| 89 | + content_type AS "content_type: FileContentType", size FROM course_note_file | ||
| 82 | WHERE id = $1 AND course_note = $2"#, | 90 | WHERE id = $1 AND course_note = $2"#, |
| 83 | - id, | 91 | + id.uuid(), |
| 84 | - note | 92 | + note.uuid() |
| 85 | ) | 93 | ) |
| 86 | .fetch_optional(db) | 94 | .fetch_optional(db) |
| 87 | .await?; | 95 | .await?; |
| @@ -114,7 +122,7 @@ pub async fn file_keys_for_course( | |||
| 114 | let rows = sqlx::query!( | 122 | let rows = sqlx::query!( |
| 115 | r#"SELECT course_note_file.id AS "id: CourseNoteFileId" FROM course_note_file | 123 | r#"SELECT course_note_file.id AS "id: CourseNoteFileId" FROM course_note_file |
| 116 | WHERE course_note IN (SELECT id FROM course_note WHERE course = $1)"#, | 124 | WHERE course_note IN (SELECT id FROM course_note WHERE course = $1)"#, |
| 117 | - course.0 | 125 | + course.uuid() |
| 118 | ) | 126 | ) |
| 119 | .fetch_all(db) | 127 | .fetch_all(db) |
| 120 | .await?; | 128 | .await?; |
| @@ -129,15 +137,17 @@ pub async fn delete(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFil | |||
| 129 | let gone = sqlx::query_as!( | 137 | let gone = sqlx::query_as!( |
| 130 | CourseNoteFile, | 138 | CourseNoteFile, |
| 131 | r#"DELETE FROM course_note_file WHERE id = $1 | 139 | r#"DELETE FROM course_note_file WHERE id = $1 |
| 132 | - RETURNING id, course_note, name, content_type, size"#, | 140 | + RETURNING id AS "id: CourseNoteFileId", |
| 133 | - file.id | 141 | + course_note AS "course_note: CourseNoteId", name AS "name: FileName", |
| 142 | + content_type AS "content_type: FileContentType", size"#, | ||
| 143 | + file.id.uuid() | ||
| 134 | ) | 144 | ) |
| 135 | .fetch_optional(&mut *conn) | 145 | .fetch_optional(&mut *conn) |
| 136 | .await?; | 146 | .await?; |
| 137 | let file = gone.ok_or(AppError::NotFound)?; | 147 | let file = gone.ok_or(AppError::NotFound)?; |
| 138 | sqlx::query!( | 148 | sqlx::query!( |
| 139 | "UPDATE course_note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1", | 149 | "UPDATE course_note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1", |
| 140 | - file.course_note | 150 | + file.course_note.uuid() |
| 141 | ) | 151 | ) |
| 142 | .execute(&mut *conn) | 152 | .execute(&mut *conn) |
| 143 | .await?; | 153 | .await?; |
src/db/course_session.rsmodified+18 -12
| @@ -41,13 +41,15 @@ pub async fn create( | |||
| 41 | CourseSession, | 41 | CourseSession, |
| 42 | r#"INSERT INTO course_session (id, course, teacher, topic, starts_at, ends_at) | 42 | r#"INSERT INTO course_session (id, course, teacher, topic, starts_at, ends_at) |
| 43 | VALUES ($1, $2, $3, $4, $5, $6) | 43 | VALUES ($1, $2, $3, $4, $5, $6) |
| 44 | - RETURNING id, course, teacher, topic, starts_at, ends_at"#, | 44 | + RETURNING id AS "id: CourseSessionId", course AS "course: CourseId", |
| 45 | - session.id, | 45 | + teacher AS "teacher: UserId", topic AS "topic: SessionTopic", |
| 46 | - session.course, | 46 | + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp""#, |
| 47 | - session.teacher, | 47 | + session.id.uuid(), |
| 48 | - session.topic, | 48 | + session.course.uuid(), |
| 49 | - session.starts_at, | 49 | + session.teacher.uuid(), |
| 50 | - session.ends_at, | 50 | + session.topic.as_str(), |
| 51 | + session.starts_at.as_millis(), | ||
| 52 | + session.ends_at.map(|at| at.as_millis()), | ||
| 51 | ) | 53 | ) |
| 52 | .fetch_one(db) | 54 | .fetch_one(db) |
| 53 | .await; | 55 | .await; |
| @@ -61,9 +63,11 @@ pub async fn create( | |||
| 61 | pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> { | 63 | pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> { |
| 62 | let session = sqlx::query_as!( | 64 | let session = sqlx::query_as!( |
| 63 | CourseSession, | 65 | CourseSession, |
| 64 | - r#"SELECT id, course, teacher, topic, starts_at, ends_at | 66 | + r#"SELECT id AS "id: CourseSessionId", course AS "course: CourseId", |
| 67 | + teacher AS "teacher: UserId", topic AS "topic: SessionTopic", | ||
| 68 | + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp" | ||
| 65 | FROM course_session WHERE id = $1"#, | 69 | FROM course_session WHERE id = $1"#, |
| 66 | - id, | 70 | + id.uuid(), |
| 67 | ) | 71 | ) |
| 68 | .fetch_optional(db) | 72 | .fetch_optional(db) |
| 69 | .await?; | 73 | .await?; |
| @@ -132,15 +136,17 @@ pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSessi | |||
| 132 | // session may simply have had none. | 136 | // session may simply have had none. |
| 133 | sqlx::query!( | 137 | sqlx::query!( |
| 134 | r#"DELETE FROM session_attendance WHERE session = $1"#, | 138 | r#"DELETE FROM session_attendance WHERE session = $1"#, |
| 135 | - session.id, | 139 | + session.id.uuid(), |
| 136 | ) | 140 | ) |
| 137 | .execute(&mut *tx) | 141 | .execute(&mut *tx) |
| 138 | .await?; | 142 | .await?; |
| 139 | let deleted = sqlx::query_as!( | 143 | let deleted = sqlx::query_as!( |
| 140 | CourseSession, | 144 | CourseSession, |
| 141 | r#"DELETE FROM course_session WHERE id = $1 | 145 | r#"DELETE FROM course_session WHERE id = $1 |
| 142 | - RETURNING id, course, teacher, topic, starts_at, ends_at"#, | 146 | + RETURNING id AS "id: CourseSessionId", course AS "course: CourseId", |
| 143 | - session.id, | 147 | + teacher AS "teacher: UserId", topic AS "topic: SessionTopic", |
| 148 | + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp""#, | ||
| 149 | + session.id.uuid(), | ||
| 144 | ) | 150 | ) |
| 145 | .fetch_optional(&mut *tx) | 151 | .fetch_optional(&mut *tx) |
| 146 | .await?; | 152 | .await?; |
src/db/dietary_profile.rsmodified+8 -8
| @@ -16,9 +16,9 @@ use crate::error::AppError; | |||
| 16 | pub async fn read(db: &Database, student: &UserId) -> Result<Option<DietaryProfile>, AppError> { | 16 | pub async fn read(db: &Database, student: &UserId) -> Result<Option<DietaryProfile>, AppError> { |
| 17 | let row = sqlx::query_as!( | 17 | let row = sqlx::query_as!( |
| 18 | DietaryProfile, | 18 | DietaryProfile, |
| 19 | - "SELECT student, tags, note, updated_by, updated_at | 19 | + "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\" |
| 20 | FROM dietary_profile WHERE student = $1", | 20 | FROM dietary_profile WHERE student = $1", |
| 21 | - *student, | 21 | + student.uuid(), |
| 22 | ) | 22 | ) |
| 23 | .fetch_optional(db) | 23 | .fetch_optional(db) |
| 24 | .await?; | 24 | .await?; |
| @@ -62,12 +62,12 @@ pub async fn save( | |||
| 62 | note = CASE WHEN $6 THEN $3 ELSE dietary_profile.note END, | 62 | note = CASE WHEN $6 THEN $3 ELSE dietary_profile.note END, |
| 63 | updated_by = $4, | 63 | updated_by = $4, |
| 64 | updated_at = $5 | 64 | updated_at = $5 |
| 65 | - RETURNING student, tags, note, updated_by, updated_at", | 65 | + 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\"", |
| 66 | - *student, | 66 | + student.uuid(), |
| 67 | - tags.map(|t| t.as_slice().to_vec()), | 67 | + tags.as_ref().map(|t| t.as_slice()), |
| 68 | - note.clone().flatten().map(|n| n.as_str().to_string()), | 68 | + note.as_ref().and_then(|n| n.as_ref()).map(|n| n.as_str()), |
| 69 | - *by, | 69 | + by.uuid(), |
| 70 | - Timestamp::now(), | 70 | + Timestamp::now().as_millis(), |
| 71 | note.is_some(), | 71 | note.is_some(), |
| 72 | ) | 72 | ) |
| 73 | .fetch_one(db) | 73 | .fetch_one(db) |
src/db/enrollment.rsmodified+21 -16
| @@ -7,6 +7,7 @@ | |||
| 7 | use crate::database::{Database, tx_with_retry, unique_violation}; | 7 | use crate::database::{Database, tx_with_retry, unique_violation}; |
| 8 | use crate::db::cap; | 8 | use crate::db::cap; |
| 9 | use crate::db::page::PagedList; | 9 | use crate::db::page::PagedList; |
| 10 | +use crate::domain::class_group::ClassGroupId; | ||
| 10 | use crate::domain::course::CourseId; | 11 | use crate::domain::course::CourseId; |
| 11 | use crate::domain::enrollment::Enrollment; | 12 | use crate::domain::enrollment::Enrollment; |
| 12 | use crate::domain::role::Role; | 13 | use crate::domain::role::Role; |
| @@ -64,8 +65,8 @@ pub async fn enroll( | |||
| 64 | // already in" still outranks everything. | 65 | // already in" still outranks everything. |
| 65 | let held = sqlx::query!( | 66 | let held = sqlx::query!( |
| 66 | r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#, | 67 | r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#, |
| 67 | - course, | 68 | + course.uuid(), |
| 68 | - user, | 69 | + user.uuid(), |
| 69 | ) | 70 | ) |
| 70 | .fetch_optional(&mut *tx) | 71 | .fetch_optional(&mut *tx) |
| 71 | .await?; | 72 | .await?; |
| @@ -77,7 +78,7 @@ pub async fn enroll( | |||
| 77 | // demotion (see the doc above). | 78 | // demotion (see the doc above). |
| 78 | let role = sqlx::query!( | 79 | let role = sqlx::query!( |
| 79 | r#"SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#, | 80 | r#"SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#, |
| 80 | - user, | 81 | + user.uuid(), |
| 81 | ) | 82 | ) |
| 82 | .fetch_optional(&mut *tx) | 83 | .fetch_optional(&mut *tx) |
| 83 | .await?; | 84 | .await?; |
| @@ -98,11 +99,12 @@ pub async fn enroll( | |||
| 98 | RETURNING 1) | 99 | RETURNING 1) |
| 99 | INSERT INTO enrollment (course, app_user, enrolled_by, source) | 100 | INSERT INTO enrollment (course, app_user, enrolled_by, source) |
| 100 | SELECT $1, $3, $4, NULL WHERE EXISTS (SELECT 1 FROM seat) | 101 | SELECT $1, $3, $4, NULL WHERE EXISTS (SELECT 1 FROM seat) |
| 101 | - RETURNING course, app_user AS "user", enrolled_by, source"#, | 102 | + RETURNING course AS "course: CourseId", app_user AS "user: UserId", |
| 102 | - course, | 103 | + enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId""#, |
| 104 | + course.uuid(), | ||
| 103 | cap::UNLIMITED, | 105 | cap::UNLIMITED, |
| 104 | - user, | 106 | + user.uuid(), |
| 105 | - enrolled_by, | 107 | + enrolled_by.uuid(), |
| 106 | ) | 108 | ) |
| 107 | .fetch_optional(&mut *tx) | 109 | .fetch_optional(&mut *tx) |
| 108 | .await?; | 110 | .await?; |
| @@ -161,9 +163,10 @@ async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result<Enrollm | |||
| 161 | Enrollment, | 163 | Enrollment, |
| 162 | r#"UPDATE enrollment SET source = NULL | 164 | r#"UPDATE enrollment SET source = NULL |
| 163 | WHERE course = $1 AND app_user = $2 | 165 | WHERE course = $1 AND app_user = $2 |
| 164 | - RETURNING course, app_user AS "user", enrolled_by, source"#, | 166 | + RETURNING course AS "course: CourseId", app_user AS "user: UserId", |
| 165 | - existing.get_course(), | 167 | + enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId""#, |
| 166 | - existing.get_user(), | 168 | + existing.get_course().uuid(), |
| 169 | + existing.get_user().uuid(), | ||
| 167 | ) | 170 | ) |
| 168 | .fetch_optional(db) | 171 | .fetch_optional(db) |
| 169 | .await?; | 172 | .await?; |
| @@ -184,10 +187,11 @@ pub async fn read_for_user( | |||
| 184 | ) -> Result<Option<Enrollment>, AppError> { | 187 | ) -> Result<Option<Enrollment>, AppError> { |
| 185 | let row = sqlx::query_as!( | 188 | let row = sqlx::query_as!( |
| 186 | Enrollment, | 189 | Enrollment, |
| 187 | - r#"SELECT course, app_user AS "user", enrolled_by, source | 190 | + r#"SELECT course AS "course: CourseId", app_user AS "user: UserId", |
| 191 | + enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId" | ||
| 188 | FROM enrollment WHERE course = $1 AND app_user = $2"#, | 192 | FROM enrollment WHERE course = $1 AND app_user = $2"#, |
| 189 | - course, | 193 | + course.uuid(), |
| 190 | - user, | 194 | + user.uuid(), |
| 191 | ) | 195 | ) |
| 192 | .fetch_optional(db) | 196 | .fetch_optional(db) |
| 193 | .await?; | 197 | .await?; |
| @@ -231,9 +235,10 @@ pub async fn remove( | |||
| 231 | enrollment_count - (SELECT count(*) FROM gone), 0) | 235 | enrollment_count - (SELECT count(*) FROM gone), 0) |
| 232 | WHERE id = $1 | 236 | WHERE id = $1 |
| 233 | RETURNING 1) | 237 | RETURNING 1) |
| 234 | - SELECT course, app_user AS "user", enrolled_by, source FROM gone"#, | 238 | + SELECT course AS "course: CourseId", app_user AS "user: UserId", |
| 235 | - course, | 239 | + enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId" FROM gone"#, |
| 236 | - user, | 240 | + course.uuid(), |
| 241 | + user.uuid(), | ||
| 237 | ) | 242 | ) |
| 238 | .fetch_optional(db) | 243 | .fetch_optional(db) |
| 239 | .await?; | 244 | .await?; |
src/db/event.rsmodified+6 -6
| @@ -40,7 +40,7 @@ pub async fn includes(db: &Database, event: &Event, user: &User) -> Result<bool, | |||
| 40 | Some(class) => { | 40 | Some(class) => { |
| 41 | let row = sqlx::query!( | 41 | let row = sqlx::query!( |
| 42 | "SELECT EXISTS(SELECT 1 FROM class_member WHERE class = $1 AND app_user = $2) | 42 | "SELECT EXISTS(SELECT 1 FROM class_member WHERE class = $1 AND app_user = $2) |
| 43 | - AS present", | 43 | + AS \"present!\"", |
| 44 | class.uuid(), | 44 | class.uuid(), |
| 45 | user.get_id().uuid() | 45 | user.get_id().uuid() |
| 46 | ) | 46 | ) |
| @@ -120,7 +120,7 @@ pub async fn create( | |||
| 120 | // bundle guarantees only the matching payload is ever non-NULL. | 120 | // bundle guarantees only the matching payload is ever non-NULL. |
| 121 | let created = query_as!( | 121 | let created = query_as!( |
| 122 | Event, | 122 | Event, |
| 123 | - "INSERT INTO event (id, creator, title AS \"title: EventTitle\", description AS \"description: EventDescription\", audience_kind, audience_role, \ | 123 | + "INSERT INTO event (id, creator, title, description, audience_kind, audience_role, \ |
| 124 | audience_course, audience_class, audience_capacity, starts_at, ends_at) | 124 | audience_course, audience_class, audience_capacity, starts_at, ends_at) |
| 125 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) | 125 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) |
| 126 | RETURNING id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \ | 126 | 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( | |||
| 134 | creator.uuid(), | 134 | creator.uuid(), |
| 135 | title.as_str(), | 135 | title.as_str(), |
| 136 | description.as_str(), | 136 | description.as_str(), |
| 137 | - audience.kind, | 137 | + audience.kind.as_str(), |
| 138 | audience.role.map(|r| r.as_str().to_string()), | 138 | audience.role.map(|r| r.as_str().to_string()), |
| 139 | audience.course.map(|c| c.uuid()), | 139 | audience.course.map(|c| c.uuid()), |
| 140 | audience.class.map(|c| c.uuid()), | 140 | audience.class.map(|c| c.uuid()), |
| @@ -225,11 +225,11 @@ pub async fn update( | |||
| 225 | ) | 225 | ) |
| 226 | .set( | 226 | .set( |
| 227 | "audience_course", | 227 | "audience_course", |
| 228 | - audience.as_ref().map(|a| Param::OptUuid(a.course.map(|c| c.uuid()))), | 228 | + audience.as_ref().map(|a| Param::OptUuid(a.course.as_ref().map(|c| c.uuid()))), |
| 229 | ) | 229 | ) |
| 230 | .set( | 230 | .set( |
| 231 | "audience_class", | 231 | "audience_class", |
| 232 | - audience.as_ref().map(|a| Param::OptUuid(a.class.map(|c| c.uuid()))), | 232 | + audience.as_ref().map(|a| Param::OptUuid(a.class.as_ref().map(|c| c.uuid()))), |
| 233 | ) | 233 | ) |
| 234 | .set( | 234 | .set( |
| 235 | "audience_capacity", | 235 | "audience_capacity", |
| @@ -259,7 +259,7 @@ pub async fn update( | |||
| 259 | /// for the event row (its insert's foreign key proves the event the moment | 259 | /// for the event row (its insert's foreign key proves the event the moment |
| 260 | /// it lands), so a lost round re-sends instead of answering 500. | 260 | /// it lands), so a lost round re-sends instead of answering 500. |
| 261 | pub async fn delete(db: &Database, event: Event) -> Result<Event, AppError> { | 261 | pub async fn delete(db: &Database, event: Event) -> Result<Event, AppError> { |
| 262 | - tx_with_retry(db, true, async |tx| { | 262 | + tx_with_retry(db, true, async move |tx| { |
| 263 | sqlx::query!("DELETE FROM attendance WHERE event = $1", event.get_id().uuid()) | 263 | sqlx::query!("DELETE FROM attendance WHERE event = $1", event.get_id().uuid()) |
| 264 | .execute(&mut *tx) | 264 | .execute(&mut *tx) |
| 265 | .await?; | 265 | .await?; |
src/db/exam.rsmodified+76 -76
| @@ -44,23 +44,23 @@ pub async fn create( | |||
| 44 | RETURNING id AS "id: ExamId", creator AS "creator: UserId", | 44 | RETURNING id AS "id: ExamId", creator AS "creator: UserId", |
| 45 | course AS "course: CourseId", title AS "title: ExamTitle", | 45 | course AS "course: CourseId", title AS "title: ExamTitle", |
| 46 | description AS "description: ExamDescription", | 46 | description AS "description: ExamDescription", |
| 47 | - kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>", | 47 | + kind AS "kind: ExamKind", mode AS "mode: ExamMode", |
| 48 | - starts_at AS "starts_at: Option<Timestamp>", | 48 | + starts_at AS "starts_at: Timestamp", |
| 49 | - ends_at AS "ends_at: Option<Timestamp>", | 49 | + ends_at AS "ends_at: Timestamp", |
| 50 | - duration_ms AS "duration_ms: Option<ExamDuration>", | 50 | + duration_ms AS "duration_ms: ExamDuration", |
| 51 | max_attempts AS "max_attempts: ExamAttemptLimit", | 51 | max_attempts AS "max_attempts: ExamAttemptLimit", |
| 52 | allow_rejoin, allow_review, draft"#, | 52 | allow_rejoin, allow_review, draft"#, |
| 53 | - ExamId::generate(), | 53 | + ExamId::generate().uuid(), |
| 54 | - creator as &UserId, | 54 | + creator.uuid(), |
| 55 | - course as &CourseId, | 55 | + course.uuid(), |
| 56 | - title, | 56 | + title.as_str(), |
| 57 | - description, | 57 | + description.as_str(), |
| 58 | - kind, | 58 | + kind.as_str(), |
| 59 | - schedule.mode, | 59 | + schedule.mode.as_ref().map(ExamMode::as_str), |
| 60 | - schedule.starts_at, | 60 | + schedule.starts_at.map(|at| at.as_millis()), |
| 61 | - schedule.ends_at, | 61 | + schedule.ends_at.map(|at| at.as_millis()), |
| 62 | - schedule.duration_ms, | 62 | + schedule.duration_ms.map(|duration| duration.as_millis()), |
| 63 | - max_attempts, | 63 | + max_attempts.as_i64(), |
| 64 | allow_rejoin, | 64 | allow_rejoin, |
| 65 | allow_review, | 65 | allow_review, |
| 66 | draft, | 66 | draft, |
| @@ -79,14 +79,14 @@ pub async fn read(db: &Database, id: &ExamId) -> Result<Option<Exam>, AppError> | |||
| 79 | Exam, | 79 | Exam, |
| 80 | r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", | 80 | r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", |
| 81 | title AS "title: ExamTitle", description AS "description: ExamDescription", | 81 | title AS "title: ExamTitle", description AS "description: ExamDescription", |
| 82 | - kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>", | 82 | + kind AS "kind: ExamKind", mode AS "mode: ExamMode", |
| 83 | - starts_at AS "starts_at: Option<Timestamp>", | 83 | + starts_at AS "starts_at: Timestamp", |
| 84 | - ends_at AS "ends_at: Option<Timestamp>", | 84 | + ends_at AS "ends_at: Timestamp", |
| 85 | - duration_ms AS "duration_ms: Option<ExamDuration>", | 85 | + duration_ms AS "duration_ms: ExamDuration", |
| 86 | max_attempts AS "max_attempts: ExamAttemptLimit", | 86 | max_attempts AS "max_attempts: ExamAttemptLimit", |
| 87 | allow_rejoin, allow_review, draft | 87 | allow_rejoin, allow_review, draft |
| 88 | FROM exam WHERE id = $1"#, | 88 | FROM exam WHERE id = $1"#, |
| 89 | - id as &ExamId, | 89 | + id.uuid(), |
| 90 | ) | 90 | ) |
| 91 | .fetch_optional(db) | 91 | .fetch_optional(db) |
| 92 | .await?) | 92 | .await?) |
| @@ -99,10 +99,10 @@ pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> { | |||
| 99 | Exam, | 99 | Exam, |
| 100 | r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", | 100 | r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", |
| 101 | title AS "title: ExamTitle", description AS "description: ExamDescription", | 101 | title AS "title: ExamTitle", description AS "description: ExamDescription", |
| 102 | - kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>", | 102 | + kind AS "kind: ExamKind", mode AS "mode: ExamMode", |
| 103 | - starts_at AS "starts_at: Option<Timestamp>", | 103 | + starts_at AS "starts_at: Timestamp", |
| 104 | - ends_at AS "ends_at: Option<Timestamp>", | 104 | + ends_at AS "ends_at: Timestamp", |
| 105 | - duration_ms AS "duration_ms: Option<ExamDuration>", | 105 | + duration_ms AS "duration_ms: ExamDuration", |
| 106 | max_attempts AS "max_attempts: ExamAttemptLimit", | 106 | max_attempts AS "max_attempts: ExamAttemptLimit", |
| 107 | allow_rejoin, allow_review, draft | 107 | allow_rejoin, allow_review, draft |
| 108 | FROM exam ORDER BY id DESC"#, | 108 | FROM exam ORDER BY id DESC"#, |
| @@ -116,14 +116,14 @@ pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Exa | |||
| 116 | Exam, | 116 | Exam, |
| 117 | r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", | 117 | r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", |
| 118 | title AS "title: ExamTitle", description AS "description: ExamDescription", | 118 | title AS "title: ExamTitle", description AS "description: ExamDescription", |
| 119 | - kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>", | 119 | + kind AS "kind: ExamKind", mode AS "mode: ExamMode", |
| 120 | - starts_at AS "starts_at: Option<Timestamp>", | 120 | + starts_at AS "starts_at: Timestamp", |
| 121 | - ends_at AS "ends_at: Option<Timestamp>", | 121 | + ends_at AS "ends_at: Timestamp", |
| 122 | - duration_ms AS "duration_ms: Option<ExamDuration>", | 122 | + duration_ms AS "duration_ms: ExamDuration", |
| 123 | max_attempts AS "max_attempts: ExamAttemptLimit", | 123 | max_attempts AS "max_attempts: ExamAttemptLimit", |
| 124 | allow_rejoin, allow_review, draft | 124 | allow_rejoin, allow_review, draft |
| 125 | FROM exam WHERE course = $1 ORDER BY id DESC"#, | 125 | FROM exam WHERE course = $1 ORDER BY id DESC"#, |
| 126 | - course as &CourseId, | 126 | + course.uuid(), |
| 127 | ) | 127 | ) |
| 128 | .fetch_all(db) | 128 | .fetch_all(db) |
| 129 | .await?) | 129 | .await?) |
| @@ -140,14 +140,14 @@ pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec | |||
| 140 | Exam, | 140 | Exam, |
| 141 | r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", | 141 | r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", |
| 142 | title AS "title: ExamTitle", description AS "description: ExamDescription", | 142 | title AS "title: ExamTitle", description AS "description: ExamDescription", |
| 143 | - kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>", | 143 | + kind AS "kind: ExamKind", mode AS "mode: ExamMode", |
| 144 | - starts_at AS "starts_at: Option<Timestamp>", | 144 | + starts_at AS "starts_at: Timestamp", |
| 145 | - ends_at AS "ends_at: Option<Timestamp>", | 145 | + ends_at AS "ends_at: Timestamp", |
| 146 | - duration_ms AS "duration_ms: Option<ExamDuration>", | 146 | + duration_ms AS "duration_ms: ExamDuration", |
| 147 | max_attempts AS "max_attempts: ExamAttemptLimit", | 147 | max_attempts AS "max_attempts: ExamAttemptLimit", |
| 148 | allow_rejoin, allow_review, draft | 148 | allow_rejoin, allow_review, draft |
| 149 | FROM exam WHERE course = ANY($1) ORDER BY id DESC"#, | 149 | FROM exam WHERE course = ANY($1) ORDER BY id DESC"#, |
| 150 | - courses, | 150 | + &courses, |
| 151 | ) | 151 | ) |
| 152 | .fetch_all(db) | 152 | .fetch_all(db) |
| 153 | .await?) | 153 | .await?) |
| @@ -160,7 +160,7 @@ pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec | |||
| 160 | pub async fn result_count(db: &Database, id: &ExamId) -> Result<i64, AppError> { | 160 | pub async fn result_count(db: &Database, id: &ExamId) -> Result<i64, AppError> { |
| 161 | let row = sqlx::query!( | 161 | let row = sqlx::query!( |
| 162 | r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#, | 162 | r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#, |
| 163 | - id as &ExamId, | 163 | + id.uuid(), |
| 164 | ) | 164 | ) |
| 165 | .fetch_one(db) | 165 | .fetch_one(db) |
| 166 | .await?; | 166 | .await?; |
| @@ -240,17 +240,17 @@ pub async fn update_if_unchanged( | |||
| 240 | let gates = sqlx::query!( | 240 | let gates = sqlx::query!( |
| 241 | r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat, | 241 | r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat, |
| 242 | EXISTS(SELECT 1 FROM exam_result WHERE exam = $1) AS graded"#, | 242 | EXISTS(SELECT 1 FROM exam_result WHERE exam = $1) AS graded"#, |
| 243 | - expected.id as &ExamId, | 243 | + expected.id.uuid(), |
| 244 | ) | 244 | ) |
| 245 | .fetch_one(&mut *conn) | 245 | .fetch_one(&mut *conn) |
| 246 | .await?; | 246 | .await?; |
| 247 | - if gates.sat || gates.graded { | 247 | + if gates.sat.unwrap_or(false) || gates.graded.unwrap_or(false) { |
| 248 | return Err(redraft_error()); | 248 | return Err(redraft_error()); |
| 249 | } | 249 | } |
| 250 | } | 250 | } |
| 251 | let was_results = sqlx::query!( | 251 | let was_results = sqlx::query!( |
| 252 | r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#, | 252 | r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#, |
| 253 | - expected.id as &ExamId, | 253 | + expected.id.uuid(), |
| 254 | ) | 254 | ) |
| 255 | .fetch_optional(&mut *conn) | 255 | .fetch_optional(&mut *conn) |
| 256 | .await? | 256 | .await? |
| @@ -274,32 +274,32 @@ pub async fn update_if_unchanged( | |||
| 274 | RETURNING id AS "id: ExamId", creator AS "creator: UserId", | 274 | RETURNING id AS "id: ExamId", creator AS "creator: UserId", |
| 275 | course AS "course: CourseId", title AS "title: ExamTitle", | 275 | course AS "course: CourseId", title AS "title: ExamTitle", |
| 276 | description AS "description: ExamDescription", | 276 | description AS "description: ExamDescription", |
| 277 | - kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>", | 277 | + kind AS "kind: ExamKind", mode AS "mode: ExamMode", |
| 278 | - starts_at AS "starts_at: Option<Timestamp>", | 278 | + starts_at AS "starts_at: Timestamp", |
| 279 | - ends_at AS "ends_at: Option<Timestamp>", | 279 | + ends_at AS "ends_at: Timestamp", |
| 280 | - duration_ms AS "duration_ms: Option<ExamDuration>", | 280 | + duration_ms AS "duration_ms: ExamDuration", |
| 281 | max_attempts AS "max_attempts: ExamAttemptLimit", | 281 | max_attempts AS "max_attempts: ExamAttemptLimit", |
| 282 | allow_rejoin, allow_review, draft"#, | 282 | allow_rejoin, allow_review, draft"#, |
| 283 | - expected.id as &ExamId, | 283 | + expected.id.uuid(), |
| 284 | - expected.title, | 284 | + expected.title.as_str(), |
| 285 | - expected.description, | 285 | + expected.description.as_str(), |
| 286 | - expected.kind, | 286 | + expected.kind.as_str(), |
| 287 | - expected.mode, | 287 | + expected.mode.as_ref().map(ExamMode::as_str), |
| 288 | - expected.starts_at, | 288 | + expected.starts_at.map(|at| at.as_millis()), |
| 289 | - expected.ends_at, | 289 | + expected.ends_at.map(|at| at.as_millis()), |
| 290 | - expected.duration_ms, | 290 | + expected.duration_ms.map(|duration| duration.as_millis()), |
| 291 | - expected.max_attempts, | 291 | + expected.max_attempts.as_i64(), |
| 292 | expected.allow_rejoin, | 292 | expected.allow_rejoin, |
| 293 | expected.allow_review, | 293 | expected.allow_review, |
| 294 | expected.draft, | 294 | expected.draft, |
| 295 | - was.0, | 295 | + was.0.as_str(), |
| 296 | - was.1, | 296 | + was.1.as_str(), |
| 297 | - was.2, | 297 | + was.2.as_str(), |
| 298 | - was.3, | 298 | + was.3.as_ref().map(ExamMode::as_str), |
| 299 | - was.4, | 299 | + was.4.map(|at| at.as_millis()), |
| 300 | - was.5, | 300 | + was.5.map(|at| at.as_millis()), |
| 301 | - was.6, | 301 | + was.6.map(|duration| duration.as_millis()), |
| 302 | - was.7, | 302 | + was.7.as_i64(), |
| 303 | was.8, | 303 | was.8, |
| 304 | was.9, | 304 | was.9, |
| 305 | was.10, | 305 | was.10, |
| @@ -358,7 +358,7 @@ pub async fn delete(db: &Database, target: Exam) -> Result<Deleted, AppError> { | |||
| 358 | // The row lock every other exam-child writer contends on. | 358 | // The row lock every other exam-child writer contends on. |
| 359 | let locked = sqlx::query!( | 359 | let locked = sqlx::query!( |
| 360 | r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, | 360 | r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, |
| 361 | - target.id as &ExamId, | 361 | + target.id.uuid(), |
| 362 | ) | 362 | ) |
| 363 | .fetch_optional(&mut *conn) | 363 | .fetch_optional(&mut *conn) |
| 364 | .await?; | 364 | .await?; |
| @@ -371,7 +371,7 @@ pub async fn delete(db: &Database, target: Exam) -> Result<Deleted, AppError> { | |||
| 371 | // refused. | 371 | // refused. |
| 372 | let image_files = sqlx::query!( | 372 | let image_files = sqlx::query!( |
| 373 | r#"SELECT file FROM question_image WHERE exam = $1"#, | 373 | r#"SELECT file FROM question_image WHERE exam = $1"#, |
| 374 | - target.id as &ExamId, | 374 | + target.id.uuid(), |
| 375 | ) | 375 | ) |
| 376 | .fetch_all(&mut *conn) | 376 | .fetch_all(&mut *conn) |
| 377 | .await? | 377 | .await? |
| @@ -380,7 +380,7 @@ pub async fn delete(db: &Database, target: Exam) -> Result<Deleted, AppError> { | |||
| 380 | .collect(); | 380 | .collect(); |
| 381 | let answer_image_files = sqlx::query!( | 381 | let answer_image_files = sqlx::query!( |
| 382 | r#"SELECT file FROM answer_image WHERE exam = $1"#, | 382 | r#"SELECT file FROM answer_image WHERE exam = $1"#, |
| 383 | - target.id as &ExamId, | 383 | + target.id.uuid(), |
| 384 | ) | 384 | ) |
| 385 | .fetch_all(&mut *conn) | 385 | .fetch_all(&mut *conn) |
| 386 | .await? | 386 | .await? |
| @@ -399,23 +399,23 @@ pub async fn delete(db: &Database, target: Exam) -> Result<Deleted, AppError> { | |||
| 399 | GROUP BY e.kind) | 399 | GROUP BY e.kind) |
| 400 | UPDATE kind_ref k SET count = GREATEST(k.count - c.n, 0) | 400 | UPDATE kind_ref k SET count = GREATEST(k.count - c.n, 0) |
| 401 | FROM kinds c WHERE k.name = c.kind"#, | 401 | FROM kinds c WHERE k.name = c.kind"#, |
| 402 | - target.id as &ExamId, | 402 | + target.id.uuid(), |
| 403 | ) | 403 | ) |
| 404 | .execute(&mut *conn) | 404 | .execute(&mut *conn) |
| 405 | .await?; | 405 | .await?; |
| 406 | - sqlx::query!(r#"DELETE FROM exam_result WHERE exam = $1"#, target.id as &ExamId) | 406 | + sqlx::query!(r#"DELETE FROM exam_result WHERE exam = $1"#, target.id.uuid()) |
| 407 | .execute(&mut *conn) | 407 | .execute(&mut *conn) |
| 408 | .await?; | 408 | .await?; |
| 409 | - sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = $1"#, target.id as &ExamId) | 409 | + sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = $1"#, target.id.uuid()) |
| 410 | .execute(&mut *conn) | 410 | .execute(&mut *conn) |
| 411 | .await?; | 411 | .await?; |
| 412 | - sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = $1"#, target.id as &ExamId) | 412 | + sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = $1"#, target.id.uuid()) |
| 413 | .execute(&mut *conn) | 413 | .execute(&mut *conn) |
| 414 | .await?; | 414 | .await?; |
| 415 | - sqlx::query!(r#"DELETE FROM answer_image WHERE exam = $1"#, target.id as &ExamId) | 415 | + sqlx::query!(r#"DELETE FROM answer_image WHERE exam = $1"#, target.id.uuid()) |
| 416 | .execute(&mut *conn) | 416 | .execute(&mut *conn) |
| 417 | .await?; | 417 | .await?; |
| 418 | - sqlx::query!(r#"DELETE FROM question_image WHERE exam = $1"#, target.id as &ExamId) | 418 | + sqlx::query!(r#"DELETE FROM question_image WHERE exam = $1"#, target.id.uuid()) |
| 419 | .execute(&mut *conn) | 419 | .execute(&mut *conn) |
| 420 | .await?; | 420 | .await?; |
| 421 | // The cascaded questions give their subject references back, | 421 | // The cascaded questions give their subject references back, |
| @@ -428,16 +428,16 @@ pub async fn delete(db: &Database, target: Exam) -> Result<Deleted, AppError> { | |||
| 428 | GROUP BY subject) | 428 | GROUP BY subject) |
| 429 | UPDATE subject s SET exam_question_count = GREATEST(s.exam_question_count - c.n, 0) | 429 | UPDATE subject s SET exam_question_count = GREATEST(s.exam_question_count - c.n, 0) |
| 430 | FROM subs c WHERE s.id = c.subject"#, | 430 | FROM subs c WHERE s.id = c.subject"#, |
| 431 | - target.id as &ExamId, | 431 | + target.id.uuid(), |
| 432 | ) | 432 | ) |
| 433 | .execute(&mut *conn) | 433 | .execute(&mut *conn) |
| 434 | .await?; | 434 | .await?; |
| 435 | - sqlx::query!(r#"DELETE FROM exam_question WHERE exam = $1"#, target.id as &ExamId) | 435 | + sqlx::query!(r#"DELETE FROM exam_question WHERE exam = $1"#, target.id.uuid()) |
| 436 | .execute(&mut *conn) | 436 | .execute(&mut *conn) |
| 437 | .await?; | 437 | .await?; |
| 438 | sqlx::query!( | 438 | sqlx::query!( |
| 439 | r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = $1"#, | 439 | r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = $1"#, |
| 440 | - target.id as &ExamId, | 440 | + target.id.uuid(), |
| 441 | ) | 441 | ) |
| 442 | .execute(&mut *conn) | 442 | .execute(&mut *conn) |
| 443 | .await?; | 443 | .await?; |
| @@ -447,13 +447,13 @@ pub async fn delete(db: &Database, target: Exam) -> Result<Deleted, AppError> { | |||
| 447 | RETURNING id AS "id: ExamId", creator AS "creator: UserId", | 447 | RETURNING id AS "id: ExamId", creator AS "creator: UserId", |
| 448 | course AS "course: CourseId", title AS "title: ExamTitle", | 448 | course AS "course: CourseId", title AS "title: ExamTitle", |
| 449 | description AS "description: ExamDescription", | 449 | description AS "description: ExamDescription", |
| 450 | - kind AS "kind: ExamKind", mode AS "mode: Option<ExamMode>", | 450 | + kind AS "kind: ExamKind", mode AS "mode: ExamMode", |
| 451 | - starts_at AS "starts_at: Option<Timestamp>", | 451 | + starts_at AS "starts_at: Timestamp", |
| 452 | - ends_at AS "ends_at: Option<Timestamp>", | 452 | + ends_at AS "ends_at: Timestamp", |
| 453 | - duration_ms AS "duration_ms: Option<ExamDuration>", | 453 | + duration_ms AS "duration_ms: ExamDuration", |
| 454 | max_attempts AS "max_attempts: ExamAttemptLimit", | 454 | max_attempts AS "max_attempts: ExamAttemptLimit", |
| 455 | allow_rejoin, allow_review, draft"#, | 455 | allow_rejoin, allow_review, draft"#, |
| 456 | - target.id as &ExamId, | 456 | + target.id.uuid(), |
| 457 | ) | 457 | ) |
| 458 | .fetch_optional(&mut *conn) | 458 | .fetch_optional(&mut *conn) |
| 459 | .await?; | 459 | .await?; |
src/db/exam_answer.rsmodified+27 -27
| @@ -76,7 +76,7 @@ pub async fn save( | |||
| 76 | // child insert whose parent is gone refuses itself — which is what | 76 | // child insert whose parent is gone refuses itself — which is what |
| 77 | // retired the bump-and-restore this used to ride on. | 77 | // retired the bump-and-restore this used to ride on. |
| 78 | tx_with_retry(db, false, async |conn| { | 78 | tx_with_retry(db, false, async |conn| { |
| 79 | - save_in(conn, question, user, seq, selected, text).await | 79 | + save_in(conn, question, user, seq, selected.clone(), text.clone()).await |
| 80 | }) | 80 | }) |
| 81 | .await | 81 | .await |
| 82 | } | 82 | } |
| @@ -93,7 +93,7 @@ pub(crate) async fn save_in( | |||
| 93 | ) -> Result<ExamAnswer, AppError> { | 93 | ) -> Result<ExamAnswer, AppError> { |
| 94 | let touched = sqlx::query!( | 94 | let touched = sqlx::query!( |
| 95 | r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, | 95 | r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, |
| 96 | - question.get_exam() as &ExamId, | 96 | + question.get_exam().uuid(), |
| 97 | ) | 97 | ) |
| 98 | .fetch_optional(&mut *conn) | 98 | .fetch_optional(&mut *conn) |
| 99 | .await?; | 99 | .await?; |
| @@ -110,16 +110,16 @@ pub(crate) async fn save_in( | |||
| 110 | updated_at = EXCLUDED.updated_at | 110 | updated_at = EXCLUDED.updated_at |
| 111 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", | 111 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 112 | app_user AS "user: UserId", seq, | 112 | app_user AS "user: UserId", seq, |
| 113 | - selected AS "selected: Option<ChoiceId>", | 113 | + selected AS "selected: ChoiceId", |
| 114 | - text AS "text: Option<AnswerText>", | 114 | + text AS "text: AnswerText", |
| 115 | updated_at AS "updated_at: Timestamp""#, | 115 | updated_at AS "updated_at: Timestamp""#, |
| 116 | - question.get_exam() as &ExamId, | 116 | + question.get_exam().uuid(), |
| 117 | - question.get_id() as &ExamQuestionId, | 117 | + question.get_id().uuid(), |
| 118 | - user as &UserId, | 118 | + user.uuid(), |
| 119 | + selected.as_ref().map(ChoiceId::as_str), | ||
| 120 | + text.as_ref().map(AnswerText::as_str), | ||
| 121 | + now.as_millis(), | ||
| 119 | seq, | 122 | seq, |
| 120 | - selected, | ||
| 121 | - text, | ||
| 122 | - now, | ||
| 123 | ) | 123 | ) |
| 124 | .fetch_one(&mut *conn) | 124 | .fetch_one(&mut *conn) |
| 125 | .await | 125 | .await |
| @@ -136,13 +136,13 @@ pub async fn read( | |||
| 136 | ExamAnswer, | 136 | ExamAnswer, |
| 137 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", | 137 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 138 | app_user AS "user: UserId", seq, | 138 | app_user AS "user: UserId", seq, |
| 139 | - selected AS "selected: Option<ChoiceId>", | 139 | + selected AS "selected: ChoiceId", |
| 140 | - text AS "text: Option<AnswerText>", | 140 | + text AS "text: AnswerText", |
| 141 | updated_at AS "updated_at: Timestamp" | 141 | updated_at AS "updated_at: Timestamp" |
| 142 | FROM exam_answer | 142 | FROM exam_answer |
| 143 | WHERE question = $1 AND app_user = $2 AND seq = $3"#, | 143 | WHERE question = $1 AND app_user = $2 AND seq = $3"#, |
| 144 | - question as &ExamQuestionId, | 144 | + question.uuid(), |
| 145 | - user as &UserId, | 145 | + user.uuid(), |
| 146 | seq, | 146 | seq, |
| 147 | ) | 147 | ) |
| 148 | .fetch_optional(db) | 148 | .fetch_optional(db) |
| @@ -158,8 +158,8 @@ pub async fn delete( | |||
| 158 | ) -> Result<(), AppError> { | 158 | ) -> Result<(), AppError> { |
| 159 | sqlx::query!( | 159 | sqlx::query!( |
| 160 | r#"DELETE FROM exam_answer WHERE question = $1 AND app_user = $2 AND seq = $3"#, | 160 | r#"DELETE FROM exam_answer WHERE question = $1 AND app_user = $2 AND seq = $3"#, |
| 161 | - question as &ExamQuestionId, | 161 | + question.uuid(), |
| 162 | - user as &UserId, | 162 | + user.uuid(), |
| 163 | seq, | 163 | seq, |
| 164 | ) | 164 | ) |
| 165 | .execute(db) | 165 | .execute(db) |
| @@ -180,14 +180,14 @@ pub async fn list_for_exam_user( | |||
| 180 | ExamAnswer, | 180 | ExamAnswer, |
| 181 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", | 181 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 182 | app_user AS "user: UserId", seq, | 182 | app_user AS "user: UserId", seq, |
| 183 | - selected AS "selected: Option<ChoiceId>", | 183 | + selected AS "selected: ChoiceId", |
| 184 | - text AS "text: Option<AnswerText>", | 184 | + text AS "text: AnswerText", |
| 185 | updated_at AS "updated_at: Timestamp" | 185 | updated_at AS "updated_at: Timestamp" |
| 186 | FROM exam_answer | 186 | FROM exam_answer |
| 187 | WHERE exam = $1 AND app_user = $2 AND seq = $3 | 187 | WHERE exam = $1 AND app_user = $2 AND seq = $3 |
| 188 | ORDER BY question ASC"#, | 188 | ORDER BY question ASC"#, |
| 189 | - exam as &ExamId, | 189 | + exam.uuid(), |
| 190 | - user as &UserId, | 190 | + user.uuid(), |
| 191 | seq, | 191 | seq, |
| 192 | ) | 192 | ) |
| 193 | .fetch_all(db) | 193 | .fetch_all(db) |
| @@ -204,8 +204,8 @@ pub async fn list_seqs_for_user( | |||
| 204 | let rows = sqlx::query!( | 204 | let rows = sqlx::query!( |
| 205 | r#"SELECT DISTINCT seq FROM exam_answer | 205 | r#"SELECT DISTINCT seq FROM exam_answer |
| 206 | WHERE exam = $1 AND app_user = $2 ORDER BY seq ASC"#, | 206 | WHERE exam = $1 AND app_user = $2 ORDER BY seq ASC"#, |
| 207 | - exam as &ExamId, | 207 | + exam.uuid(), |
| 208 | - user as &UserId, | 208 | + user.uuid(), |
| 209 | ) | 209 | ) |
| 210 | .fetch_all(db) | 210 | .fetch_all(db) |
| 211 | .await?; | 211 | .await?; |
| @@ -218,11 +218,11 @@ pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamAnswe | |||
| 218 | ExamAnswer, | 218 | ExamAnswer, |
| 219 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", | 219 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 220 | app_user AS "user: UserId", seq, | 220 | app_user AS "user: UserId", seq, |
| 221 | - selected AS "selected: Option<ChoiceId>", | 221 | + selected AS "selected: ChoiceId", |
| 222 | - text AS "text: Option<AnswerText>", | 222 | + text AS "text: AnswerText", |
| 223 | updated_at AS "updated_at: Timestamp" | 223 | updated_at AS "updated_at: Timestamp" |
| 224 | FROM exam_answer WHERE exam = $1 ORDER BY question ASC"#, | 224 | FROM exam_answer WHERE exam = $1 ORDER BY question ASC"#, |
| 225 | - exam as &ExamId, | 225 | + exam.uuid(), |
| 226 | ) | 226 | ) |
| 227 | .fetch_all(db) | 227 | .fetch_all(db) |
| 228 | .await?) | 228 | .await?) |
| @@ -237,8 +237,8 @@ pub async fn delete_for_exam_user( | |||
| 237 | ) -> Result<(), AppError> { | 237 | ) -> Result<(), AppError> { |
| 238 | sqlx::query!( | 238 | sqlx::query!( |
| 239 | r#"DELETE FROM exam_answer WHERE exam = $1 AND app_user = $2"#, | 239 | r#"DELETE FROM exam_answer WHERE exam = $1 AND app_user = $2"#, |
| 240 | - exam as &ExamId, | 240 | + exam.uuid(), |
| 241 | - user as &UserId, | 241 | + user.uuid(), |
| 242 | ) | 242 | ) |
| 243 | .execute(db) | 243 | .execute(db) |
| 244 | .await?; | 244 | .await?; |
src/db/exam_attempt.rsmodified+46 -46
| @@ -7,7 +7,7 @@ use sqlx::PgConnection; | |||
| 7 | 7 | ||
| 8 | use crate::database::{Database, tx_with_retry, unique_violation}; | 8 | use crate::database::{Database, tx_with_retry, unique_violation}; |
| 9 | use crate::db::cap::Claimed; | 9 | use crate::db::cap::Claimed; |
| 10 | -use crate::domain::exam::ExamId; | 10 | +use crate::domain::exam::{ExamId, ExamMode}; |
| 11 | use crate::domain::exam_attempt::{ExamAttempt, ExamAttemptId}; | 11 | use crate::domain::exam_attempt::{ExamAttempt, ExamAttemptId}; |
| 12 | use crate::domain::timestamp::Timestamp; | 12 | use crate::domain::timestamp::Timestamp; |
| 13 | use crate::domain::user::UserId; | 13 | use crate::domain::user::UserId; |
| @@ -37,7 +37,7 @@ fn frozen_error() -> AppError { | |||
| 37 | pub(crate) async fn freeze_gate(conn: &mut PgConnection, exam: &ExamId) -> Result<(), AppError> { | 37 | pub(crate) async fn freeze_gate(conn: &mut PgConnection, exam: &ExamId) -> Result<(), AppError> { |
| 38 | let row = sqlx::query!( | 38 | let row = sqlx::query!( |
| 39 | r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, | 39 | r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, |
| 40 | - exam as &ExamId, | 40 | + exam.uuid(), |
| 41 | ) | 41 | ) |
| 42 | .fetch_optional(&mut *conn) | 42 | .fetch_optional(&mut *conn) |
| 43 | .await?; | 43 | .await?; |
| @@ -46,11 +46,11 @@ pub(crate) async fn freeze_gate(conn: &mut PgConnection, exam: &ExamId) -> Resul | |||
| 46 | } | 46 | } |
| 47 | let sat = sqlx::query!( | 47 | let sat = sqlx::query!( |
| 48 | r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat"#, | 48 | r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat"#, |
| 49 | - exam as &ExamId, | 49 | + exam.uuid(), |
| 50 | ) | 50 | ) |
| 51 | .fetch_one(&mut *conn) | 51 | .fetch_one(&mut *conn) |
| 52 | .await?; | 52 | .await?; |
| 53 | - if sat.sat { | 53 | + if sat.sat.unwrap_or(false) { |
| 54 | return Err(frozen_error()); | 54 | return Err(frozen_error()); |
| 55 | } | 55 | } |
| 56 | Ok(()) | 56 | Ok(()) |
| @@ -73,11 +73,11 @@ pub async fn finish(db: &Database, attempt: ExamAttempt) -> Result<ExamAttempt, | |||
| 73 | WHERE exam = $2 AND app_user = $3 AND seq = $4 | 73 | WHERE exam = $2 AND app_user = $3 AND seq = $4 |
| 74 | RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, | 74 | RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, |
| 75 | started_at AS "started_at: Timestamp", | 75 | started_at AS "started_at: Timestamp", |
| 76 | - finished_at AS "finished_at: Option<Timestamp>", | 76 | + finished_at AS "finished_at: Timestamp", |
| 77 | - left_at AS "left_at: Option<Timestamp>""#, | 77 | + left_at AS "left_at: Timestamp""#, |
| 78 | - Timestamp::now(), | 78 | + Timestamp::now().as_millis(), |
| 79 | - id.exam, | 79 | + id.exam.uuid(), |
| 80 | - id.user, | 80 | + id.user.uuid(), |
| 81 | id.seq, | 81 | id.seq, |
| 82 | ) | 82 | ) |
| 83 | .fetch_optional(db) | 83 | .fetch_optional(db) |
| @@ -106,11 +106,11 @@ pub async fn set_left( | |||
| 106 | WHERE exam = $2 AND app_user = $3 AND seq = $4 | 106 | WHERE exam = $2 AND app_user = $3 AND seq = $4 |
| 107 | RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, | 107 | RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, |
| 108 | started_at AS "started_at: Timestamp", | 108 | started_at AS "started_at: Timestamp", |
| 109 | - finished_at AS "finished_at: Option<Timestamp>", | 109 | + finished_at AS "finished_at: Timestamp", |
| 110 | - left_at AS "left_at: Option<Timestamp>""#, | 110 | + left_at AS "left_at: Timestamp""#, |
| 111 | - left_at, | 111 | + left_at.map(|at| at.as_millis()), |
| 112 | - id.exam, | 112 | + id.exam.uuid(), |
| 113 | - id.user, | 113 | + id.user.uuid(), |
| 114 | id.seq, | 114 | id.seq, |
| 115 | ) | 115 | ) |
| 116 | .fetch_optional(db) | 116 | .fetch_optional(db) |
| @@ -139,10 +139,10 @@ pub async fn stamp_left_if_running( | |||
| 139 | AND a.left_at IS NULL AND a.finished_at IS NULL | 139 | AND a.left_at IS NULL AND a.finished_at IS NULL |
| 140 | AND (e.duration_ms IS NULL OR $4 < a.started_at + e.duration_ms) | 140 | AND (e.duration_ms IS NULL OR $4 < a.started_at + e.duration_ms) |
| 141 | AND (e.duration_ms IS NOT NULL OR e.ends_at IS NULL OR $4 < e.ends_at)"#, | 141 | AND (e.duration_ms IS NOT NULL OR e.ends_at IS NULL OR $4 < e.ends_at)"#, |
| 142 | - attempt_id.exam, | 142 | + attempt_id.exam.uuid(), |
| 143 | - attempt_id.user, | 143 | + attempt_id.user.uuid(), |
| 144 | attempt_id.seq, | 144 | attempt_id.seq, |
| 145 | - now, | 145 | + now.as_millis(), |
| 146 | ) | 146 | ) |
| 147 | .execute(db) | 147 | .execute(db) |
| 148 | .await?; | 148 | .await?; |
| @@ -156,12 +156,12 @@ pub async fn read(db: &Database, id: &ExamAttemptId) -> Result<Option<ExamAttemp | |||
| 156 | ExamAttempt, | 156 | ExamAttempt, |
| 157 | r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, | 157 | r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, |
| 158 | started_at AS "started_at: Timestamp", | 158 | started_at AS "started_at: Timestamp", |
| 159 | - finished_at AS "finished_at: Option<Timestamp>", | 159 | + finished_at AS "finished_at: Timestamp", |
| 160 | - left_at AS "left_at: Option<Timestamp>" | 160 | + left_at AS "left_at: Timestamp" |
| 161 | FROM exam_attempt | 161 | FROM exam_attempt |
| 162 | WHERE exam = $1 AND app_user = $2 AND seq = $3"#, | 162 | WHERE exam = $1 AND app_user = $2 AND seq = $3"#, |
| 163 | - id.exam, | 163 | + id.exam.uuid(), |
| 164 | - id.user, | 164 | + id.user.uuid(), |
| 165 | id.seq, | 165 | id.seq, |
| 166 | ) | 166 | ) |
| 167 | .fetch_optional(db) | 167 | .fetch_optional(db) |
| @@ -179,14 +179,14 @@ pub async fn read_latest_for_user( | |||
| 179 | ExamAttempt, | 179 | ExamAttempt, |
| 180 | r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, | 180 | r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, |
| 181 | started_at AS "started_at: Timestamp", | 181 | started_at AS "started_at: Timestamp", |
| 182 | - finished_at AS "finished_at: Option<Timestamp>", | 182 | + finished_at AS "finished_at: Timestamp", |
| 183 | - left_at AS "left_at: Option<Timestamp>" | 183 | + left_at AS "left_at: Timestamp" |
| 184 | FROM exam_attempt | 184 | FROM exam_attempt |
| 185 | WHERE exam = $1 AND app_user = $2 | 185 | WHERE exam = $1 AND app_user = $2 |
| 186 | ORDER BY seq DESC | 186 | ORDER BY seq DESC |
| 187 | LIMIT 1"#, | 187 | LIMIT 1"#, |
| 188 | - exam as &ExamId, | 188 | + exam.uuid(), |
| 189 | - user as &UserId, | 189 | + user.uuid(), |
| 190 | ) | 190 | ) |
| 191 | .fetch_optional(db) | 191 | .fetch_optional(db) |
| 192 | .await?) | 192 | .await?) |
| @@ -202,13 +202,13 @@ pub async fn list_for_user( | |||
| 202 | ExamAttempt, | 202 | ExamAttempt, |
| 203 | r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, | 203 | r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, |
| 204 | started_at AS "started_at: Timestamp", | 204 | started_at AS "started_at: Timestamp", |
| 205 | - finished_at AS "finished_at: Option<Timestamp>", | 205 | + finished_at AS "finished_at: Timestamp", |
| 206 | - left_at AS "left_at: Option<Timestamp>" | 206 | + left_at AS "left_at: Timestamp" |
| 207 | FROM exam_attempt | 207 | FROM exam_attempt |
| 208 | WHERE exam = $1 AND app_user = $2 | 208 | WHERE exam = $1 AND app_user = $2 |
| 209 | ORDER BY seq DESC"#, | 209 | ORDER BY seq DESC"#, |
| 210 | - exam as &ExamId, | 210 | + exam.uuid(), |
| 211 | - user as &UserId, | 211 | + user.uuid(), |
| 212 | ) | 212 | ) |
| 213 | .fetch_all(db) | 213 | .fetch_all(db) |
| 214 | .await?) | 214 | .await?) |
| @@ -226,12 +226,12 @@ pub async fn list_unfinished_for_user( | |||
| 226 | ExamAttempt, | 226 | ExamAttempt, |
| 227 | r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, | 227 | r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, |
| 228 | started_at AS "started_at: Timestamp", | 228 | started_at AS "started_at: Timestamp", |
| 229 | - finished_at AS "finished_at: Option<Timestamp>", | 229 | + finished_at AS "finished_at: Timestamp", |
| 230 | - left_at AS "left_at: Option<Timestamp>" | 230 | + left_at AS "left_at: Timestamp" |
| 231 | FROM exam_attempt | 231 | FROM exam_attempt |
| 232 | WHERE app_user = $1 AND finished_at IS NULL | 232 | WHERE app_user = $1 AND finished_at IS NULL |
| 233 | ORDER BY started_at, exam"#, | 233 | ORDER BY started_at, exam"#, |
| 234 | - user as &UserId, | 234 | + user.uuid(), |
| 235 | ) | 235 | ) |
| 236 | .fetch_all(db) | 236 | .fetch_all(db) |
| 237 | .await?) | 237 | .await?) |
| @@ -242,12 +242,12 @@ pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamAttem | |||
| 242 | ExamAttempt, | 242 | ExamAttempt, |
| 243 | r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, | 243 | r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq, |
| 244 | started_at AS "started_at: Timestamp", | 244 | started_at AS "started_at: Timestamp", |
| 245 | - finished_at AS "finished_at: Option<Timestamp>", | 245 | + finished_at AS "finished_at: Timestamp", |
| 246 | - left_at AS "left_at: Option<Timestamp>" | 246 | + left_at AS "left_at: Timestamp" |
| 247 | FROM exam_attempt | 247 | FROM exam_attempt |
| 248 | WHERE exam = $1 | 248 | WHERE exam = $1 |
| 249 | ORDER BY started_at DESC, seq DESC"#, | 249 | ORDER BY started_at DESC, seq DESC"#, |
| 250 | - exam as &ExamId, | 250 | + exam.uuid(), |
| 251 | ) | 251 | ) |
| 252 | .fetch_all(db) | 252 | .fetch_all(db) |
| 253 | .await?) | 253 | .await?) |
| @@ -258,11 +258,11 @@ pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamAttem | |||
| 258 | pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result<bool, AppError> { | 258 | pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result<bool, AppError> { |
| 259 | let row = sqlx::query!( | 259 | let row = sqlx::query!( |
| 260 | r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat"#, | 260 | r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat"#, |
| 261 | - exam as &ExamId, | 261 | + exam.uuid(), |
| 262 | ) | 262 | ) |
| 263 | .fetch_one(db) | 263 | .fetch_one(db) |
| 264 | .await?; | 264 | .await?; |
| 265 | - Ok(row.sat) | 265 | + Ok(row.sat.unwrap_or(false)) |
| 266 | } | 266 | } |
| 267 | 267 | ||
| 268 | /// The sitting-create guard: the exam row locked `FOR UPDATE` and | 268 | /// The sitting-create guard: the exam row locked `FOR UPDATE` and |
| @@ -280,11 +280,11 @@ pub(crate) async fn guard_start( | |||
| 280 | now: Timestamp, | 280 | now: Timestamp, |
| 281 | ) -> Result<(), AppError> { | 281 | ) -> Result<(), AppError> { |
| 282 | let row = sqlx::query!( | 282 | let row = sqlx::query!( |
| 283 | - r#"SELECT draft AS "draft: bool", mode AS "mode: Option<ExamMode>", | 283 | + r#"SELECT draft AS "draft: bool", mode AS "mode: ExamMode", |
| 284 | - starts_at AS "starts_at: Option<Timestamp>", | 284 | + starts_at AS "starts_at: Timestamp", |
| 285 | - ends_at AS "ends_at: Option<Timestamp>" | 285 | + ends_at AS "ends_at: Timestamp" |
| 286 | FROM exam WHERE id = $1 FOR UPDATE"#, | 286 | FROM exam WHERE id = $1 FOR UPDATE"#, |
| 287 | - exam as &ExamId, | 287 | + exam.uuid(), |
| 288 | ) | 288 | ) |
| 289 | .fetch_optional(&mut *conn) | 289 | .fetch_optional(&mut *conn) |
| 290 | .await?; | 290 | .await?; |
| @@ -336,13 +336,13 @@ pub(crate) async fn create_in( | |||
| 336 | SELECT $1, $2, $3, $5, NULL, NULL WHERE EXISTS (SELECT 1 FROM seat) | 336 | SELECT $1, $2, $3, $5, NULL, NULL WHERE EXISTS (SELECT 1 FROM seat) |
| 337 | RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, | 337 | RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, |
| 338 | started_at AS "started_at: Timestamp", | 338 | started_at AS "started_at: Timestamp", |
| 339 | - finished_at AS "finished_at: Option<Timestamp>", | 339 | + finished_at AS "finished_at: Timestamp", |
| 340 | - left_at AS "left_at: Option<Timestamp>""#, | 340 | + left_at AS "left_at: Timestamp""#, |
| 341 | - attempt.exam, | 341 | + attempt.exam.uuid(), |
| 342 | - attempt.user, | 342 | + attempt.user.uuid(), |
| 343 | attempt.seq, | 343 | attempt.seq, |
| 344 | bump, | 344 | bump, |
| 345 | - attempt.started_at, | 345 | + attempt.started_at.as_millis(), |
| 346 | ) | 346 | ) |
| 347 | .fetch_optional(&mut *conn) | 347 | .fetch_optional(&mut *conn) |
| 348 | .await; | 348 | .await; |
src/db/exam_question.rsmodified+64 -53
| @@ -14,7 +14,8 @@ use crate::db::page::{PagedList, Param}; | |||
| 14 | use crate::domain::bank_question::BankQuestionId; | 14 | use crate::domain::bank_question::BankQuestionId; |
| 15 | use crate::domain::exam::ExamId; | 15 | use crate::domain::exam::ExamId; |
| 16 | use crate::domain::exam_question::{ | 16 | use crate::domain::exam_question::{ |
| 17 | - Choice, ExamQuestion, ExamQuestionId, QuestionPoints, QuestionSpec, QuestionText, | 17 | + Choice, ChoiceId, ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, |
| 18 | + QuestionText, | ||
| 18 | }; | 19 | }; |
| 19 | use crate::domain::subject::SubjectId; | 20 | use crate::domain::subject::SubjectId; |
| 20 | use crate::error::{AppError, ValidationError}; | 21 | use crate::error::{AppError, ValidationError}; |
| @@ -29,6 +30,13 @@ fn dead_subject() -> AppError { | |||
| 29 | }) | 30 | }) |
| 30 | } | 31 | } |
| 31 | 32 | ||
| 33 | +/// The `choices` JSONB bind as the macros type the parameter — a | ||
| 34 | +/// `serde_json::Value`. A `Choice` is two plain strings: serializing one | ||
| 35 | +/// cannot fail. | ||
| 36 | +fn choices_as_value(choices: &[Choice]) -> serde_json::Value { | ||
| 37 | + serde_json::to_value(choices).expect("Choice serialization cannot fail") | ||
| 38 | +} | ||
| 39 | + | ||
| 32 | pub async fn create( | 40 | pub async fn create( |
| 33 | db: &Database, | 41 | db: &Database, |
| 34 | exam: &ExamId, | 42 | exam: &ExamId, |
| @@ -71,7 +79,7 @@ async fn insert( | |||
| 71 | text, | 79 | text, |
| 72 | points, | 80 | points, |
| 73 | kind: spec.kind, | 81 | kind: spec.kind, |
| 74 | - choices: spec.choices, | 82 | + choices: spec.choices.map(Json), |
| 75 | correct: spec.correct, | 83 | correct: spec.correct, |
| 76 | from_bank, | 84 | from_bank, |
| 77 | // An insert never banks anything: only a to-bank save writes this. | 85 | // An insert never banks anything: only a to-bank save writes this. |
| @@ -115,19 +123,22 @@ async fn claim_subject_and_insert( | |||
| 115 | RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", | 123 | RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", |
| 116 | subject AS "subject: SubjectId", text AS "text: QuestionText", | 124 | subject AS "subject: SubjectId", text AS "text: QuestionText", |
| 117 | kind AS "kind: QuestionKind", points AS "points: QuestionPoints", | 125 | kind AS "kind: QuestionKind", points AS "points: QuestionPoints", |
| 118 | - choices AS "choices: Option<Json<Vec<Choice>>>", | 126 | + choices AS "choices: Json<Vec<Choice>>", |
| 119 | - correct AS "correct: Option<ChoiceId>", | 127 | + correct AS "correct: ChoiceId", |
| 120 | - from_bank AS "from_bank: Option<BankQuestionId>", | 128 | + from_bank AS "from_bank: BankQuestionId", |
| 121 | - banked_as AS "banked_as: Option<BankQuestionId>""#, | 129 | + banked_as AS "banked_as: BankQuestionId""#, |
| 122 | - question.subject, | 130 | + question.subject.uuid(), |
| 123 | - question.id, | 131 | + question.id.uuid(), |
| 124 | - question.exam, | 132 | + question.exam.uuid(), |
| 125 | - question.text, | 133 | + question.text.as_str(), |
| 126 | - question.kind, | 134 | + question.kind.as_str(), |
| 127 | - question.points, | 135 | + question.points.as_i64(), |
| 128 | - question.choices, | 136 | + question |
| 129 | - question.correct, | 137 | + .choices |
| 130 | - question.from_bank, | 138 | + .as_ref() |
| 139 | + .map(|json| choices_as_value(&json.0)), | ||
| 140 | + question.correct.as_ref().map(ChoiceId::as_str), | ||
| 141 | + question.from_bank.as_ref().map(BankQuestionId::uuid), | ||
| 131 | ) | 142 | ) |
| 132 | .fetch_optional(&mut *conn) | 143 | .fetch_optional(&mut *conn) |
| 133 | .await?; | 144 | .await?; |
| @@ -140,12 +151,12 @@ pub async fn read(db: &Database, id: &ExamQuestionId) -> Result<Option<ExamQuest | |||
| 140 | r#"SELECT id AS "id: ExamQuestionId", exam AS "exam: ExamId", | 151 | r#"SELECT id AS "id: ExamQuestionId", exam AS "exam: ExamId", |
| 141 | subject AS "subject: SubjectId", text AS "text: QuestionText", | 152 | subject AS "subject: SubjectId", text AS "text: QuestionText", |
| 142 | kind AS "kind: QuestionKind", points AS "points: QuestionPoints", | 153 | kind AS "kind: QuestionKind", points AS "points: QuestionPoints", |
| 143 | - choices AS "choices: Option<Json<Vec<Choice>>>", | 154 | + choices AS "choices: Json<Vec<Choice>>", |
| 144 | - correct AS "correct: Option<ChoiceId>", | 155 | + correct AS "correct: ChoiceId", |
| 145 | - from_bank AS "from_bank: Option<BankQuestionId>", | 156 | + from_bank AS "from_bank: BankQuestionId", |
| 146 | - banked_as AS "banked_as: Option<BankQuestionId>" | 157 | + banked_as AS "banked_as: BankQuestionId" |
| 147 | FROM exam_question WHERE id = $1"#, | 158 | FROM exam_question WHERE id = $1"#, |
| 148 | - id as &ExamQuestionId, | 159 | + id.uuid(), |
| 149 | ) | 160 | ) |
| 150 | .fetch_optional(db) | 161 | .fetch_optional(db) |
| 151 | .await?) | 162 | .await?) |
| @@ -204,8 +215,8 @@ pub async fn list_shared_with( | |||
| 204 | WHERE q.exam = $2 | 215 | WHERE q.exam = $2 |
| 205 | AND (q.from_bank IN (SELECT t FROM shared) | 216 | AND (q.from_bank IN (SELECT t FROM shared) |
| 206 | OR q.banked_as IN (SELECT t FROM shared))"#, | 217 | OR q.banked_as IN (SELECT t FROM shared))"#, |
| 207 | - live, | 218 | + &live, |
| 208 | - exam as &ExamId, | 219 | + exam.uuid(), |
| 209 | ) | 220 | ) |
| 210 | .fetch_all(db) | 221 | .fetch_all(db) |
| 211 | .await?; | 222 | .await?; |
| @@ -256,14 +267,14 @@ pub async fn update( | |||
| 256 | r#"UPDATE subject SET exam_question_count = | 267 | r#"UPDATE subject SET exam_question_count = |
| 257 | GREATEST(exam_question_count - 1, 0) | 268 | GREATEST(exam_question_count - 1, 0) |
| 258 | WHERE id = $1"#, | 269 | WHERE id = $1"#, |
| 259 | - previous as &SubjectId, | 270 | + previous.uuid(), |
| 260 | ) | 271 | ) |
| 261 | .execute(&mut *conn) | 272 | .execute(&mut *conn) |
| 262 | .await?; | 273 | .await?; |
| 263 | let claimed = sqlx::query!( | 274 | let claimed = sqlx::query!( |
| 264 | r#"UPDATE subject SET exam_question_count = subject.exam_question_count + 1 | 275 | r#"UPDATE subject SET exam_question_count = subject.exam_question_count + 1 |
| 265 | - WHERE id = $1 RETURNING 1"#, | 276 | + WHERE id = $1 RETURNING 1 AS n"#, |
| 266 | - next as &SubjectId, | 277 | + next.uuid(), |
| 267 | ) | 278 | ) |
| 268 | .fetch_optional(&mut *conn) | 279 | .fetch_optional(&mut *conn) |
| 269 | .await?; | 280 | .await?; |
| @@ -285,18 +296,18 @@ pub async fn update( | |||
| 285 | RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", | 296 | RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", |
| 286 | subject AS "subject: SubjectId", text AS "text: QuestionText", | 297 | subject AS "subject: SubjectId", text AS "text: QuestionText", |
| 287 | kind AS "kind: QuestionKind", points AS "points: QuestionPoints", | 298 | kind AS "kind: QuestionKind", points AS "points: QuestionPoints", |
| 288 | - choices AS "choices: Option<Json<Vec<Choice>>>", | 299 | + choices AS "choices: Json<Vec<Choice>>", |
| 289 | - correct AS "correct: Option<ChoiceId>", | 300 | + correct AS "correct: ChoiceId", |
| 290 | - from_bank AS "from_bank: Option<BankQuestionId>", | 301 | + from_bank AS "from_bank: BankQuestionId", |
| 291 | - banked_as AS "banked_as: Option<BankQuestionId>""#, | 302 | + banked_as AS "banked_as: BankQuestionId""#, |
| 292 | - question.id as &ExamQuestionId, | 303 | + question.id.uuid(), |
| 293 | - subject, | 304 | + subject.uuid(), |
| 294 | - text, | 305 | + text.as_str(), |
| 295 | - points, | 306 | + points.as_i64(), |
| 296 | - spec.kind, | 307 | + spec.kind.as_str(), |
| 297 | - spec.choices, | 308 | + spec.choices.as_deref().map(choices_as_value), |
| 298 | - spec.correct, | 309 | + spec.correct.as_ref().map(ChoiceId::as_str), |
| 299 | - question.subject as &SubjectId, | 310 | + question.subject.uuid(), |
| 300 | ) | 311 | ) |
| 301 | .fetch_optional(&mut *conn) | 312 | .fetch_optional(&mut *conn) |
| 302 | .await?; | 313 | .await?; |
| @@ -307,11 +318,11 @@ pub async fn update( | |||
| 307 | // which is the 409. | 318 | // which is the 409. |
| 308 | let live = sqlx::query!( | 319 | let live = sqlx::query!( |
| 309 | r#"SELECT EXISTS(SELECT 1 FROM exam_question WHERE id = $1) AS live"#, | 320 | r#"SELECT EXISTS(SELECT 1 FROM exam_question WHERE id = $1) AS live"#, |
| 310 | - question.id as &ExamQuestionId, | 321 | + question.id.uuid(), |
| 311 | ) | 322 | ) |
| 312 | .fetch_one(&mut *conn) | 323 | .fetch_one(&mut *conn) |
| 313 | .await?; | 324 | .await?; |
| 314 | - if !live.live { | 325 | + if !live.live.unwrap_or(false) { |
| 315 | return Err(AppError::NotFound); | 326 | return Err(AppError::NotFound); |
| 316 | } | 327 | } |
| 317 | return Err(AppError::Conflict( | 328 | return Err(AppError::Conflict( |
| @@ -346,12 +357,12 @@ pub async fn link_banked_as( | |||
| 346 | RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", | 357 | RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", |
| 347 | subject AS "subject: SubjectId", text AS "text: QuestionText", | 358 | subject AS "subject: SubjectId", text AS "text: QuestionText", |
| 348 | kind AS "kind: QuestionKind", points AS "points: QuestionPoints", | 359 | kind AS "kind: QuestionKind", points AS "points: QuestionPoints", |
| 349 | - choices AS "choices: Option<Json<Vec<Choice>>>", | 360 | + choices AS "choices: Json<Vec<Choice>>", |
| 350 | - correct AS "correct: Option<ChoiceId>", | 361 | + correct AS "correct: ChoiceId", |
| 351 | - from_bank AS "from_bank: Option<BankQuestionId>", | 362 | + from_bank AS "from_bank: BankQuestionId", |
| 352 | - banked_as AS "banked_as: Option<BankQuestionId>""#, | 363 | + banked_as AS "banked_as: BankQuestionId""#, |
| 353 | - question.id as &ExamQuestionId, | 364 | + question.id.uuid(), |
| 354 | - template as &BankQuestionId, | 365 | + template.uuid(), |
| 355 | ) | 366 | ) |
| 356 | .fetch_optional(db) | 367 | .fetch_optional(db) |
| 357 | .await?; | 368 | .await?; |
| @@ -369,13 +380,13 @@ pub async fn delete(db: &Database, question: ExamQuestion) -> Result<ExamQuestio | |||
| 369 | freeze_gate(conn, &question.exam).await?; | 380 | freeze_gate(conn, &question.exam).await?; |
| 370 | sqlx::query!( | 381 | sqlx::query!( |
| 371 | r#"DELETE FROM exam_answer WHERE question = $1"#, | 382 | r#"DELETE FROM exam_answer WHERE question = $1"#, |
| 372 | - question.id as &ExamQuestionId, | 383 | + question.id.uuid(), |
| 373 | ) | 384 | ) |
| 374 | .execute(&mut *conn) | 385 | .execute(&mut *conn) |
| 375 | .await?; | 386 | .await?; |
| 376 | sqlx::query!( | 387 | sqlx::query!( |
| 377 | r#"DELETE FROM question_image WHERE question = $1"#, | 388 | r#"DELETE FROM question_image WHERE question = $1"#, |
| 378 | - question.id as &ExamQuestionId, | 389 | + question.id.uuid(), |
| 379 | ) | 390 | ) |
| 380 | .execute(&mut *conn) | 391 | .execute(&mut *conn) |
| 381 | .await?; | 392 | .await?; |
| @@ -385,11 +396,11 @@ pub async fn delete(db: &Database, question: ExamQuestion) -> Result<ExamQuestio | |||
| 385 | RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", | 396 | RETURNING id AS "id: ExamQuestionId", exam AS "exam: ExamId", |
| 386 | subject AS "subject: SubjectId", text AS "text: QuestionText", | 397 | subject AS "subject: SubjectId", text AS "text: QuestionText", |
| 387 | kind AS "kind: QuestionKind", points AS "points: QuestionPoints", | 398 | kind AS "kind: QuestionKind", points AS "points: QuestionPoints", |
| 388 | - choices AS "choices: Option<Json<Vec<Choice>>>", | 399 | + choices AS "choices: Json<Vec<Choice>>", |
| 389 | - correct AS "correct: Option<ChoiceId>", | 400 | + correct AS "correct: ChoiceId", |
| 390 | - from_bank AS "from_bank: Option<BankQuestionId>", | 401 | + from_bank AS "from_bank: BankQuestionId", |
| 391 | - banked_as AS "banked_as: Option<BankQuestionId>""#, | 402 | + banked_as AS "banked_as: BankQuestionId""#, |
| 392 | - question.id as &ExamQuestionId, | 403 | + question.id.uuid(), |
| 393 | ) | 404 | ) |
| 394 | .fetch_optional(&mut *conn) | 405 | .fetch_optional(&mut *conn) |
| 395 | .await?; | 406 | .await?; |
| @@ -401,7 +412,7 @@ pub async fn delete(db: &Database, question: ExamQuestion) -> Result<ExamQuestio | |||
| 401 | r#"UPDATE subject SET exam_question_count = | 412 | r#"UPDATE subject SET exam_question_count = |
| 402 | GREATEST(exam_question_count - 1, 0) | 413 | GREATEST(exam_question_count - 1, 0) |
| 403 | WHERE id = $1"#, | 414 | WHERE id = $1"#, |
| 404 | - deleted.subject as &SubjectId, | 415 | + deleted.subject.uuid(), |
| 405 | ) | 416 | ) |
| 406 | .execute(&mut *conn) | 417 | .execute(&mut *conn) |
| 407 | .await?; | 418 | .await?; |
src/db/exam_result.rsmodified+24 -24
| @@ -23,8 +23,8 @@ async fn find(db: &Database, exam: &ExamId, user: &UserId) -> Result<Option<Exam | |||
| 23 | mark AS "mark: Mark", graded_by AS "graded_by: UserId" | 23 | mark AS "mark: Mark", graded_by AS "graded_by: UserId" |
| 24 | FROM exam_result WHERE exam = $1 AND app_user = $2 | 24 | FROM exam_result WHERE exam = $1 AND app_user = $2 |
| 25 | ORDER BY seq DESC LIMIT 1"#, | 25 | ORDER BY seq DESC LIMIT 1"#, |
| 26 | - exam as &ExamId, | 26 | + exam.uuid(), |
| 27 | - user as &UserId, | 27 | + user.uuid(), |
| 28 | ) | 28 | ) |
| 29 | .fetch_optional(db) | 29 | .fetch_optional(db) |
| 30 | .await?) | 30 | .await?) |
| @@ -109,7 +109,7 @@ pub async fn grade( | |||
| 109 | tx_with_retry(db, false, async |conn| { | 109 | tx_with_retry(db, false, async |conn| { |
| 110 | let exam_row = sqlx::query!( | 110 | let exam_row = sqlx::query!( |
| 111 | r#"SELECT draft AS "draft: bool" FROM exam WHERE id = $1 FOR UPDATE"#, | 111 | r#"SELECT draft AS "draft: bool" FROM exam WHERE id = $1 FOR UPDATE"#, |
| 112 | - exam as &ExamId, | 112 | + exam.uuid(), |
| 113 | ) | 113 | ) |
| 114 | .fetch_optional(&mut *conn) | 114 | .fetch_optional(&mut *conn) |
| 115 | .await?; | 115 | .await?; |
| @@ -122,8 +122,8 @@ pub async fn grade( | |||
| 122 | let before = sqlx::query!( | 122 | let before = sqlx::query!( |
| 123 | r#"SELECT mark AS "mark: Mark" FROM exam_result | 123 | r#"SELECT mark AS "mark: Mark" FROM exam_result |
| 124 | WHERE exam = $1 AND app_user = $2 AND seq = $3"#, | 124 | WHERE exam = $1 AND app_user = $2 AND seq = $3"#, |
| 125 | - exam as &ExamId, | 125 | + exam.uuid(), |
| 126 | - user as &UserId, | 126 | + user.uuid(), |
| 127 | seq, | 127 | seq, |
| 128 | ) | 128 | ) |
| 129 | .fetch_optional(&mut *conn) | 129 | .fetch_optional(&mut *conn) |
| @@ -137,7 +137,7 @@ pub async fn grade( | |||
| 137 | let claimed = sqlx::query!( | 137 | let claimed = sqlx::query!( |
| 138 | r#"UPDATE kind_ref SET count = kind_ref.count + 1 | 138 | r#"UPDATE kind_ref SET count = kind_ref.count + 1 |
| 139 | WHERE name = $1 AND retired = false | 139 | WHERE name = $1 AND retired = false |
| 140 | - RETURNING 1"#, | 140 | + RETURNING 1 AS n"#, |
| 141 | kind, | 141 | kind, |
| 142 | ) | 142 | ) |
| 143 | .fetch_optional(&mut *conn) | 143 | .fetch_optional(&mut *conn) |
| @@ -147,14 +147,14 @@ pub async fn grade( | |||
| 147 | } | 147 | } |
| 148 | sqlx::query!( | 148 | sqlx::query!( |
| 149 | r#"UPDATE exam SET result_count = exam.result_count + 1 WHERE id = $1"#, | 149 | r#"UPDATE exam SET result_count = exam.result_count + 1 WHERE id = $1"#, |
| 150 | - exam as &ExamId, | 150 | + exam.uuid(), |
| 151 | ) | 151 | ) |
| 152 | .execute(&mut *conn) | 152 | .execute(&mut *conn) |
| 153 | .await?; | 153 | .await?; |
| 154 | sqlx::query!( | 154 | sqlx::query!( |
| 155 | r#"UPDATE app_user SET marks_given_total = app_user.marks_given_total + 1 | 155 | r#"UPDATE app_user SET marks_given_total = app_user.marks_given_total + 1 |
| 156 | WHERE id = $1"#, | 156 | WHERE id = $1"#, |
| 157 | - graded_by as &UserId, | 157 | + graded_by.uuid(), |
| 158 | ) | 158 | ) |
| 159 | .execute(&mut *conn) | 159 | .execute(&mut *conn) |
| 160 | .await?; | 160 | .await?; |
| @@ -166,7 +166,7 @@ pub async fn grade( | |||
| 166 | r#"UPDATE app_user SET high_mark_total = | 166 | r#"UPDATE app_user SET high_mark_total = |
| 167 | GREATEST(high_mark_total + $2, 0) | 167 | GREATEST(high_mark_total + $2, 0) |
| 168 | WHERE id = $1"#, | 168 | WHERE id = $1"#, |
| 169 | - user as &UserId, | 169 | + user.uuid(), |
| 170 | high, | 170 | high, |
| 171 | ) | 171 | ) |
| 172 | .execute(&mut *conn) | 172 | .execute(&mut *conn) |
| @@ -180,11 +180,11 @@ pub async fn grade( | |||
| 180 | SET mark = EXCLUDED.mark, graded_by = EXCLUDED.graded_by | 180 | SET mark = EXCLUDED.mark, graded_by = EXCLUDED.graded_by |
| 181 | RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, | 181 | RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, |
| 182 | mark AS "mark: Mark", graded_by AS "graded_by: UserId""#, | 182 | mark AS "mark: Mark", graded_by AS "graded_by: UserId""#, |
| 183 | - exam as &ExamId, | 183 | + exam.uuid(), |
| 184 | - user as &UserId, | 184 | + user.uuid(), |
| 185 | seq, | 185 | seq, |
| 186 | - mark, | 186 | + mark.as_i64(), |
| 187 | - graded_by as &UserId, | 187 | + graded_by.uuid(), |
| 188 | ) | 188 | ) |
| 189 | .fetch_one(&mut *conn) | 189 | .fetch_one(&mut *conn) |
| 190 | .await?; | 190 | .await?; |
| @@ -207,8 +207,8 @@ pub async fn list_for_user_in_course( | |||
| 207 | FROM exam_result r JOIN exam e ON e.id = r.exam | 207 | FROM exam_result r JOIN exam e ON e.id = r.exam |
| 208 | WHERE r.app_user = $1 AND e.course = $2 | 208 | WHERE r.app_user = $1 AND e.course = $2 |
| 209 | ORDER BY r.exam DESC, r.seq DESC"#, | 209 | ORDER BY r.exam DESC, r.seq DESC"#, |
| 210 | - user as &UserId, | 210 | + user.uuid(), |
| 211 | - course as &CourseId, | 211 | + course.uuid(), |
| 212 | ) | 212 | ) |
| 213 | .fetch_all(db) | 213 | .fetch_all(db) |
| 214 | .await?; | 214 | .await?; |
| @@ -222,7 +222,7 @@ pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamResul | |||
| 222 | mark AS "mark: Mark", graded_by AS "graded_by: UserId" | 222 | mark AS "mark: Mark", graded_by AS "graded_by: UserId" |
| 223 | FROM exam_result WHERE exam = $1 | 223 | FROM exam_result WHERE exam = $1 |
| 224 | ORDER BY exam DESC, seq DESC"#, | 224 | ORDER BY exam DESC, seq DESC"#, |
| 225 | - exam as &ExamId, | 225 | + exam.uuid(), |
| 226 | ) | 226 | ) |
| 227 | .fetch_all(db) | 227 | .fetch_all(db) |
| 228 | .await?; | 228 | .await?; |
| @@ -242,8 +242,8 @@ pub async fn list_all_for_exam_user( | |||
| 242 | mark AS "mark: Mark", graded_by AS "graded_by: UserId" | 242 | mark AS "mark: Mark", graded_by AS "graded_by: UserId" |
| 243 | FROM exam_result WHERE exam = $1 AND app_user = $2 | 243 | FROM exam_result WHERE exam = $1 AND app_user = $2 |
| 244 | ORDER BY seq ASC"#, | 244 | ORDER BY seq ASC"#, |
| 245 | - exam as &ExamId, | 245 | + exam.uuid(), |
| 246 | - user as &UserId, | 246 | + user.uuid(), |
| 247 | ) | 247 | ) |
| 248 | .fetch_all(db) | 248 | .fetch_all(db) |
| 249 | .await?) | 249 | .await?) |
| @@ -298,11 +298,11 @@ pub async fn remove( | |||
| 298 | r#"WITH gone AS ( | 298 | r#"WITH gone AS ( |
| 299 | DELETE FROM exam_result | 299 | DELETE FROM exam_result |
| 300 | WHERE exam = $1 AND app_user = $2 | 300 | WHERE exam = $1 AND app_user = $2 |
| 301 | - RETURNING mark AS "mark: Mark", graded_by AS "graded_by: UserId", seq) | 301 | + RETURNING mark, graded_by, seq) |
| 302 | SELECT seq, mark AS "mark: Mark", graded_by AS "graded_by: UserId" | 302 | SELECT seq, mark AS "mark: Mark", graded_by AS "graded_by: UserId" |
| 303 | FROM gone ORDER BY seq ASC"#, | 303 | FROM gone ORDER BY seq ASC"#, |
| 304 | - exam as &ExamId, | 304 | + exam.uuid(), |
| 305 | - user as &UserId, | 305 | + user.uuid(), |
| 306 | ) | 306 | ) |
| 307 | .fetch_all(&mut *conn) | 307 | .fetch_all(&mut *conn) |
| 308 | .await?; | 308 | .await?; |
| @@ -320,7 +320,7 @@ pub async fn remove( | |||
| 320 | sqlx::query!( | 320 | sqlx::query!( |
| 321 | r#"UPDATE exam SET result_count = GREATEST(exam.result_count - $2, 0) | 321 | r#"UPDATE exam SET result_count = GREATEST(exam.result_count - $2, 0) |
| 322 | WHERE id = $1"#, | 322 | WHERE id = $1"#, |
| 323 | - exam as &ExamId, | 323 | + exam.uuid(), |
| 324 | gone.len() as i64, | 324 | gone.len() as i64, |
| 325 | ) | 325 | ) |
| 326 | .execute(&mut *conn) | 326 | .execute(&mut *conn) |
| @@ -334,7 +334,7 @@ pub async fn remove( | |||
| 334 | r#"UPDATE app_user SET high_mark_total = | 334 | r#"UPDATE app_user SET high_mark_total = |
| 335 | GREATEST(high_mark_total - $2, 0) | 335 | GREATEST(high_mark_total - $2, 0) |
| 336 | WHERE id = $1"#, | 336 | WHERE id = $1"#, |
| 337 | - user as &UserId, | 337 | + user.uuid(), |
| 338 | high, | 338 | high, |
| 339 | ) | 339 | ) |
| 340 | .execute(&mut *conn) | 340 | .execute(&mut *conn) |
| @@ -358,7 +358,7 @@ pub async fn remove( | |||
| 358 | r#"UPDATE app_user SET marks_given_total = | 358 | r#"UPDATE app_user SET marks_given_total = |
| 359 | GREATEST(marks_given_total - $2, 0) | 359 | GREATEST(marks_given_total - $2, 0) |
| 360 | WHERE id = $1"#, | 360 | WHERE id = $1"#, |
| 361 | - grader as &UserId, | 361 | + grader.uuid(), |
| 362 | n, | 362 | n, |
| 363 | ) | 363 | ) |
| 364 | .execute(&mut *conn) | 364 | .execute(&mut *conn) |
src/db/fee_plan.rsmodified+19 -12
| @@ -28,18 +28,20 @@ pub async fn create( | |||
| 28 | created_by: &UserId, | 28 | created_by: &UserId, |
| 29 | ) -> Result<FeePlan, AppError> { | 29 | ) -> Result<FeePlan, AppError> { |
| 30 | validate_installments(&installments)?; | 30 | validate_installments(&installments)?; |
| 31 | + let installments = serde_json::to_value(&installments) | ||
| 32 | + .map_err(|e| AppError::Internal(format!("fee plan encode: {e}")))?; | ||
| 31 | let id = FeePlanId::generate(); | 33 | let id = FeePlanId::generate(); |
| 32 | let created_at = Timestamp::now(); | 34 | let created_at = Timestamp::now(); |
| 33 | sqlx::query_as!( | 35 | sqlx::query_as!( |
| 34 | FeePlan, | 36 | FeePlan, |
| 35 | "INSERT INTO fee_plan (id, name, installments, created_by, created_at) \ | 37 | "INSERT INTO fee_plan (id, name, installments, created_by, created_at) \ |
| 36 | VALUES ($1, $2, $3, $4, $5) \ | 38 | VALUES ($1, $2, $3, $4, $5) \ |
| 37 | - RETURNING id, name, installments, created_by, created_at", | 39 | + RETURNING id AS \"id: FeePlanId\", name AS \"name: FeePlanName\", installments AS \"installments: sqlx::types::Json<Vec<Installment>>\", created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"", |
| 38 | - id, | 40 | + id.uuid(), |
| 39 | - name, | 41 | + name.as_str(), |
| 40 | - sqlx::types::Json(installments), | 42 | + installments, |
| 41 | - created_by, | 43 | + created_by.uuid(), |
| 42 | - created_at, | 44 | + created_at.as_millis(), |
| 43 | ) | 45 | ) |
| 44 | .fetch_one(db) | 46 | .fetch_one(db) |
| 45 | .await | 47 | .await |
| @@ -49,9 +51,9 @@ pub async fn create( | |||
| 49 | pub async fn read(db: &Database, id: &FeePlanId) -> Result<Option<FeePlan>, AppError> { | 51 | pub async fn read(db: &Database, id: &FeePlanId) -> Result<Option<FeePlan>, AppError> { |
| 50 | sqlx::query_as!( | 52 | sqlx::query_as!( |
| 51 | FeePlan, | 53 | FeePlan, |
| 52 | - "SELECT id, name, installments, created_by, created_at \ | 54 | + "SELECT id AS \"id: FeePlanId\", name AS \"name: FeePlanName\", installments AS \"installments: sqlx::types::Json<Vec<Installment>>\", created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\" |
| 53 | FROM fee_plan WHERE id = $1", | 55 | FROM fee_plan WHERE id = $1", |
| 54 | - id, | 56 | + id.uuid(), |
| 55 | ) | 57 | ) |
| 56 | .fetch_optional(db) | 58 | .fetch_optional(db) |
| 57 | .await | 59 | .await |
| @@ -103,15 +105,20 @@ pub async fn update( | |||
| 103 | // is the whole answer, assigned or not. | 105 | // is the whole answer, assigned or not. |
| 104 | return read(db, &plan.id).await?.ok_or(AppError::NotFound); | 106 | return read(db, &plan.id).await?.ok_or(AppError::NotFound); |
| 105 | } | 107 | } |
| 108 | + let installments = installments | ||
| 109 | + .as_ref() | ||
| 110 | + .map(serde_json::to_value) | ||
| 111 | + .transpose() | ||
| 112 | + .map_err(|e| AppError::Internal(format!("fee plan encode: {e}")))?; | ||
| 106 | let edited = sqlx::query_as!( | 113 | let edited = sqlx::query_as!( |
| 107 | FeePlan, | 114 | FeePlan, |
| 108 | "UPDATE fee_plan \ | 115 | "UPDATE fee_plan \ |
| 109 | SET name = COALESCE($2, name), installments = COALESCE($3, installments) \ | 116 | SET name = COALESCE($2, name), installments = COALESCE($3, installments) \ |
| 110 | WHERE id = $1 AND assignment_count = 0 \ | 117 | WHERE id = $1 AND assignment_count = 0 \ |
| 111 | - RETURNING id, name, installments, created_by, created_at", | 118 | + RETURNING id AS \"id: FeePlanId\", name AS \"name: FeePlanName\", installments AS \"installments: sqlx::types::Json<Vec<Installment>>\", created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"", |
| 112 | - plan.id, | 119 | + plan.id.uuid(), |
| 113 | name.map(|n| n.as_str().to_string()), | 120 | name.map(|n| n.as_str().to_string()), |
| 114 | - installments.map(sqlx::types::Json), | 121 | + installments, |
| 115 | ) | 122 | ) |
| 116 | .fetch_optional(db) | 123 | .fetch_optional(db) |
| 117 | .await?; | 124 | .await?; |
| @@ -143,7 +150,7 @@ pub async fn update( | |||
| 143 | pub async fn delete(db: &Database, plan: FeePlan) -> Result<bool, AppError> { | 150 | pub async fn delete(db: &Database, plan: FeePlan) -> Result<bool, AppError> { |
| 144 | let deleted = sqlx::query!( | 151 | let deleted = sqlx::query!( |
| 145 | "DELETE FROM fee_plan WHERE id = $1 AND assignment_count = 0 RETURNING id", | 152 | "DELETE FROM fee_plan WHERE id = $1 AND assignment_count = 0 RETURNING id", |
| 146 | - plan.id, | 153 | + plan.id.uuid(), |
| 147 | ) | 154 | ) |
| 148 | .fetch_optional(db) | 155 | .fetch_optional(db) |
| 149 | .await?; | 156 | .await?; |
src/db/fee_plan_assignment.rsmodified+13 -13
| @@ -18,10 +18,10 @@ pub async fn read( | |||
| 18 | ) -> Result<Option<FeePlanAssignment>, AppError> { | 18 | ) -> Result<Option<FeePlanAssignment>, AppError> { |
| 19 | sqlx::query_as!( | 19 | sqlx::query_as!( |
| 20 | FeePlanAssignment, | 20 | FeePlanAssignment, |
| 21 | - "SELECT plan, student, assigned_by, created_at \ | 21 | + "SELECT plan AS \"plan: FeePlanId\", student AS \"student: UserId\", assigned_by AS \"assigned_by: UserId\", created_at AS \"created_at: Timestamp\" |
| 22 | FROM fee_plan_assignment WHERE plan = $1 AND student = $2", | 22 | FROM fee_plan_assignment WHERE plan = $1 AND student = $2", |
| 23 | - id.plan, | 23 | + id.plan.uuid(), |
| 24 | - id.student, | 24 | + id.student.uuid(), |
| 25 | ) | 25 | ) |
| 26 | .fetch_optional(db) | 26 | .fetch_optional(db) |
| 27 | .await | 27 | .await |
| @@ -58,13 +58,13 @@ pub async fn create( | |||
| 58 | RETURNING 1) | 58 | RETURNING 1) |
| 59 | INSERT INTO fee_plan_assignment (plan, student, assigned_by, created_at) | 59 | INSERT INTO fee_plan_assignment (plan, student, assigned_by, created_at) |
| 60 | SELECT $3, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) | 60 | SELECT $3, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) |
| 61 | - RETURNING plan, student, assigned_by, created_at"#, | 61 | + RETURNING plan AS "plan: FeePlanId", student AS "student: UserId", assigned_by AS "assigned_by: UserId", created_at AS "created_at: Timestamp""#, |
| 62 | - plan, | 62 | + plan.uuid(), |
| 63 | cap::UNLIMITED, | 63 | cap::UNLIMITED, |
| 64 | - plan, | 64 | + plan.uuid(), |
| 65 | - student, | 65 | + student.uuid(), |
| 66 | - assigned_by, | 66 | + assigned_by.uuid(), |
| 67 | - created_at, | 67 | + created_at.as_millis(), |
| 68 | ) | 68 | ) |
| 69 | .fetch_optional(db) | 69 | .fetch_optional(db) |
| 70 | .await; | 70 | .await; |
| @@ -101,13 +101,13 @@ pub async fn list_for_plan( | |||
| 101 | /// can be behind. Kept because a *test* asserting the rows and the counter | 101 | /// can be behind. Kept because a *test* asserting the rows and the counter |
| 102 | /// agree is the only thing that would catch the counter drifting. | 102 | /// agree is the only thing that would catch the counter drifting. |
| 103 | pub async fn exists_for_plan(db: &Database, plan: &FeePlanId) -> Result<bool, AppError> { | 103 | pub async fn exists_for_plan(db: &Database, plan: &FeePlanId) -> Result<bool, AppError> { |
| 104 | - let (exists,) = sqlx::query!( | 104 | + let row = sqlx::query!( |
| 105 | - "SELECT EXISTS (SELECT 1 FROM fee_plan_assignment WHERE plan = $1)", | 105 | + "SELECT EXISTS (SELECT 1 FROM fee_plan_assignment WHERE plan = $1) AS \"exists!\"", |
| 106 | - plan | 106 | + plan.uuid() |
| 107 | ) | 107 | ) |
| 108 | .fetch_one(db) | 108 | .fetch_one(db) |
| 109 | .await?; | 109 | .await?; |
| 110 | - Ok(exists) | 110 | + Ok(row.exists) |
| 111 | } | 111 | } |
| 112 | 112 | ||
| 113 | /// Which plans a student is on — one student may hold several. | 113 | /// Which plans a student is on — one student may hold several. |
src/db/field_update.rsmodified+68 -60
| @@ -125,7 +125,12 @@ impl FieldUpdate { | |||
| 125 | /// row stays editable field by field. `NULL` on either side passes, | 125 | /// row stays editable field by field. `NULL` on either side passes, |
| 126 | /// exactly like [`crate::web::check_time_range`] skipping an absent end. | 126 | /// exactly like [`crate::web::check_time_range`] skipping an absent end. |
| 127 | #[must_use] | 127 | #[must_use] |
| 128 | - pub(crate) fn ordered(mut self, low: &'static str, high: &'static str, refused: AppError) -> Self { | 128 | + pub(crate) fn ordered( |
| 129 | + mut self, | ||
| 130 | + low: &'static str, | ||
| 131 | + high: &'static str, | ||
| 132 | + refused: AppError, | ||
| 133 | + ) -> Self { | ||
| 129 | self.ordered = Some((low, high, refused)); | 134 | self.ordered = Some((low, high, refused)); |
| 130 | self | 135 | self |
| 131 | } | 136 | } |
| @@ -374,71 +379,75 @@ async fn run_with_refcount<T>( | |||
| 374 | where | 379 | where |
| 375 | T: for<'r> FromRow<'r, PgRow> + Send + Unpin, | 380 | T: for<'r> FromRow<'r, PgRow> + Send + Unpin, |
| 376 | { | 381 | { |
| 377 | - let mut slot: Option<AppError> = Some(refused); | 382 | + // Owned captures + `async move`: the closure's future must be Send and |
| 378 | - let outcome = tx_with_retry(db, false, async |tx| { | 383 | + // general enough for axum's handler registration — borrowed captures |
| 384 | + // (`async |tx|` over `&mut`/`&T`) fail that check tree-wide. | ||
| 385 | + let mut refused = Some(refused); | ||
| 386 | + let outcome = tx_with_retry(db, false, async move |tx| { | ||
| 379 | let binds = binds.clone(); | 387 | let binds = binds.clone(); |
| 380 | - if let Some(release) = release { | 388 | + if let Some(release) = release { |
| 381 | - sqlx::query(AssertSqlSafe(format!( | 389 | + sqlx::query(AssertSqlSafe(format!( |
| 382 | - "UPDATE {counter_table} \ | 390 | + "UPDATE {counter_table} \ |
| 383 | SET {counter_field} = GREATEST({counter_field} - 1, 0) WHERE id = $1" | 391 | SET {counter_field} = GREATEST({counter_field} - 1, 0) WHERE id = $1" |
| 384 | - ))) | 392 | + ))) |
| 385 | - .bind(release) | 393 | + .bind(release) |
| 386 | - .execute(&mut *tx) | 394 | + .execute(&mut *tx) |
| 387 | - .await?; | 395 | + .await?; |
| 388 | - } | 396 | + } |
| 389 | - // The conditional claim doubles as the existence check: zero rows | 397 | + // The conditional claim doubles as the existence check: zero rows |
| 390 | - // is the claimed row being gone, the caller's own refusal. | 398 | + // is the claimed row being gone, the caller's own refusal. |
| 391 | - if let Some(claim) = claim { | 399 | + if let Some(claim) = claim { |
| 392 | - let seat: Option<i32> = sqlx::query_scalar(AssertSqlSafe(format!( | 400 | + let seat: Option<i32> = sqlx::query_scalar(AssertSqlSafe(format!( |
| 393 | - "UPDATE {counter_table} SET {counter_field} = {counter_field} + 1 \ | 401 | + "UPDATE {counter_table} SET {counter_field} = {counter_field} + 1 \ |
| 394 | WHERE id = $1 RETURNING 1" | 402 | WHERE id = $1 RETURNING 1" |
| 395 | - ))) | 403 | + ))) |
| 396 | - .bind(claim) | 404 | + .bind(claim) |
| 397 | - .fetch_optional(&mut *tx) | 405 | + .fetch_optional(&mut *tx) |
| 398 | - .await?; | 406 | + .await?; |
| 399 | - if seat.is_none() { | 407 | + if seat.is_none() { |
| 400 | - return Err(slot.take().unwrap_or_else(|| mark(REFUSAL_MARK))); | 408 | + return Err(refused.take().unwrap_or_else(|| mark(REFUSAL_MARK))); |
| 401 | - } | ||
| 402 | - } | ||
| 403 | - let mut args = PgArguments::default(); | ||
| 404 | - for bind in binds.iter().cloned() { | ||
| 405 | - bind.add_to(&mut args); | ||
| 406 | - } | ||
| 407 | - let rows: Vec<T> = sqlx::query_as_with(AssertSqlSafe(update.as_str()), args) | ||
| 408 | - .fetch_all(&mut *tx) | ||
| 409 | - .await?; | ||
| 410 | - if !rows.is_empty() { | ||
| 411 | - return Ok(rows); | ||
| 412 | - } | ||
| 413 | - // Zero rows: the caller's own guard bit, the row deleted in the | ||
| 414 | - // window after the handler's read, or — the CAS only — the link | ||
| 415 | - // moved since the handler read it. Nothing was written yet either | ||
| 416 | - // way, so the probe that tells the cases apart is free: it matches | ||
| 417 | - // only a row that is *there*, whose *own* guards still hold, and | ||
| 418 | - // whose link has moved off what the handler read — which is the | ||
| 419 | - // CAS, and nothing else, having bitten. Carrying the caller's | ||
| 420 | - // guards is what keeps that true when a write is refused for | ||
| 421 | - // *both* reasons at once: a `.guard()`/`.ordered()` refusal is the | ||
| 422 | - // caller's own answer to give, and reporting it as "the link | ||
| 423 | - // moved" would send the client to re-read a link that was never | ||
| 424 | - // its problem. | ||
| 425 | - let mut args = PgArguments::default(); | ||
| 426 | - for bind in binds { | ||
| 427 | - bind.add_to(&mut args); | ||
| 428 | - } | ||
| 429 | - let live: Option<i32> = sqlx::query_scalar_with(AssertSqlSafe(probe.as_str()), args) | ||
| 430 | - .fetch_optional(&mut *tx) | ||
| 431 | - .await?; | ||
| 432 | - match live { | ||
| 433 | - Some(_) => Err(mark(STALE_MARK)), | ||
| 434 | - None => Err(mark(GONE_MARK)), | ||
| 435 | } | 409 | } |
| 410 | + } | ||
| 411 | + let mut args = PgArguments::default(); | ||
| 412 | + for bind in binds.iter().cloned() { | ||
| 413 | + bind.add_to(&mut args); | ||
| 414 | + } | ||
| 415 | + let rows: Vec<T> = sqlx::query_as_with(AssertSqlSafe(update.as_str()), args) | ||
| 416 | + .fetch_all(&mut *tx) | ||
| 417 | + .await?; | ||
| 418 | + if !rows.is_empty() { | ||
| 419 | + return Ok(rows); | ||
| 420 | + } | ||
| 421 | + // Zero rows: the caller's own guard bit, the row deleted in the | ||
| 422 | + // window after the handler's read, or — the CAS only — the link | ||
| 423 | + // moved since the handler read it. Nothing was written yet either | ||
| 424 | + // way, so the probe that tells the cases apart is free: it matches | ||
| 425 | + // only a row that is *there*, whose *own* guards still hold, and | ||
| 426 | + // whose link has moved off what the handler read — which is the | ||
| 427 | + // CAS, and nothing else, having bitten. Carrying the caller's | ||
| 428 | + // guards is what keeps that true when a write is refused for | ||
| 429 | + // *both* reasons at once: a `.guard()`/`.ordered()` refusal is the | ||
| 430 | + // caller's own answer to give, and reporting it as "the link | ||
| 431 | + // moved" would send the client to re-read a link that was never | ||
| 432 | + // its problem. | ||
| 433 | + let mut args = PgArguments::default(); | ||
| 434 | + for bind in binds { | ||
| 435 | + bind.add_to(&mut args); | ||
| 436 | + } | ||
| 437 | + let live: Option<i32> = sqlx::query_scalar_with(AssertSqlSafe(probe.as_str()), args) | ||
| 438 | + .fetch_optional(&mut *tx) | ||
| 439 | + .await?; | ||
| 440 | + match live { | ||
| 441 | + Some(_) => Err(mark(STALE_MARK)), | ||
| 442 | + None => Err(mark(GONE_MARK)), | ||
| 443 | + } | ||
| 436 | }) | 444 | }) |
| 437 | .await; | 445 | .await; |
| 438 | match outcome { | 446 | match outcome { |
| 439 | - Err(AppError::Internal(m)) if m == REFUSAL_MARK => { | 447 | + // The mark only ever leaves the closure once the real refusal was |
| 440 | - Err(slot.take().unwrap_or_else(|| mark(REFUSAL_MARK))) | 448 | + // spent, so it is the final answer here (today's slot.take() could |
| 441 | - } | 449 | + // never resurrect it either). |
| 450 | + Err(AppError::Internal(m)) if m == REFUSAL_MARK => Err(mark(REFUSAL_MARK)), | ||
| 442 | Err(AppError::Internal(m)) if m == STALE_MARK => Err(AppError::Conflict(STALE_MOVE)), | 451 | Err(AppError::Internal(m)) if m == STALE_MARK => Err(AppError::Conflict(STALE_MOVE)), |
| 443 | // The row is gone: exactly the "wrote nothing" answer the plain path | 452 | // The row is gone: exactly the "wrote nothing" answer the plain path |
| 444 | // reports, so the caller's refusal is unchanged. | 453 | // reports, so the caller's refusal is unchanged. |
| @@ -446,4 +455,3 @@ where | |||
| 446 | other => other, | 455 | other => other, |
| 447 | } | 456 | } |
| 448 | } | 457 | } |
| 449 | - | ||
src/db/meal_attendance.rsmodified+12 -8
| @@ -39,13 +39,15 @@ pub async fn mark( | |||
| 39 | marked_by: &UserId, | 39 | marked_by: &UserId, |
| 40 | ) -> Result<MealAttendance, AppError> { | 40 | ) -> Result<MealAttendance, AppError> { |
| 41 | let marked_at = Timestamp::now(); | 41 | let marked_at = Timestamp::now(); |
| 42 | + // Owned captures (`Send` rule of `tx_with_retry` closures). | ||
| 43 | + let menu_key = menu.key().to_string(); | ||
| 42 | let student = *student; | 44 | let student = *student; |
| 43 | let marked_by = *marked_by; | 45 | let marked_by = *marked_by; |
| 44 | - tx_with_retry(db, false, async |tx| { | 46 | + tx_with_retry(db, false, async move |tx| { |
| 45 | let bumped = sqlx::query!( | 47 | let bumped = sqlx::query!( |
| 46 | "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 | 48 | "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 |
| 47 | RETURNING 1 AS bumped", | 49 | RETURNING 1 AS bumped", |
| 48 | - menu.key(), | 50 | + menu_key, |
| 49 | ) | 51 | ) |
| 50 | .fetch_optional(&mut *tx) | 52 | .fetch_optional(&mut *tx) |
| 51 | .await?; | 53 | .await?; |
| @@ -60,12 +62,14 @@ pub async fn mark( | |||
| 60 | SET status = EXCLUDED.status, | 62 | SET status = EXCLUDED.status, |
| 61 | marked_by = EXCLUDED.marked_by, | 63 | marked_by = EXCLUDED.marked_by, |
| 62 | marked_at = EXCLUDED.marked_at | 64 | marked_at = EXCLUDED.marked_at |
| 63 | - RETURNING menu, student, status, marked_by, marked_at", | 65 | + RETURNING menu AS \"menu: MenuId\", student AS \"student: UserId\", |
| 64 | - menu.key(), | 66 | + status AS \"status: MealAttendanceStatus\", marked_by AS \"marked_by: UserId\", |
| 65 | - student, | 67 | + marked_at AS \"marked_at: Timestamp\"", |
| 66 | - status, | 68 | + menu_key, |
| 67 | - marked_by, | 69 | + student.uuid(), |
| 68 | - marked_at, | 70 | + status.as_str(), |
| 71 | + marked_by.uuid(), | ||
| 72 | + marked_at.as_millis(), | ||
| 69 | ) | 73 | ) |
| 70 | .fetch_one(&mut *tx) | 74 | .fetch_one(&mut *tx) |
| 71 | .await?; | 75 | .await?; |
src/db/meal_booking.rsmodified+64 -42
| @@ -8,7 +8,7 @@ | |||
| 8 | use crate::database::{Database, tx_with_retry}; | 8 | use crate::database::{Database, tx_with_retry}; |
| 9 | use crate::db::cap::Claimed; | 9 | use crate::db::cap::Claimed; |
| 10 | use crate::db::page::PagedList; | 10 | use crate::db::page::PagedList; |
| 11 | -use crate::domain::meal_booking::{MealBooking, MealBookingId}; | 11 | +use crate::domain::meal_booking::{MealBooking, MealBookingId, MealBookingStatus}; |
| 12 | use crate::domain::meal_ledger::{LedgerAmount, MealLedger}; | 12 | use crate::domain::meal_ledger::{LedgerAmount, MealLedger}; |
| 13 | use crate::domain::menu::MenuId; | 13 | use crate::domain::menu::MenuId; |
| 14 | use crate::domain::timestamp::Timestamp; | 14 | use crate::domain::timestamp::Timestamp; |
| @@ -18,10 +18,10 @@ use crate::error::AppError; | |||
| 18 | pub async fn read(db: &Database, id: &MealBookingId) -> Result<Option<MealBooking>, AppError> { | 18 | pub async fn read(db: &Database, id: &MealBookingId) -> Result<Option<MealBooking>, AppError> { |
| 19 | let row = sqlx::query_as!( | 19 | let row = sqlx::query_as!( |
| 20 | MealBooking, | 20 | MealBooking, |
| 21 | - "SELECT menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at | 21 | + "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\" |
| 22 | FROM meal_booking WHERE menu = $1 AND student = $2", | 22 | FROM meal_booking WHERE menu = $1 AND student = $2", |
| 23 | id.menu().key(), | 23 | id.menu().key(), |
| 24 | - *id.student(), | 24 | + id.student().uuid(), |
| 25 | ) | 25 | ) |
| 26 | .fetch_optional(db) | 26 | .fetch_optional(db) |
| 27 | .await?; | 27 | .await?; |
| @@ -64,14 +64,14 @@ pub async fn list_for_students( | |||
| 64 | if students.is_empty() { | 64 | if students.is_empty() { |
| 65 | return Ok((Vec::new(), 0)); | 65 | return Ok((Vec::new(), 0)); |
| 66 | } | 66 | } |
| 67 | - let keys: Vec<String> = students.iter().map(UserId::key).collect(); | 67 | + let ids: Vec<uuid::Uuid> = students.iter().map(UserId::uuid).collect(); |
| 68 | let rows = sqlx::query_as!( | 68 | let rows = sqlx::query_as!( |
| 69 | MealBooking, | 69 | MealBooking, |
| 70 | - "SELECT menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at | 70 | + "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\" |
| 71 | FROM meal_booking WHERE student = ANY($1::uuid[]) | 71 | FROM meal_booking WHERE student = ANY($1::uuid[]) |
| 72 | ORDER BY created_at DESC, menu DESC | 72 | ORDER BY created_at DESC, menu DESC |
| 73 | LIMIT $2 OFFSET $3", | 73 | LIMIT $2 OFFSET $3", |
| 74 | - keys, | 74 | + &ids, |
| 75 | limit, | 75 | limit, |
| 76 | offset, | 76 | offset, |
| 77 | ) | 77 | ) |
| @@ -81,10 +81,11 @@ pub async fn list_for_students( | |||
| 81 | let total = if limit.is_some() || offset != 0 { | 81 | let total = if limit.is_some() || offset != 0 { |
| 82 | sqlx::query_scalar!( | 82 | sqlx::query_scalar!( |
| 83 | "SELECT count(*) FROM meal_booking WHERE student = ANY($1::uuid[])", | 83 | "SELECT count(*) FROM meal_booking WHERE student = ANY($1::uuid[])", |
| 84 | - keys, | 84 | + &ids, |
| 85 | ) | 85 | ) |
| 86 | .fetch_one(db) | 86 | .fetch_one(db) |
| 87 | - .await? as i64 | 87 | + .await? |
| 88 | + .unwrap_or(0) | ||
| 88 | } else { | 89 | } else { |
| 89 | rows.len() as i64 | 90 | rows.len() as i64 |
| 90 | }; | 91 | }; |
| @@ -133,9 +134,28 @@ pub(crate) async fn claim_and_place( | |||
| 133 | charge: Option<&MealLedger>, | 134 | charge: Option<&MealLedger>, |
| 134 | ) -> Result<Claimed<MealBooking>, AppError> { | 135 | ) -> Result<Claimed<MealBooking>, AppError> { |
| 135 | let menu_key = menu.key().to_string(); | 136 | let menu_key = menu.key().to_string(); |
| 136 | - let student = row.student; | 137 | + let student = row.student.uuid(); |
| 137 | let attempt = row.attempt; | 138 | let attempt = row.attempt; |
| 138 | - tx_with_retry(db, false, async |tx| { | 139 | + // Owned captures only: a closure holding a `&T` fails the higher-ranked |
| 140 | + // `Send` check `tx_with_retry`'s future must pass. | ||
| 141 | + let booked_by = row.booked_by.uuid(); | ||
| 142 | + let status = row.status.as_str(); | ||
| 143 | + let cancelled_at = row.cancelled_at.map(|t| t.as_millis()); | ||
| 144 | + let created_at = row.created_at.as_millis(); | ||
| 145 | + let charge = charge.map(|line| { | ||
| 146 | + ( | ||
| 147 | + line.id.key().to_string(), | ||
| 148 | + line.student.uuid(), | ||
| 149 | + line.kind.as_str(), | ||
| 150 | + line.amount_minor.as_minor(), | ||
| 151 | + line.source.clone(), | ||
| 152 | + line.method.as_ref().map(|m| m.as_str().to_string()), | ||
| 153 | + line.note.as_ref().map(|n| n.as_str().to_string()), | ||
| 154 | + line.recorded_by.uuid(), | ||
| 155 | + line.created_at.as_millis(), | ||
| 156 | + ) | ||
| 157 | + }); | ||
| 158 | + tx_with_retry(db, false, async move |tx| { | ||
| 139 | // Already held? Same attempt, same price it was taken at — answered | 159 | // Already held? Same attempt, same price it was taken at — answered |
| 140 | // as `Duplicate`, which the caller replays into the winner's row | 160 | // as `Duplicate`, which the caller replays into the winner's row |
| 141 | // (and its charge) without claiming anything. | 161 | // (and its charge) without claiming anything. |
| @@ -175,12 +195,12 @@ pub(crate) async fn claim_and_place( | |||
| 175 | "UPDATE meal_booking | 195 | "UPDATE meal_booking |
| 176 | SET status = 'booked', attempt = $3, price_minor = $4, cancelled_at = NULL | 196 | SET status = 'booked', attempt = $3, price_minor = $4, cancelled_at = NULL |
| 177 | WHERE menu = $1 AND student = $2 | 197 | WHERE menu = $1 AND student = $2 |
| 178 | - AND status = 'cancelled' AND attempt = $3 - 1 | 198 | + AND status = 'cancelled' AND attempt = $3::bigint - 1 |
| 179 | - RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at", | 199 | + 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\"", |
| 180 | menu_key, | 200 | menu_key, |
| 181 | student, | 201 | student, |
| 182 | attempt, | 202 | attempt, |
| 183 | - price, | 203 | + price.map(LedgerAmount::as_minor), |
| 184 | ) | 204 | ) |
| 185 | .fetch_optional(&mut *tx) | 205 | .fetch_optional(&mut *tx) |
| 186 | .await?; | 206 | .await?; |
| @@ -196,15 +216,15 @@ pub(crate) async fn claim_and_place( | |||
| 196 | (menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at) | 216 | (menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at) |
| 197 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8) | 217 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8) |
| 198 | ON CONFLICT (menu, student) DO NOTHING | 218 | ON CONFLICT (menu, student) DO NOTHING |
| 199 | - RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at", | 219 | + 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\"", |
| 200 | menu_key, | 220 | menu_key, |
| 201 | student, | 221 | student, |
| 202 | - row.booked_by, | 222 | + booked_by, |
| 203 | - row.status, | 223 | + status, |
| 204 | - row.attempt, | 224 | + attempt, |
| 205 | - price, | 225 | + price.map(LedgerAmount::as_minor), |
| 206 | - row.cancelled_at, | 226 | + cancelled_at, |
| 207 | - row.created_at, | 227 | + created_at, |
| 208 | ) | 228 | ) |
| 209 | .fetch_optional(&mut *tx) | 229 | .fetch_optional(&mut *tx) |
| 210 | .await?; | 230 | .await?; |
| @@ -216,21 +236,23 @@ pub(crate) async fn claim_and_place( | |||
| 216 | }; | 236 | }; |
| 217 | // The charge rides the same transaction; already there (a replayed | 237 | // The charge rides the same transaction; already there (a replayed |
| 218 | // POST of this seat) means fine — nothing is written twice. | 238 | // POST of this seat) means fine — nothing is written twice. |
| 219 | - if let Some(line) = charge { | 239 | + if let Some((id, student, kind, amount, source, method, note, recorded_by, created_at)) = |
| 240 | + &charge | ||
| 241 | + { | ||
| 220 | sqlx::query!( | 242 | sqlx::query!( |
| 221 | "INSERT INTO meal_ledger | 243 | "INSERT INTO meal_ledger |
| 222 | (id, student, kind, amount_minor, source, method, note, recorded_by, created_at) | 244 | (id, student, kind, amount_minor, source, method, note, recorded_by, created_at) |
| 223 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) | 245 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) |
| 224 | ON CONFLICT (id) DO NOTHING", | 246 | ON CONFLICT (id) DO NOTHING", |
| 225 | - line.id.key(), | 247 | + id.as_str(), |
| 226 | - line.student, | 248 | + student, |
| 227 | - line.kind, | 249 | + kind, |
| 228 | - line.amount_minor, | 250 | + amount, |
| 229 | - line.source, | 251 | + source.as_deref(), |
| 230 | - line.method, | 252 | + method.as_deref(), |
| 231 | - line.note, | 253 | + note.as_deref(), |
| 232 | - line.recorded_by, | 254 | + recorded_by, |
| 233 | - line.created_at, | 255 | + created_at, |
| 234 | ) | 256 | ) |
| 235 | .execute(&mut *tx) | 257 | .execute(&mut *tx) |
| 236 | .await?; | 258 | .await?; |
| @@ -278,18 +300,18 @@ pub async fn release_seat( | |||
| 278 | ) -> Result<Option<MealBooking>, AppError> { | 300 | ) -> Result<Option<MealBooking>, AppError> { |
| 279 | let refund = MealLedger::reversal_for(booked, recorded_by); | 301 | let refund = MealLedger::reversal_for(booked, recorded_by); |
| 280 | let menu_key = booked.menu.key().to_string(); | 302 | let menu_key = booked.menu.key().to_string(); |
| 281 | - let student = booked.student; | 303 | + let student = booked.student.uuid(); |
| 282 | let attempt = booked.attempt; | 304 | let attempt = booked.attempt; |
| 283 | let cancelled_at = Timestamp::now(); | 305 | let cancelled_at = Timestamp::now(); |
| 284 | - tx_with_retry(db, false, async |tx| { | 306 | + tx_with_retry(db, false, async move |tx| { |
| 285 | let flipped = sqlx::query_as!( | 307 | let flipped = sqlx::query_as!( |
| 286 | MealBooking, | 308 | MealBooking, |
| 287 | "UPDATE meal_booking SET status = 'cancelled', cancelled_at = $3 | 309 | "UPDATE meal_booking SET status = 'cancelled', cancelled_at = $3 |
| 288 | WHERE menu = $1 AND student = $2 AND status = 'booked' AND attempt = $4 | 310 | WHERE menu = $1 AND student = $2 AND status = 'booked' AND attempt = $4 |
| 289 | - RETURNING menu, student, booked_by, status, attempt, price_minor, cancelled_at, created_at", | 311 | + 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\"", |
| 290 | menu_key, | 312 | menu_key, |
| 291 | student, | 313 | student, |
| 292 | - cancelled_at, | 314 | + cancelled_at.as_millis(), |
| 293 | attempt, | 315 | attempt, |
| 294 | ) | 316 | ) |
| 295 | .fetch_optional(&mut *tx) | 317 | .fetch_optional(&mut *tx) |
| @@ -326,14 +348,14 @@ pub async fn release_seat( | |||
| 326 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) | 348 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) |
| 327 | ON CONFLICT (id) DO NOTHING", | 349 | ON CONFLICT (id) DO NOTHING", |
| 328 | line.id.key(), | 350 | line.id.key(), |
| 329 | - line.student, | 351 | + line.student.uuid(), |
| 330 | - line.kind, | 352 | + line.kind.as_str(), |
| 331 | - line.amount_minor, | 353 | + line.amount_minor.as_minor(), |
| 332 | - line.source, | 354 | + line.source.as_deref(), |
| 333 | - line.method, | 355 | + line.method.as_ref().map(|m| m.as_str()), |
| 334 | - line.note, | 356 | + line.note.as_ref().map(|n| n.as_str()), |
| 335 | - line.recorded_by, | 357 | + line.recorded_by.uuid(), |
| 336 | - line.created_at, | 358 | + line.created_at.as_millis(), |
| 337 | ) | 359 | ) |
| 338 | .execute(&mut *tx) | 360 | .execute(&mut *tx) |
| 339 | .await?; | 361 | .await?; |
src/db/meal_ledger.rsmodified+17 -14
| @@ -5,7 +5,10 @@ | |||
| 5 | 5 | ||
| 6 | use crate::database::Database; | 6 | use crate::database::Database; |
| 7 | use crate::db::page::PagedList; | 7 | use crate::db::page::PagedList; |
| 8 | -use crate::domain::meal_ledger::{LedgerAmount, MealLedger, MealLedgerId}; | 8 | +use crate::domain::meal_ledger::{ |
| 9 | + LedgerAmount, LedgerMethod, LedgerNote, MealLedger, MealLedgerId, MealLedgerKind, | ||
| 10 | +}; | ||
| 11 | +use crate::domain::timestamp::Timestamp; | ||
| 9 | use crate::domain::menu::MenuId; | 12 | use crate::domain::menu::MenuId; |
| 10 | use crate::domain::user::UserId; | 13 | use crate::domain::user::UserId; |
| 11 | use crate::error::AppError; | 14 | use crate::error::AppError; |
| @@ -31,16 +34,16 @@ pub(crate) async fn append(db: &Database, row: MealLedger) -> Result<MealLedger, | |||
| 31 | (id, student, kind, amount_minor, source, method, note, recorded_by, created_at) | 34 | (id, student, kind, amount_minor, source, method, note, recorded_by, created_at) |
| 32 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) | 35 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) |
| 33 | ON CONFLICT (id) DO NOTHING | 36 | ON CONFLICT (id) DO NOTHING |
| 34 | - RETURNING id, student, kind, amount_minor, source, method, note, recorded_by, created_at", | 37 | + RETURNING 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\"", |
| 35 | row.id.key(), | 38 | row.id.key(), |
| 36 | - row.student, | 39 | + row.student.uuid(), |
| 37 | - row.kind, | 40 | + row.kind.as_str(), |
| 38 | - row.amount_minor, | 41 | + row.amount_minor.as_minor(), |
| 39 | row.source, | 42 | row.source, |
| 40 | - row.method, | 43 | + row.method.as_ref().map(|m| m.as_str()), |
| 41 | - row.note, | 44 | + row.note.as_ref().map(|n| n.as_str()), |
| 42 | - row.recorded_by, | 45 | + row.recorded_by.uuid(), |
| 43 | - row.created_at, | 46 | + row.created_at.as_millis(), |
| 44 | ) | 47 | ) |
| 45 | .fetch_optional(db) | 48 | .fetch_optional(db) |
| 46 | .await?; | 49 | .await?; |
| @@ -57,7 +60,7 @@ pub(crate) async fn append(db: &Database, row: MealLedger) -> Result<MealLedger, | |||
| 57 | pub async fn read(db: &Database, id: &MealLedgerId) -> Result<Option<MealLedger>, AppError> { | 60 | pub async fn read(db: &Database, id: &MealLedgerId) -> Result<Option<MealLedger>, AppError> { |
| 58 | let row = sqlx::query_as!( | 61 | let row = sqlx::query_as!( |
| 59 | MealLedger, | 62 | MealLedger, |
| 60 | - "SELECT id, student, kind, amount_minor, source, method, note, recorded_by, created_at | 63 | + "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\" |
| 61 | FROM meal_ledger WHERE id = $1", | 64 | FROM meal_ledger WHERE id = $1", |
| 62 | id.key(), | 65 | id.key(), |
| 63 | ) | 66 | ) |
| @@ -77,7 +80,7 @@ pub async fn price_snapshot( | |||
| 77 | menu: &MenuId, | 80 | menu: &MenuId, |
| 78 | ) -> Result<Option<LedgerAmount>, AppError> { | 81 | ) -> Result<Option<LedgerAmount>, AppError> { |
| 79 | let row = | 82 | let row = |
| 80 | - sqlx::query!("SELECT CAST(COALESCE(sum(price_minor), 0) AS BIGINT) AS total FROM menu_dish WHERE menu = $1", menu.key()) | 83 | + sqlx::query!("SELECT CAST(COALESCE(sum(price_minor), 0) AS BIGINT) AS \"total!\" FROM menu_dish WHERE menu = $1", menu.key()) |
| 81 | .fetch_one(db) | 84 | .fetch_one(db) |
| 82 | .await?; | 85 | .await?; |
| 83 | let total = row.total; | 86 | let total = row.total; |
| @@ -98,7 +101,7 @@ pub async fn list_for_student( | |||
| 98 | "meal_ledger WHERE student = $1", | 101 | "meal_ledger WHERE student = $1", |
| 99 | "ORDER BY created_at DESC, id DESC", | 102 | "ORDER BY created_at DESC, id DESC", |
| 100 | ) | 103 | ) |
| 101 | - .bind(student.key()) | 104 | + .bind(student.uuid()) |
| 102 | .run(limit, offset, db) | 105 | .run(limit, offset, db) |
| 103 | .await | 106 | .await |
| 104 | } | 107 | } |
| @@ -127,9 +130,9 @@ pub async fn list_for_student( | |||
| 127 | pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> { | 130 | pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> { |
| 128 | let totals = sqlx::query!( | 131 | let totals = sqlx::query!( |
| 129 | r#"SELECT kind AS "kind: crate::domain::meal_ledger::MealLedgerKind", | 132 | r#"SELECT kind AS "kind: crate::domain::meal_ledger::MealLedgerKind", |
| 130 | - CAST(sum(amount_minor) AS BIGINT) AS total | 133 | + CAST(sum(amount_minor) AS BIGINT) AS "total!" |
| 131 | FROM meal_ledger WHERE student = $1 GROUP BY kind"#, | 134 | FROM meal_ledger WHERE student = $1 GROUP BY kind"#, |
| 132 | - *student, | 135 | + student.uuid(), |
| 133 | ) | 136 | ) |
| 134 | .fetch_all(db) | 137 | .fetch_all(db) |
| 135 | .await?; | 138 | .await?; |
src/db/menu.rsmodified+9 -9
| @@ -41,7 +41,7 @@ pub async fn create( | |||
| 41 | let slot_s = slot.as_str().to_string(); | 41 | let slot_s = slot.as_str().to_string(); |
| 42 | let created_by = *created_by; | 42 | let created_by = *created_by; |
| 43 | let created_at = Timestamp::now(); | 43 | let created_at = Timestamp::now(); |
| 44 | - tx_with_retry(db, false, async |tx| { | 44 | + tx_with_retry(db, false, async move |tx| { |
| 45 | // Duplicate gate ahead of the retired check: "already published" | 45 | // Duplicate gate ahead of the retired check: "already published" |
| 46 | // outranks "slot retired", on the very path a rival publish races. | 46 | // outranks "slot retired", on the very path a rival publish races. |
| 47 | let exists = sqlx::query!("SELECT 1 AS taken FROM menu WHERE id = $1", id_key,) | 47 | let exists = sqlx::query!("SELECT 1 AS taken FROM menu WHERE id = $1", id_key,) |
| @@ -62,15 +62,15 @@ pub async fn create( | |||
| 62 | ) | 62 | ) |
| 63 | INSERT INTO menu (id, date, slot, capacity, version, created_by, created_at) | 63 | INSERT INTO menu (id, date, slot, capacity, version, created_by, created_at) |
| 64 | SELECT $1, $3, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM ref) | 64 | SELECT $1, $3, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM ref) |
| 65 | - RETURNING id, date, slot, capacity, version, created_by, created_at", | 65 | + 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\"", |
| 66 | id_key, | 66 | id_key, |
| 67 | counter, | 67 | counter, |
| 68 | date_s, | 68 | date_s, |
| 69 | slot_s, | 69 | slot_s, |
| 70 | capacity, | 70 | capacity, |
| 71 | Some(0i64), | 71 | Some(0i64), |
| 72 | - created_by, | 72 | + created_by.uuid(), |
| 73 | - created_at, | 73 | + created_at.as_millis(), |
| 74 | ) | 74 | ) |
| 75 | .fetch_optional(&mut *tx) | 75 | .fetch_optional(&mut *tx) |
| 76 | .await | 76 | .await |
| @@ -102,7 +102,7 @@ pub async fn create( | |||
| 102 | pub async fn read(db: &Database, id: &MenuId) -> Result<Option<Menu>, AppError> { | 102 | pub async fn read(db: &Database, id: &MenuId) -> Result<Option<Menu>, AppError> { |
| 103 | let row = sqlx::query_as!( | 103 | let row = sqlx::query_as!( |
| 104 | Menu, | 104 | Menu, |
| 105 | - "SELECT id, date, slot, capacity, version, created_by, created_at | 105 | + "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\" |
| 106 | FROM menu WHERE id = $1", | 106 | FROM menu WHERE id = $1", |
| 107 | id.key(), | 107 | id.key(), |
| 108 | ) | 108 | ) |
| @@ -119,7 +119,7 @@ pub async fn find( | |||
| 119 | ) -> Result<Option<Menu>, AppError> { | 119 | ) -> Result<Option<Menu>, AppError> { |
| 120 | let row = sqlx::query_as!( | 120 | let row = sqlx::query_as!( |
| 121 | Menu, | 121 | Menu, |
| 122 | - "SELECT id, date, slot, capacity, version, created_by, created_at | 122 | + "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\" |
| 123 | FROM menu WHERE date = $1 AND slot = $2 LIMIT 1", | 123 | FROM menu WHERE date = $1 AND slot = $2 LIMIT 1", |
| 124 | date.as_str(), | 124 | date.as_str(), |
| 125 | slot.as_str(), | 125 | slot.as_str(), |
| @@ -174,7 +174,7 @@ pub async fn update( | |||
| 174 | Menu, | 174 | Menu, |
| 175 | "UPDATE menu SET capacity = $2, version = COALESCE(version, 0) + 1 | 175 | "UPDATE menu SET capacity = $2, version = COALESCE(version, 0) + 1 |
| 176 | WHERE id = $1 | 176 | WHERE id = $1 |
| 177 | - RETURNING id, date, slot, capacity, version, created_by, created_at", | 177 | + 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\"", |
| 178 | menu.id.key(), | 178 | menu.id.key(), |
| 179 | capacity, | 179 | capacity, |
| 180 | ) | 180 | ) |
| @@ -217,11 +217,11 @@ pub async fn update( | |||
| 217 | pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> { | 217 | pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> { |
| 218 | let key = menu.id.key().to_string(); | 218 | let key = menu.id.key().to_string(); |
| 219 | let counter = slot_ref(menu.slot.as_str()); | 219 | let counter = slot_ref(menu.slot.as_str()); |
| 220 | - let deleted = tx_with_retry(db, true, async |tx| { | 220 | + let deleted = tx_with_retry(db, true, async move |tx| { |
| 221 | let deleted = sqlx::query_as!( | 221 | let deleted = sqlx::query_as!( |
| 222 | Menu, | 222 | Menu, |
| 223 | "DELETE FROM menu WHERE id = $1 AND seats_booked = 0 | 223 | "DELETE FROM menu WHERE id = $1 AND seats_booked = 0 |
| 224 | - RETURNING id, date, slot, capacity, version, created_by, created_at", | 224 | + 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\"", |
| 225 | key, | 225 | key, |
| 226 | ) | 226 | ) |
| 227 | .fetch_optional(&mut *tx) | 227 | .fetch_optional(&mut *tx) |
src/db/menu_dish.rsmodified+21 -24
| @@ -32,7 +32,7 @@ pub async fn create( | |||
| 32 | let menu_key = menu.key().to_string(); | 32 | let menu_key = menu.key().to_string(); |
| 33 | let id = MenuDishId::generate(); | 33 | let id = MenuDishId::generate(); |
| 34 | let created_at = Timestamp::now(); | 34 | let created_at = Timestamp::now(); |
| 35 | - tx_with_retry(db, false, async |tx| { | 35 | + tx_with_retry(db, false, async move |tx| { |
| 36 | // The lock first: every later statement in this transaction then | 36 | // The lock first: every later statement in this transaction then |
| 37 | // sees the committed state of whoever queued ahead of it. | 37 | // sees the committed state of whoever queued ahead of it. |
| 38 | let locked = sqlx::query!( | 38 | let locked = sqlx::query!( |
| @@ -55,14 +55,14 @@ pub async fn create( | |||
| 55 | "INSERT INTO menu_dish (id, menu, name, description, price_minor, tags, created_at) | 55 | "INSERT INTO menu_dish (id, menu, name, description, price_minor, tags, created_at) |
| 56 | SELECT $1, $2, $3, $4, $5, $6, $7 | 56 | SELECT $1, $2, $3, $4, $5, $6, $7 |
| 57 | WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $8 | 57 | WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $8 |
| 58 | - RETURNING id, menu, name, description, price_minor, tags, created_at", | 58 | + 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\"", |
| 59 | - id, | 59 | + id.uuid(), |
| 60 | menu_key, | 60 | menu_key, |
| 61 | - name, | 61 | + name.as_str(), |
| 62 | - description, | 62 | + description.as_ref().map(|d| d.as_str()), |
| 63 | - price_minor, | 63 | + price_minor.as_minor(), |
| 64 | - tags, | 64 | + tags.as_slice(), |
| 65 | - created_at, | 65 | + created_at.as_millis(), |
| 66 | cap, | 66 | cap, |
| 67 | ) | 67 | ) |
| 68 | .fetch_optional(&mut *tx) | 68 | .fetch_optional(&mut *tx) |
| @@ -81,9 +81,9 @@ pub async fn create( | |||
| 81 | pub async fn read(db: &Database, id: &MenuDishId) -> Result<Option<MenuDish>, AppError> { | 81 | pub async fn read(db: &Database, id: &MenuDishId) -> Result<Option<MenuDish>, AppError> { |
| 82 | let row = sqlx::query_as!( | 82 | let row = sqlx::query_as!( |
| 83 | MenuDish, | 83 | MenuDish, |
| 84 | - "SELECT id, menu, name, description, price_minor, tags, created_at | 84 | + "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\" |
| 85 | FROM menu_dish WHERE id = $1", | 85 | FROM menu_dish WHERE id = $1", |
| 86 | - id.key(), | 86 | + id.uuid(), |
| 87 | ) | 87 | ) |
| 88 | .fetch_optional(db) | 88 | .fetch_optional(db) |
| 89 | .await?; | 89 | .await?; |
| @@ -104,9 +104,9 @@ pub async fn list_for_menus(db: &Database, menus: &[MenuId]) -> Result<Vec<MenuD | |||
| 104 | let keys: Vec<String> = menus.iter().map(|m| m.key().to_string()).collect(); | 104 | let keys: Vec<String> = menus.iter().map(|m| m.key().to_string()).collect(); |
| 105 | let rows = sqlx::query_as!( | 105 | let rows = sqlx::query_as!( |
| 106 | MenuDish, | 106 | MenuDish, |
| 107 | - "SELECT id, menu, name, description, price_minor, tags, created_at | 107 | + "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\" |
| 108 | FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC", | 108 | FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC", |
| 109 | - keys, | 109 | + &keys, |
| 110 | ) | 110 | ) |
| 111 | .fetch_all(db) | 111 | .fetch_all(db) |
| 112 | .await?; | 112 | .await?; |
| @@ -131,9 +131,9 @@ pub async fn update( | |||
| 131 | price_minor: Option<DishPrice>, | 131 | price_minor: Option<DishPrice>, |
| 132 | tags: Option<DishTags>, | 132 | tags: Option<DishTags>, |
| 133 | ) -> Result<MenuDish, AppError> { | 133 | ) -> Result<MenuDish, AppError> { |
| 134 | - let dish_key = dish.id.key(); | 134 | + let dish_key = dish.id.uuid(); |
| 135 | let menu_key = dish.menu.key().to_string(); | 135 | let menu_key = dish.menu.key().to_string(); |
| 136 | - tx_with_retry(db, false, async |tx| { | 136 | + tx_with_retry(db, false, async move |tx| { |
| 137 | let bumped = sqlx::query!( | 137 | let bumped = sqlx::query!( |
| 138 | "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 | 138 | "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 |
| 139 | RETURNING 1 AS bumped", | 139 | RETURNING 1 AS bumped", |
| @@ -152,16 +152,13 @@ pub async fn update( | |||
| 152 | price_minor = COALESCE($5, price_minor), | 152 | price_minor = COALESCE($5, price_minor), |
| 153 | tags = COALESCE($6, tags) | 153 | tags = COALESCE($6, tags) |
| 154 | WHERE id = $1 | 154 | WHERE id = $1 |
| 155 | - RETURNING id, menu, name, description, price_minor, tags, created_at", | 155 | + 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\"", |
| 156 | dish_key, | 156 | dish_key, |
| 157 | - name.map(|n| n.as_str().to_string()), | 157 | + name.as_ref().map(|n| n.as_str()), |
| 158 | description.is_some(), | 158 | description.is_some(), |
| 159 | - description | 159 | + description.as_ref().and_then(|d| d.as_ref()).map(|d| d.as_str()), |
| 160 | - .clone() | ||
| 161 | - .flatten() | ||
| 162 | - .map(|d| d.as_str().to_string()), | ||
| 163 | price_minor.map(DishPrice::as_minor), | 160 | price_minor.map(DishPrice::as_minor), |
| 164 | - tags.map(|t| t.as_slice().to_vec()), | 161 | + tags.as_ref().map(|t| t.as_slice()), |
| 165 | ) | 162 | ) |
| 166 | .fetch_optional(&mut *tx) | 163 | .fetch_optional(&mut *tx) |
| 167 | .await?; | 164 | .await?; |
| @@ -171,9 +168,9 @@ pub async fn update( | |||
| 171 | } | 168 | } |
| 172 | 169 | ||
| 173 | pub async fn delete(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> { | 170 | pub async fn delete(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> { |
| 174 | - let dish_key = dish.id.key(); | 171 | + let dish_key = dish.id.uuid(); |
| 175 | let menu_key = dish.menu.key().to_string(); | 172 | let menu_key = dish.menu.key().to_string(); |
| 176 | - tx_with_retry(db, false, async |tx| { | 173 | + tx_with_retry(db, false, async move |tx| { |
| 177 | let bumped = sqlx::query!( | 174 | let bumped = sqlx::query!( |
| 178 | "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 | 175 | "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1 |
| 179 | RETURNING 1 AS bumped", | 176 | RETURNING 1 AS bumped", |
| @@ -187,7 +184,7 @@ pub async fn delete(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> | |||
| 187 | let row = sqlx::query_as!( | 184 | let row = sqlx::query_as!( |
| 188 | MenuDish, | 185 | MenuDish, |
| 189 | "DELETE FROM menu_dish WHERE id = $1 | 186 | "DELETE FROM menu_dish WHERE id = $1 |
| 190 | - RETURNING id, menu, name, description, price_minor, tags, created_at", | 187 | + 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\"", |
| 191 | dish_key, | 188 | dish_key, |
| 192 | ) | 189 | ) |
| 193 | .fetch_optional(&mut *tx) | 190 | .fetch_optional(&mut *tx) |
src/db/message.rsmodified+10 -10
| @@ -27,7 +27,7 @@ pub async fn send( | |||
| 27 | sender_folder, recipient_folder, sender_origin, recipient_origin) | 27 | sender_folder, recipient_folder, sender_origin, recipient_origin) |
| 28 | VALUES ($1, $2, $3, $4, $5, $6, $7, false, 'sent', 'inbox', NULL, NULL) | 28 | VALUES ($1, $2, $3, $4, $5, $6, $7, false, 'sent', 'inbox', NULL, NULL) |
| 29 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ | 29 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ |
| 30 | - subject, body, label AS \"label: MessageLabel\", \ | 30 | + subject AS \"subject: MessageSubject\", body AS \"body: MessageBody\", label AS \"label: MessageLabel\", \ |
| 31 | sent_at AS \"sent_at: Timestamp\", read, \ | 31 | sent_at AS \"sent_at: Timestamp\", read, \ |
| 32 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ | 32 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ |
| 33 | sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", | 33 | sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", |
| @@ -83,7 +83,7 @@ pub async fn list_folder( | |||
| 83 | if read.is_some() { | 83 | if read.is_some() { |
| 84 | from.push_str(&format!(" AND read = ${}", if home_arm { 3 } else { 2 })); | 84 | from.push_str(&format!(" AND read = ${}", if home_arm { 3 } else { 2 })); |
| 85 | } | 85 | } |
| 86 | - let mut builder = PagedList::new(from, "ORDER BY id DESC").bind(user); | 86 | + let mut builder = PagedList::new(from, "ORDER BY id DESC").bind(user.uuid()); |
| 87 | if home_arm { | 87 | if home_arm { |
| 88 | builder = builder.bind(folder.as_str().to_string()); | 88 | builder = builder.bind(folder.as_str().to_string()); |
| 89 | } | 89 | } |
| @@ -103,7 +103,7 @@ pub async fn read_for( | |||
| 103 | let message = query_as!( | 103 | let message = query_as!( |
| 104 | Message, | 104 | Message, |
| 105 | "SELECT id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ | 105 | "SELECT id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ |
| 106 | - subject, body, label AS \"label: MessageLabel\", \ | 106 | + subject AS \"subject: MessageSubject\", body AS \"body: MessageBody\", label AS \"label: MessageLabel\", \ |
| 107 | sent_at AS \"sent_at: Timestamp\", read, \ | 107 | sent_at AS \"sent_at: Timestamp\", read, \ |
| 108 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ | 108 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ |
| 109 | sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\" \ | 109 | 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<Mes | |||
| 125 | Message, | 125 | Message, |
| 126 | "UPDATE message SET read = $1 WHERE id = $2 \ | 126 | "UPDATE message SET read = $1 WHERE id = $2 \ |
| 127 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ | 127 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ |
| 128 | - subject, body, label AS \"label: MessageLabel\", \ | 128 | + subject AS \"subject: MessageSubject\", body AS \"body: MessageBody\", label AS \"label: MessageLabel\", \ |
| 129 | sent_at AS \"sent_at: Timestamp\", read, \ | 129 | sent_at AS \"sent_at: Timestamp\", read, \ |
| 130 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ | 130 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ |
| 131 | sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", | 131 | sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", |
| 132 | read, | 132 | read, |
| 133 | - message.get_id(), | 133 | + message.get_id().uuid(), |
| 134 | ) | 134 | ) |
| 135 | .fetch_optional(db) | 135 | .fetch_optional(db) |
| 136 | .await?; | 136 | .await?; |
| @@ -169,7 +169,7 @@ pub async fn move_to( | |||
| 169 | Message, | 169 | Message, |
| 170 | "UPDATE message SET sender_folder = $1, sender_origin = $2 WHERE id = $3 \ | 170 | "UPDATE message SET sender_folder = $1, sender_origin = $2 WHERE id = $3 \ |
| 171 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ | 171 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ |
| 172 | - subject, body, label AS \"label: MessageLabel\", \ | 172 | + subject AS \"subject: MessageSubject\", body AS \"body: MessageBody\", label AS \"label: MessageLabel\", \ |
| 173 | sent_at AS \"sent_at: Timestamp\", read, \ | 173 | sent_at AS \"sent_at: Timestamp\", read, \ |
| 174 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ | 174 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ |
| 175 | sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", | 175 | sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", |
| @@ -184,7 +184,7 @@ pub async fn move_to( | |||
| 184 | Message, | 184 | Message, |
| 185 | "UPDATE message SET recipient_folder = $1, recipient_origin = $2 WHERE id = $3 \ | 185 | "UPDATE message SET recipient_folder = $1, recipient_origin = $2 WHERE id = $3 \ |
| 186 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ | 186 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ |
| 187 | - subject, body, label AS \"label: MessageLabel\", \ | 187 | + subject AS \"subject: MessageSubject\", body AS \"body: MessageBody\", label AS \"label: MessageLabel\", \ |
| 188 | sent_at AS \"sent_at: Timestamp\", read, \ | 188 | sent_at AS \"sent_at: Timestamp\", read, \ |
| 189 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ | 189 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ |
| 190 | sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", | 190 | sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", |
| @@ -211,7 +211,7 @@ pub async fn delete_for(db: &Database, message: Message, user: &UserId) -> Resul | |||
| 211 | "UPDATE message SET sender_folder = 'deleted', sender_origin = NULL \ | 211 | "UPDATE message SET sender_folder = 'deleted', sender_origin = NULL \ |
| 212 | WHERE id = $1 AND sender_folder = 'trash' \ | 212 | WHERE id = $1 AND sender_folder = 'trash' \ |
| 213 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ | 213 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ |
| 214 | - subject, body, label AS \"label: MessageLabel\", \ | 214 | + subject AS \"subject: MessageSubject\", body AS \"body: MessageBody\", label AS \"label: MessageLabel\", \ |
| 215 | sent_at AS \"sent_at: Timestamp\", read, \ | 215 | sent_at AS \"sent_at: Timestamp\", read, \ |
| 216 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ | 216 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ |
| 217 | sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", | 217 | 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 | |||
| 225 | "UPDATE message SET recipient_folder = 'deleted', recipient_origin = NULL \ | 225 | "UPDATE message SET recipient_folder = 'deleted', recipient_origin = NULL \ |
| 226 | WHERE id = $1 AND recipient_folder = 'trash' \ | 226 | WHERE id = $1 AND recipient_folder = 'trash' \ |
| 227 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ | 227 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ |
| 228 | - subject, body, label AS \"label: MessageLabel\", \ | 228 | + subject AS \"subject: MessageSubject\", body AS \"body: MessageBody\", label AS \"label: MessageLabel\", \ |
| 229 | sent_at AS \"sent_at: Timestamp\", read, \ | 229 | sent_at AS \"sent_at: Timestamp\", read, \ |
| 230 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ | 230 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ |
| 231 | sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", | 231 | 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 | |||
| 244 | Message, | 244 | Message, |
| 245 | "DELETE FROM message WHERE id = $1 \ | 245 | "DELETE FROM message WHERE id = $1 \ |
| 246 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ | 246 | RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ |
| 247 | - subject, body, label AS \"label: MessageLabel\", \ | 247 | + subject AS \"subject: MessageSubject\", body AS \"body: MessageBody\", label AS \"label: MessageLabel\", \ |
| 248 | sent_at AS \"sent_at: Timestamp\", read, \ | 248 | sent_at AS \"sent_at: Timestamp\", read, \ |
| 249 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ | 249 | sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ |
| 250 | sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", | 250 | sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", |
src/db/note.rsmodified+19 -14
| @@ -5,7 +5,7 @@ use crate::database::{Database, tx_with_retry}; | |||
| 5 | use crate::db::field_update::FieldUpdate; | 5 | use crate::db::field_update::FieldUpdate; |
| 6 | use crate::db::page::PagedList; | 6 | use crate::db::page::PagedList; |
| 7 | use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; | 7 | use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; |
| 8 | -use crate::domain::note_file::NoteFile; | 8 | +use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId}; |
| 9 | use crate::domain::user::UserId; | 9 | use crate::domain::user::UserId; |
| 10 | use crate::error::AppError; | 10 | use crate::error::AppError; |
| 11 | 11 | ||
| @@ -26,11 +26,12 @@ pub async fn create( | |||
| 26 | Note, | 26 | Note, |
| 27 | r#"INSERT INTO note (id, app_user, title, content) | 27 | r#"INSERT INTO note (id, app_user, title, content) |
| 28 | VALUES ($1, $2, $3, $4) | 28 | VALUES ($1, $2, $3, $4) |
| 29 | - RETURNING id, app_user AS "user", title, content"#, | 29 | + RETURNING id AS "id: NoteId", app_user AS "user: UserId", |
| 30 | - note.id, | 30 | + title AS "title: NoteTitle", content AS "content: NoteContent""#, |
| 31 | - note.user, | 31 | + note.id.uuid(), |
| 32 | - note.title, | 32 | + note.user.uuid(), |
| 33 | - note.content | 33 | + note.title.as_str(), |
| 34 | + note.content.as_str() | ||
| 34 | ) | 35 | ) |
| 35 | .fetch_one(db) | 36 | .fetch_one(db) |
| 36 | .await?; | 37 | .await?; |
| @@ -45,9 +46,10 @@ pub async fn read_owned( | |||
| 45 | ) -> Result<Option<Note>, AppError> { | 46 | ) -> Result<Option<Note>, AppError> { |
| 46 | let note = sqlx::query_as!( | 47 | let note = sqlx::query_as!( |
| 47 | Note, | 48 | Note, |
| 48 | - r#"SELECT id, app_user AS "user", title, content FROM note WHERE id = $1 AND app_user = $2"#, | 49 | + r#"SELECT id AS "id: NoteId", app_user AS "user: UserId", |
| 49 | - id, | 50 | + title AS "title: NoteTitle", content AS "content: NoteContent" FROM note WHERE id = $1 AND app_user = $2"#, |
| 50 | - owner | 51 | + id.uuid(), |
| 52 | + owner.uuid() | ||
| 51 | ) | 53 | ) |
| 52 | .fetch_optional(db) | 54 | .fetch_optional(db) |
| 53 | .await?; | 55 | .await?; |
| @@ -106,20 +108,23 @@ pub async fn update( | |||
| 106 | /// separate `delete_for_note` call stays, as a harmless idempotent repeat. | 108 | /// separate `delete_for_note` call stays, as a harmless idempotent repeat. |
| 107 | pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> { | 109 | pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> { |
| 108 | tx_with_retry(db, true, async |conn| { | 110 | tx_with_retry(db, true, async |conn| { |
| 109 | - sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id) | 111 | + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id.uuid()) |
| 110 | .execute(&mut *conn) | 112 | .execute(&mut *conn) |
| 111 | .await?; | 113 | .await?; |
| 112 | let files = sqlx::query_as!( | 114 | let files = sqlx::query_as!( |
| 113 | NoteFile, | 115 | NoteFile, |
| 114 | - r#"DELETE FROM note_file WHERE note = $1 RETURNING id, note, name, content_type, size"#, | 116 | + r#"DELETE FROM note_file WHERE note = $1 |
| 115 | - note.id | 117 | + RETURNING id AS "id: NoteFileId", note AS "note: NoteId", name AS "name: FileName", |
| 118 | + content_type AS "content_type: FileContentType", size"#, | ||
| 119 | + note.id.uuid() | ||
| 116 | ) | 120 | ) |
| 117 | .fetch_all(&mut *conn) | 121 | .fetch_all(&mut *conn) |
| 118 | .await?; | 122 | .await?; |
| 119 | let gone = sqlx::query_as!( | 123 | let gone = sqlx::query_as!( |
| 120 | Note, | 124 | Note, |
| 121 | - r#"DELETE FROM note WHERE id = $1 RETURNING id, app_user AS "user", title, content"#, | 125 | + r#"DELETE FROM note WHERE id = $1 RETURNING id AS "id: NoteId", app_user AS "user: UserId", |
| 122 | - note.id | 126 | + title AS "title: NoteTitle", content AS "content: NoteContent""#, |
| 127 | + note.id.uuid() | ||
| 123 | ) | 128 | ) |
| 124 | .fetch_optional(&mut *conn) | 129 | .fetch_optional(&mut *conn) |
| 125 | .await?; | 130 | .await?; |
src/db/note_file.rsmodified+15 -12
| @@ -6,7 +6,7 @@ use crate::constant::MAX_NOTE_FILES; | |||
| 6 | use crate::database::{Database, tx_with_retry, unique_violation}; | 6 | use crate::database::{Database, tx_with_retry, unique_violation}; |
| 7 | use crate::db::page::PagedList; | 7 | use crate::db::page::PagedList; |
| 8 | use crate::domain::note::NoteId; | 8 | use crate::domain::note::NoteId; |
| 9 | -use crate::domain::note_file::{NoteFile, NoteFileId}; | 9 | +use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId}; |
| 10 | use crate::error::AppError; | 10 | use crate::error::AppError; |
| 11 | 11 | ||
| 12 | /// Persist the row assembled by [`NoteFile::new`], refusing once its note | 12 | /// Persist the row assembled by [`NoteFile::new`], refusing once its note |
| @@ -28,12 +28,13 @@ pub async fn insert(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> | |||
| 28 | RETURNING 1) | 28 | RETURNING 1) |
| 29 | INSERT INTO note_file (id, note, name, content_type, size) | 29 | INSERT INTO note_file (id, note, name, content_type, size) |
| 30 | SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) | 30 | SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) |
| 31 | - RETURNING id, note, name, content_type, size"#, | 31 | + RETURNING id AS "id: NoteFileId", note AS "note: NoteId", name AS "name: FileName", |
| 32 | - file.note, | 32 | + content_type AS "content_type: FileContentType", size"#, |
| 33 | + file.note.uuid(), | ||
| 33 | MAX_NOTE_FILES as i64, | 34 | MAX_NOTE_FILES as i64, |
| 34 | - file.id, | 35 | + file.id.uuid(), |
| 35 | - file.name, | 36 | + file.name.as_str(), |
| 36 | - file.content_type, | 37 | + file.content_type.as_str(), |
| 37 | file.size | 38 | file.size |
| 38 | ) | 39 | ) |
| 39 | .fetch_optional(db) | 40 | .fetch_optional(db) |
| @@ -62,9 +63,10 @@ pub async fn read_for( | |||
| 62 | ) -> Result<Option<NoteFile>, AppError> { | 63 | ) -> Result<Option<NoteFile>, AppError> { |
| 63 | let file = sqlx::query_as!( | 64 | let file = sqlx::query_as!( |
| 64 | NoteFile, | 65 | NoteFile, |
| 65 | - r#"SELECT id, note, name, content_type, size FROM note_file WHERE id = $1 AND note = $2"#, | 66 | + r#"SELECT id AS "id: NoteFileId", note AS "note: NoteId", name AS "name: FileName", |
| 66 | - id, | 67 | + content_type AS "content_type: FileContentType", size FROM note_file WHERE id = $1 AND note = $2"#, |
| 67 | - note | 68 | + id.uuid(), |
| 69 | + note.uuid() | ||
| 68 | ) | 70 | ) |
| 69 | .fetch_optional(db) | 71 | .fetch_optional(db) |
| 70 | .await?; | 72 | .await?; |
| @@ -91,15 +93,16 @@ pub async fn delete(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> | |||
| 91 | tx_with_retry(db, true, async |conn| { | 93 | tx_with_retry(db, true, async |conn| { |
| 92 | let gone = sqlx::query_as!( | 94 | let gone = sqlx::query_as!( |
| 93 | NoteFile, | 95 | NoteFile, |
| 94 | - r#"DELETE FROM note_file WHERE id = $1 RETURNING id, note, name, content_type, size"#, | 96 | + r#"DELETE FROM note_file WHERE id = $1 RETURNING id AS "id: NoteFileId", note AS "note: NoteId", name AS "name: FileName", |
| 95 | - file.id | 97 | + content_type AS "content_type: FileContentType", size"#, |
| 98 | + file.id.uuid() | ||
| 96 | ) | 99 | ) |
| 97 | .fetch_optional(&mut *conn) | 100 | .fetch_optional(&mut *conn) |
| 98 | .await?; | 101 | .await?; |
| 99 | let file = gone.ok_or(AppError::NotFound)?; | 102 | let file = gone.ok_or(AppError::NotFound)?; |
| 100 | sqlx::query!( | 103 | sqlx::query!( |
| 101 | "UPDATE note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1", | 104 | "UPDATE note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1", |
| 102 | - file.note | 105 | + file.note.uuid() |
| 103 | ) | 106 | ) |
| 104 | .execute(&mut *conn) | 107 | .execute(&mut *conn) |
| 105 | .await?; | 108 | .await?; |
src/db/parent_link.rsmodified+1 -1
| @@ -38,7 +38,7 @@ pub async fn link( | |||
| 38 | /// role) is [`crate::service::parent_link::links_live`]. | 38 | /// role) is [`crate::service::parent_link::links_live`]. |
| 39 | pub async fn exists(db: &Database, parent: &UserId, student: &UserId) -> Result<bool, AppError> { | 39 | pub async fn exists(db: &Database, parent: &UserId, student: &UserId) -> Result<bool, AppError> { |
| 40 | let row = sqlx::query!( | 40 | let row = sqlx::query!( |
| 41 | - "SELECT EXISTS(SELECT 1 FROM parent_link WHERE parent = $1 AND student = $2) AS present", | 41 | + "SELECT EXISTS(SELECT 1 FROM parent_link WHERE parent = $1 AND student = $2) AS \"present!\"", |
| 42 | parent.uuid(), | 42 | parent.uuid(), |
| 43 | student.uuid() | 43 | student.uuid() |
| 44 | ) | 44 | ) |
src/db/payment_ledger.rsmodified+32 -23
| @@ -21,7 +21,9 @@ use crate::database::Database; | |||
| 21 | use crate::db::page::PagedList; | 21 | use crate::db::page::PagedList; |
| 22 | use crate::domain::fee_plan::Installment; | 22 | use crate::domain::fee_plan::Installment; |
| 23 | use crate::domain::fee_plan_assignment::FeePlanAssignment; | 23 | use crate::domain::fee_plan_assignment::FeePlanAssignment; |
| 24 | -use crate::domain::payment_ledger::{PaymentLedger, PaymentLedgerId, PaymentLedgerKind}; | 24 | +use crate::domain::payment_ledger::{ |
| 25 | + LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind, | ||
| 26 | +}; | ||
| 25 | use crate::domain::timestamp::Timestamp; | 27 | use crate::domain::timestamp::Timestamp; |
| 26 | use crate::domain::user::UserId; | 28 | use crate::domain::user::UserId; |
| 27 | use crate::error::AppError; | 29 | use crate::error::AppError; |
| @@ -56,28 +58,32 @@ pub(crate) async fn append( | |||
| 56 | ON CONFLICT (id) DO NOTHING | 58 | ON CONFLICT (id) DO NOTHING |
| 57 | RETURNING id, student, kind, amount_minor, source, due_at, method, note, | 59 | RETURNING id, student, kind, amount_minor, source, due_at, method, note, |
| 58 | recorded_by, created_at) | 60 | recorded_by, created_at) |
| 59 | - SELECT id AS "id!", student AS "student!", | 61 | + SELECT id AS "id!: PaymentLedgerId", student AS "student!: UserId", |
| 60 | kind AS "kind!: PaymentLedgerKind", | 62 | kind AS "kind!: PaymentLedgerKind", |
| 61 | - amount_minor AS "amount_minor!", source, due_at, method, note, | 63 | + amount_minor AS "amount_minor!: LedgerAmount", source, |
| 62 | - recorded_by AS "recorded_by!", created_at AS "created_at!" | 64 | + due_at AS "due_at: Timestamp", method AS "method: LedgerMethod", |
| 65 | + note AS "note: LedgerNote", | ||
| 66 | + recorded_by AS "recorded_by!: UserId", created_at AS "created_at!: Timestamp" | ||
| 63 | FROM ins | 67 | FROM ins |
| 64 | UNION ALL | 68 | UNION ALL |
| 65 | - SELECT id AS "id!", student AS "student!", | 69 | + SELECT id AS "id!: PaymentLedgerId", student AS "student!: UserId", |
| 66 | kind AS "kind!: PaymentLedgerKind", | 70 | kind AS "kind!: PaymentLedgerKind", |
| 67 | - amount_minor AS "amount_minor!", source, due_at, method, note, | 71 | + amount_minor AS "amount_minor!: LedgerAmount", source, |
| 68 | - recorded_by AS "recorded_by!", created_at AS "created_at!" | 72 | + due_at AS "due_at: Timestamp", method AS "method: LedgerMethod", |
| 73 | + note AS "note: LedgerNote", | ||
| 74 | + recorded_by AS "recorded_by!: UserId", created_at AS "created_at!: Timestamp" | ||
| 69 | FROM payment_ledger | 75 | FROM payment_ledger |
| 70 | WHERE id = $1 AND NOT EXISTS (SELECT 1 FROM ins)"#, | 76 | WHERE id = $1 AND NOT EXISTS (SELECT 1 FROM ins)"#, |
| 71 | - row.id, | 77 | + row.id.key(), |
| 72 | - row.student, | 78 | + row.student.uuid(), |
| 73 | - row.kind, | 79 | + row.kind.as_str(), |
| 74 | - row.amount_minor, | 80 | + row.amount_minor.as_minor(), |
| 75 | row.source, | 81 | row.source, |
| 76 | - row.due_at, | 82 | + row.due_at.map(|t| t.as_millis()), |
| 77 | - row.method, | 83 | + row.method.as_ref().map(|m| m.as_str()), |
| 78 | - row.note, | 84 | + row.note.as_ref().map(|n| n.as_str()), |
| 79 | - row.recorded_by, | 85 | + row.recorded_by.uuid(), |
| 80 | - row.created_at, | 86 | + row.created_at.as_millis(), |
| 81 | ) | 87 | ) |
| 82 | .fetch_optional(exe) | 88 | .fetch_optional(exe) |
| 83 | .await?; | 89 | .await?; |
| @@ -98,10 +104,13 @@ pub async fn read( | |||
| 98 | ) -> Result<Option<PaymentLedger>, AppError> { | 104 | ) -> Result<Option<PaymentLedger>, AppError> { |
| 99 | sqlx::query_as!( | 105 | sqlx::query_as!( |
| 100 | PaymentLedger, | 106 | PaymentLedger, |
| 101 | - "SELECT id, student, kind, amount_minor, source, due_at, method, note, \ | 107 | + "SELECT id AS \"id: PaymentLedgerId\", student AS \"student: UserId\", |
| 102 | - recorded_by, created_at \ | 108 | + kind AS \"kind: PaymentLedgerKind\", amount_minor AS \"amount_minor: LedgerAmount\", |
| 109 | + source, due_at AS \"due_at: Timestamp\", method AS \"method: LedgerMethod\", | ||
| 110 | + note AS \"note: LedgerNote\", recorded_by AS \"recorded_by: UserId\", | ||
| 111 | + created_at AS \"created_at: Timestamp\" | ||
| 103 | FROM payment_ledger WHERE id = $1", | 112 | FROM payment_ledger WHERE id = $1", |
| 104 | - id, | 113 | + id.key(), |
| 105 | ) | 114 | ) |
| 106 | .fetch_optional(exe) | 115 | .fetch_optional(exe) |
| 107 | .await | 116 | .await |
| @@ -125,7 +134,7 @@ pub async fn charge_for_installment( | |||
| 125 | append( | 134 | append( |
| 126 | exe, | 135 | exe, |
| 127 | PaymentLedger { | 136 | PaymentLedger { |
| 128 | - id: PaymentLedgerId::for_installment(assignment.get_id(), n), | 137 | + id: PaymentLedgerId::for_installment(&assignment.get_id(), n), |
| 129 | student: assignment.get_student().clone(), | 138 | student: assignment.get_student().clone(), |
| 130 | kind: PaymentLedgerKind::Charge, | 139 | kind: PaymentLedgerKind::Charge, |
| 131 | amount_minor: installment.get_amount_minor(), | 140 | amount_minor: installment.get_amount_minor(), |
| @@ -190,7 +199,7 @@ pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError | |||
| 190 | COALESCE(sum(amount_minor), 0)::bigint AS \"total!: i64\", \ | 199 | COALESCE(sum(amount_minor), 0)::bigint AS \"total!: i64\", \ |
| 191 | count(*)::bigint AS \"lines!: i64\" \ | 200 | count(*)::bigint AS \"lines!: i64\" \ |
| 192 | FROM payment_ledger WHERE student = $1 GROUP BY kind", | 201 | FROM payment_ledger WHERE student = $1 GROUP BY kind", |
| 193 | - student, | 202 | + student.uuid(), |
| 194 | ) | 203 | ) |
| 195 | .fetch_all(db) | 204 | .fetch_all(db) |
| 196 | .await?; | 205 | .await?; |
| @@ -223,14 +232,14 @@ pub(crate) async fn lock_for_cap( | |||
| 223 | let row = sqlx::query!( | 232 | let row = sqlx::query!( |
| 224 | r#"SELECT kind AS "kind: PaymentLedgerKind", source | 233 | r#"SELECT kind AS "kind: PaymentLedgerKind", source |
| 225 | FROM payment_ledger WHERE id = $1 FOR UPDATE"#, | 234 | FROM payment_ledger WHERE id = $1 FOR UPDATE"#, |
| 226 | - key, | 235 | + key.key(), |
| 227 | ) | 236 | ) |
| 228 | .fetch_optional(&mut *exe) | 237 | .fetch_optional(&mut *exe) |
| 229 | .await?; | 238 | .await?; |
| 230 | next = match row { | 239 | next = match row { |
| 231 | // Keep walking while the row points at another *ledger* row. | 240 | // Keep walking while the row points at another *ledger* row. |
| 232 | Some(row) if row.kind != PaymentLedgerKind::Charge => { | 241 | Some(row) if row.kind != PaymentLedgerKind::Charge => { |
| 233 | - row.source.map(PaymentLedgerId::from_key) | 242 | + row.source.map(|s| PaymentLedgerId::from_key(&s)) |
| 234 | } | 243 | } |
| 235 | // A charge's source is an assignment key, not a ledger row — | 244 | // A charge's source is an assignment key, not a ledger row — |
| 236 | // and by then the root lock is held, which is the point. | 245 | // and by then the root lock is held, which is the point. |
src/db/pomodoro.rsmodified+5 -2
| @@ -126,7 +126,10 @@ pub async fn start( | |||
| 126 | pub async fn finish(db: &Database, user: &UserId) -> Result<PomodoroSession, AppError> { | 126 | pub async fn finish(db: &Database, user: &UserId) -> Result<PomodoroSession, AppError> { |
| 127 | let done = Timestamp::now(); | 127 | let done = Timestamp::now(); |
| 128 | let day = done.day_number(); | 128 | let day = done.day_number(); |
| 129 | - let saved = tx_with_retry(db, false, async |tx| { | 129 | + // Owned capture: an `async move` closure holding a `&UserId` fails the |
| 130 | + // higher-ranked `Send` check `tx_with_retry`'s future must pass. | ||
| 131 | + let user = *user; | ||
| 132 | + let saved = tx_with_retry(db, false, async move |tx| { | ||
| 130 | // Take the open row. Empty means nothing is running. | 133 | // Take the open row. Empty means nothing is running. |
| 131 | let open = sqlx::query!( | 134 | let open = sqlx::query!( |
| 132 | "DELETE FROM pomodoro_session | 135 | "DELETE FROM pomodoro_session |
| @@ -222,7 +225,7 @@ pub async fn finish(db: &Database, user: &UserId) -> Result<PomodoroSession, App | |||
| 222 | // A badge is a decoration on top of the stint: losing one to a | 225 | // A badge is a decoration on top of the stint: losing one to a |
| 223 | // transient database error must never fail the finish, and the next | 226 | // transient database error must never fail the finish, and the next |
| 224 | // counter move re-runs this and heals it. | 227 | // counter move re-runs this and heals it. |
| 225 | - if let Err(err) = crate::db::badge::sync(db, user).await { | 228 | + if let Err(err) = crate::db::badge::sync(db, &user).await { |
| 226 | tracing::warn!("failed to sync badges for {}: {err}", user.key()); | 229 | tracing::warn!("failed to sync badges for {}: {err}", user.key()); |
| 227 | } | 230 | } |
| 228 | Ok(saved) | 231 | Ok(saved) |
src/db/pool_question.rsmodified+83 -29
| @@ -7,8 +7,11 @@ | |||
| 7 | use crate::constant::{STATUS_APPROVED, STATUS_PENDING}; | 7 | use crate::constant::{STATUS_APPROVED, STATUS_PENDING}; |
| 8 | use crate::database::{Database, tx_with_retry}; | 8 | use crate::database::{Database, tx_with_retry}; |
| 9 | use crate::domain::note_file::FileContentType; | 9 | use crate::domain::note_file::FileContentType; |
| 10 | -use crate::domain::pool_question::{PoolQuestion, PoolQuestionId}; | 10 | +use crate::domain::pool_question::{ |
| 11 | -use crate::domain::solution::Solution; | 11 | + PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle, |
| 12 | +}; | ||
| 13 | +use crate::domain::solution::{Solution, SolutionBody, SolutionId}; | ||
| 14 | +use crate::domain::timestamp::Timestamp; | ||
| 12 | use crate::domain::user::UserId; | 15 | use crate::domain::user::UserId; |
| 13 | use crate::error::AppError; | 16 | use crate::error::AppError; |
| 14 | 17 | ||
| @@ -17,13 +20,18 @@ pub async fn insert(db: &Database, question: PoolQuestion) -> Result<PoolQuestio | |||
| 17 | PoolQuestion, | 20 | PoolQuestion, |
| 18 | r#"INSERT INTO pool_question (id, asker, title, body, status, asked_at) | 21 | r#"INSERT INTO pool_question (id, asker, title, body, status, asked_at) |
| 19 | VALUES ($1, $2, $3, $4, $5, $6) | 22 | VALUES ($1, $2, $3, $4, $5, $6) |
| 20 | - RETURNING *"#, | 23 | + RETURNING id AS "id: PoolQuestionId", asker AS "asker: UserId", |
| 21 | - question.id, | 24 | + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", |
| 22 | - question.asker, | 25 | + status, asked_at AS "asked_at: Timestamp", |
| 23 | - question.title, | 26 | + approved_by AS "approved_by: Option<UserId>", image_file, |
| 24 | - question.body, | 27 | + image_content_type AS "image_content_type: Option<FileContentType>", |
| 28 | + image_size"#, | ||
| 29 | + question.id.uuid(), | ||
| 30 | + question.asker.uuid(), | ||
| 31 | + question.title.as_str(), | ||
| 32 | + question.body.as_str(), | ||
| 25 | question.status, | 33 | question.status, |
| 26 | - question.asked_at, | 34 | + question.asked_at.as_millis(), |
| 27 | ) | 35 | ) |
| 28 | .fetch_one(db) | 36 | .fetch_one(db) |
| 29 | .await?; | 37 | .await?; |
| @@ -33,8 +41,14 @@ pub async fn insert(db: &Database, question: PoolQuestion) -> Result<PoolQuestio | |||
| 33 | pub async fn read(db: &Database, id: &PoolQuestionId) -> Result<Option<PoolQuestion>, AppError> { | 41 | pub async fn read(db: &Database, id: &PoolQuestionId) -> Result<Option<PoolQuestion>, AppError> { |
| 34 | let row = sqlx::query_as!( | 42 | let row = sqlx::query_as!( |
| 35 | PoolQuestion, | 43 | PoolQuestion, |
| 36 | - "SELECT * FROM pool_question WHERE id = $1", | 44 | + r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", |
| 37 | - id | 45 | + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", |
| 46 | + status, asked_at AS "asked_at: Timestamp", | ||
| 47 | + approved_by AS "approved_by: Option<UserId>", image_file, | ||
| 48 | + image_content_type AS "image_content_type: Option<FileContentType>", | ||
| 49 | + image_size | ||
| 50 | + FROM pool_question WHERE id = $1"#, | ||
| 51 | + id.uuid() | ||
| 38 | ) | 52 | ) |
| 39 | .fetch_optional(db) | 53 | .fetch_optional(db) |
| 40 | .await?; | 54 | .await?; |
| @@ -46,7 +60,13 @@ pub async fn read(db: &Database, id: &PoolQuestionId) -> Result<Option<PoolQuest | |||
| 46 | pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> { | 60 | pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> { |
| 47 | let rows = sqlx::query_as!( | 61 | let rows = sqlx::query_as!( |
| 48 | PoolQuestion, | 62 | PoolQuestion, |
| 49 | - "SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC", | 63 | + r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", |
| 64 | + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", | ||
| 65 | + status, asked_at AS "asked_at: Timestamp", | ||
| 66 | + approved_by AS "approved_by: Option<UserId>", image_file, | ||
| 67 | + image_content_type AS "image_content_type: Option<FileContentType>", | ||
| 68 | + image_size | ||
| 69 | + FROM pool_question ORDER BY asked_at DESC, id DESC"#, | ||
| 50 | ) | 70 | ) |
| 51 | .fetch_all(db) | 71 | .fetch_all(db) |
| 52 | .await?; | 72 | .await?; |
| @@ -58,11 +78,17 @@ pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> { | |||
| 58 | pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQuestion>, AppError> { | 78 | pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQuestion>, AppError> { |
| 59 | let rows = sqlx::query_as!( | 79 | let rows = sqlx::query_as!( |
| 60 | PoolQuestion, | 80 | PoolQuestion, |
| 61 | - r#"SELECT * FROM pool_question | 81 | + r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", |
| 82 | + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", | ||
| 83 | + status, asked_at AS "asked_at: Timestamp", | ||
| 84 | + approved_by AS "approved_by: Option<UserId>", image_file, | ||
| 85 | + image_content_type AS "image_content_type: Option<FileContentType>", | ||
| 86 | + image_size | ||
| 87 | + FROM pool_question | ||
| 62 | WHERE status = $1 OR asker = $2 | 88 | WHERE status = $1 OR asker = $2 |
| 63 | ORDER BY asked_at DESC, id DESC"#, | 89 | ORDER BY asked_at DESC, id DESC"#, |
| 64 | STATUS_APPROVED, | 90 | STATUS_APPROVED, |
| 65 | - user | 91 | + user.uuid() |
| 66 | ) | 92 | ) |
| 67 | .fetch_all(db) | 93 | .fetch_all(db) |
| 68 | .await?; | 94 | .await?; |
| @@ -111,10 +137,15 @@ pub async fn approve( | |||
| 111 | PoolQuestion, | 137 | PoolQuestion, |
| 112 | r#"UPDATE pool_question SET status = $2, approved_by = $3 | 138 | r#"UPDATE pool_question SET status = $2, approved_by = $3 |
| 113 | WHERE id = $1 AND status = $4 | 139 | WHERE id = $1 AND status = $4 |
| 114 | - RETURNING *"#, | 140 | + RETURNING id AS "id: PoolQuestionId", asker AS "asker: UserId", |
| 115 | - *id, | 141 | + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", |
| 142 | + status, asked_at AS "asked_at: Timestamp", | ||
| 143 | + approved_by AS "approved_by: Option<UserId>", image_file, | ||
| 144 | + image_content_type AS "image_content_type: Option<FileContentType>", | ||
| 145 | + image_size"#, | ||
| 146 | + id.uuid(), | ||
| 116 | STATUS_APPROVED, | 147 | STATUS_APPROVED, |
| 117 | - approver, | 148 | + approver.uuid(), |
| 118 | STATUS_PENDING, | 149 | STATUS_PENDING, |
| 119 | ) | 150 | ) |
| 120 | .fetch_optional(tx) | 151 | .fetch_optional(tx) |
| @@ -126,14 +157,14 @@ pub async fn approve( | |||
| 126 | sqlx::query!( | 157 | sqlx::query!( |
| 127 | "UPDATE app_user SET pool_approved_total = pool_approved_total + 1 | 158 | "UPDATE app_user SET pool_approved_total = pool_approved_total + 1 |
| 128 | WHERE id = $1", | 159 | WHERE id = $1", |
| 129 | - approver | 160 | + approver.uuid() |
| 130 | ) | 161 | ) |
| 131 | .execute(tx) | 162 | .execute(tx) |
| 132 | .await?; | 163 | .await?; |
| 133 | sqlx::query!( | 164 | sqlx::query!( |
| 134 | "UPDATE app_user SET pool_published_total = pool_published_total + 1 | 165 | "UPDATE app_user SET pool_published_total = pool_published_total + 1 |
| 135 | WHERE id = $1", | 166 | WHERE id = $1", |
| 136 | - question.asker | 167 | + question.asker.uuid() |
| 137 | ) | 168 | ) |
| 138 | .execute(tx) | 169 | .execute(tx) |
| 139 | .await?; | 170 | .await?; |
| @@ -164,8 +195,14 @@ pub async fn set_image( | |||
| 164 | tx_with_retry(db, false, async |tx| { | 195 | tx_with_retry(db, false, async |tx| { |
| 165 | let before = sqlx::query_as!( | 196 | let before = sqlx::query_as!( |
| 166 | PoolQuestion, | 197 | PoolQuestion, |
| 167 | - "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE", | 198 | + r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", |
| 168 | - *id | 199 | + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", |
| 200 | + status, asked_at AS "asked_at: Timestamp", | ||
| 201 | + approved_by AS "approved_by: Option<UserId>", image_file, | ||
| 202 | + image_content_type AS "image_content_type: Option<FileContentType>", | ||
| 203 | + image_size | ||
| 204 | + FROM pool_question WHERE id = $1 FOR UPDATE"#, | ||
| 205 | + id.uuid() | ||
| 169 | ) | 206 | ) |
| 170 | .fetch_optional(tx) | 207 | .fetch_optional(tx) |
| 171 | .await?; | 208 | .await?; |
| @@ -176,9 +213,9 @@ pub async fn set_image( | |||
| 176 | r#"UPDATE pool_question | 213 | r#"UPDATE pool_question |
| 177 | SET image_file = $2, image_content_type = $3, image_size = $4 | 214 | SET image_file = $2, image_content_type = $3, image_size = $4 |
| 178 | WHERE id = $1 AND status = $5"#, | 215 | WHERE id = $1 AND status = $5"#, |
| 179 | - *id, | 216 | + id.uuid(), |
| 180 | file, | 217 | file, |
| 181 | - content_type, | 218 | + content_type.as_str(), |
| 182 | size, | 219 | size, |
| 183 | STATUS_PENDING, | 220 | STATUS_PENDING, |
| 184 | ) | 221 | ) |
| @@ -201,8 +238,14 @@ pub async fn clear_image( | |||
| 201 | tx_with_retry(db, false, async |tx| { | 238 | tx_with_retry(db, false, async |tx| { |
| 202 | let before = sqlx::query_as!( | 239 | let before = sqlx::query_as!( |
| 203 | PoolQuestion, | 240 | PoolQuestion, |
| 204 | - "SELECT * FROM pool_question WHERE id = $1 FOR UPDATE", | 241 | + r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", |
| 205 | - *id | 242 | + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", |
| 243 | + status, asked_at AS "asked_at: Timestamp", | ||
| 244 | + approved_by AS "approved_by: Option<UserId>", image_file, | ||
| 245 | + image_content_type AS "image_content_type: Option<FileContentType>", | ||
| 246 | + image_size | ||
| 247 | + FROM pool_question WHERE id = $1 FOR UPDATE"#, | ||
| 248 | + id.uuid() | ||
| 206 | ) | 249 | ) |
| 207 | .fetch_optional(tx) | 250 | .fetch_optional(tx) |
| 208 | .await?; | 251 | .await?; |
| @@ -213,7 +256,7 @@ pub async fn clear_image( | |||
| 213 | r#"UPDATE pool_question | 256 | r#"UPDATE pool_question |
| 214 | SET image_file = NULL, image_content_type = NULL, image_size = NULL | 257 | SET image_file = NULL, image_content_type = NULL, image_size = NULL |
| 215 | WHERE id = $1 AND status = $2"#, | 258 | WHERE id = $1 AND status = $2"#, |
| 216 | - *id, | 259 | + id.uuid(), |
| 217 | STATUS_PENDING, | 260 | STATUS_PENDING, |
| 218 | ) | 261 | ) |
| 219 | .execute(tx) | 262 | .execute(tx) |
| @@ -244,15 +287,26 @@ pub async fn delete( | |||
| 244 | tx_with_retry(db, true, async |tx| { | 287 | tx_with_retry(db, true, async |tx| { |
| 245 | let solutions = sqlx::query_as!( | 288 | let solutions = sqlx::query_as!( |
| 246 | Solution, | 289 | Solution, |
| 247 | - "DELETE FROM solution WHERE question = $1 RETURNING *", | 290 | + r#"DELETE FROM solution WHERE question = $1 |
| 248 | - *id | 291 | + RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 292 | + author AS "author: UserId", body AS "body: SolutionBody", | ||
| 293 | + offered_at AS "offered_at: Timestamp", image_file, | ||
| 294 | + image_content_type AS "image_content_type: Option<FileContentType>", | ||
| 295 | + image_size"#, | ||
| 296 | + id.uuid() | ||
| 249 | ) | 297 | ) |
| 250 | .fetch_all(tx) | 298 | .fetch_all(tx) |
| 251 | .await?; | 299 | .await?; |
| 252 | let question = sqlx::query_as!( | 300 | let question = sqlx::query_as!( |
| 253 | PoolQuestion, | 301 | PoolQuestion, |
| 254 | - "DELETE FROM pool_question WHERE id = $1 RETURNING *", | 302 | + r#"DELETE FROM pool_question WHERE id = $1 |
| 255 | - *id | 303 | + RETURNING id AS "id: PoolQuestionId", asker AS "asker: UserId", |
| 304 | + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", | ||
| 305 | + status, asked_at AS "asked_at: Timestamp", | ||
| 306 | + approved_by AS "approved_by: Option<UserId>", image_file, | ||
| 307 | + image_content_type AS "image_content_type: Option<FileContentType>", | ||
| 308 | + image_size"#, | ||
| 309 | + id.uuid() | ||
| 256 | ) | 310 | ) |
| 257 | .fetch_optional(tx) | 311 | .fetch_optional(tx) |
| 258 | .await?; | 312 | .await?; |
src/db/question_image.rsmodified+26 -23
| @@ -31,7 +31,7 @@ pub async fn upsert( | |||
| 31 | db: &Database, | 31 | db: &Database, |
| 32 | image: QuestionImage, | 32 | image: QuestionImage, |
| 33 | ) -> Result<(QuestionImage, Option<String>), AppError> { | 33 | ) -> Result<(QuestionImage, Option<String>), AppError> { |
| 34 | - tx_with_retry(db, false, async |conn| upsert_in(conn, image).await).await | 34 | + tx_with_retry(db, false, async |conn| upsert_in(conn, image.clone()).await).await |
| 35 | } | 35 | } |
| 36 | 36 | ||
| 37 | /// The gated read-and-replace, on one connection. | 37 | /// The gated read-and-replace, on one connection. |
| @@ -49,13 +49,13 @@ pub(crate) async fn upsert_in( | |||
| 49 | SET file = EXCLUDED.file, content_type = EXCLUDED.content_type, | 49 | SET file = EXCLUDED.file, content_type = EXCLUDED.content_type, |
| 50 | size = EXCLUDED.size | 50 | size = EXCLUDED.size |
| 51 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", | 51 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 52 | - slot AS "slot: Option<ChoiceId>", file, | 52 | + slot AS "slot: ChoiceId", file, |
| 53 | content_type AS "content_type: FileContentType", size"#, | 53 | content_type AS "content_type: FileContentType", size"#, |
| 54 | - image.exam as &ExamId, | 54 | + image.exam.uuid(), |
| 55 | - image.question as &ExamQuestionId, | 55 | + image.question.uuid(), |
| 56 | - image.slot, | 56 | + image.slot.as_ref().map(ChoiceId::as_str), |
| 57 | image.file, | 57 | image.file, |
| 58 | - image.content_type, | 58 | + image.content_type.as_str(), |
| 59 | image.size, | 59 | image.size, |
| 60 | ) | 60 | ) |
| 61 | .fetch_one(&mut *conn) | 61 | .fetch_one(&mut *conn) |
| @@ -74,8 +74,8 @@ pub(crate) async fn replaced_file( | |||
| 74 | let row = sqlx::query!( | 74 | let row = sqlx::query!( |
| 75 | r#"SELECT file FROM question_image | 75 | r#"SELECT file FROM question_image |
| 76 | WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#, | 76 | WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#, |
| 77 | - question as &ExamQuestionId, | 77 | + question.uuid(), |
| 78 | - slot.map(ChoiceId::clone), | 78 | + slot.map(ChoiceId::as_str), |
| 79 | ) | 79 | ) |
| 80 | .fetch_optional(conn) | 80 | .fetch_optional(conn) |
| 81 | .await?; | 81 | .await?; |
| @@ -90,12 +90,12 @@ pub async fn read_slot( | |||
| 90 | Ok(sqlx::query_as!( | 90 | Ok(sqlx::query_as!( |
| 91 | QuestionImage, | 91 | QuestionImage, |
| 92 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", | 92 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 93 | - slot AS "slot: Option<ChoiceId>", file, | 93 | + slot AS "slot: ChoiceId", file, |
| 94 | content_type AS "content_type: FileContentType", size | 94 | content_type AS "content_type: FileContentType", size |
| 95 | FROM question_image | 95 | FROM question_image |
| 96 | WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#, | 96 | WHERE question = $1 AND slot IS NOT DISTINCT FROM $2"#, |
| 97 | - question as &ExamQuestionId, | 97 | + question.uuid(), |
| 98 | - slot.map(ChoiceId::clone), | 98 | + slot.map(ChoiceId::as_str), |
| 99 | ) | 99 | ) |
| 100 | .fetch_optional(db) | 100 | .fetch_optional(db) |
| 101 | .await?) | 101 | .await?) |
| @@ -106,10 +106,10 @@ pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<QuestionI | |||
| 106 | Ok(sqlx::query_as!( | 106 | Ok(sqlx::query_as!( |
| 107 | QuestionImage, | 107 | QuestionImage, |
| 108 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", | 108 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 109 | - slot AS "slot: Option<ChoiceId>", file, | 109 | + slot AS "slot: ChoiceId", file, |
| 110 | content_type AS "content_type: FileContentType", size | 110 | content_type AS "content_type: FileContentType", size |
| 111 | FROM question_image WHERE exam = $1"#, | 111 | FROM question_image WHERE exam = $1"#, |
| 112 | - exam as &ExamId, | 112 | + exam.uuid(), |
| 113 | ) | 113 | ) |
| 114 | .fetch_all(db) | 114 | .fetch_all(db) |
| 115 | .await?) | 115 | .await?) |
| @@ -122,10 +122,10 @@ pub async fn list_for_question( | |||
| 122 | Ok(sqlx::query_as!( | 122 | Ok(sqlx::query_as!( |
| 123 | QuestionImage, | 123 | QuestionImage, |
| 124 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", | 124 | r#"SELECT exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 125 | - slot AS "slot: Option<ChoiceId>", file, | 125 | + slot AS "slot: ChoiceId", file, |
| 126 | content_type AS "content_type: FileContentType", size | 126 | content_type AS "content_type: FileContentType", size |
| 127 | FROM question_image WHERE question = $1"#, | 127 | FROM question_image WHERE question = $1"#, |
| 128 | - question as &ExamQuestionId, | 128 | + question.uuid(), |
| 129 | ) | 129 | ) |
| 130 | .fetch_all(db) | 130 | .fetch_all(db) |
| 131 | .await?) | 131 | .await?) |
| @@ -145,16 +145,19 @@ pub async fn delete_choices_not_in( | |||
| 145 | question: &ExamQuestionId, | 145 | question: &ExamQuestionId, |
| 146 | keep: &[ChoiceId], | 146 | keep: &[ChoiceId], |
| 147 | ) -> Result<Vec<QuestionImage>, AppError> { | 147 | ) -> Result<Vec<QuestionImage>, AppError> { |
| 148 | - let keep = keep.iter().map(ChoiceId::as_str).collect::<Vec<_>>(); | 148 | + let keep = keep |
| 149 | + .iter() | ||
| 150 | + .map(|id| id.as_str().to_string()) | ||
| 151 | + .collect::<Vec<_>>(); | ||
| 149 | Ok(sqlx::query_as!( | 152 | Ok(sqlx::query_as!( |
| 150 | QuestionImage, | 153 | QuestionImage, |
| 151 | r#"DELETE FROM question_image | 154 | r#"DELETE FROM question_image |
| 152 | WHERE question = $1 AND slot IS NOT NULL AND NOT (slot = ANY($2)) | 155 | WHERE question = $1 AND slot IS NOT NULL AND NOT (slot = ANY($2)) |
| 153 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", | 156 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 154 | - slot AS "slot: Option<ChoiceId>", file, | 157 | + slot AS "slot: ChoiceId", file, |
| 155 | content_type AS "content_type: FileContentType", size"#, | 158 | content_type AS "content_type: FileContentType", size"#, |
| 156 | - question as &ExamQuestionId, | 159 | + question.uuid(), |
| 157 | - keep, | 160 | + &keep, |
| 158 | ) | 161 | ) |
| 159 | .fetch_all(db) | 162 | .fetch_all(db) |
| 160 | .await?) | 163 | .await?) |
| @@ -169,7 +172,7 @@ pub async fn file_keys_for_course( | |||
| 169 | let rows = sqlx::query!( | 172 | let rows = sqlx::query!( |
| 170 | r#"SELECT qi.file FROM question_image qi | 173 | r#"SELECT qi.file FROM question_image qi |
| 171 | JOIN exam e ON e.id = qi.exam WHERE e.course = $1"#, | 174 | JOIN exam e ON e.id = qi.exam WHERE e.course = $1"#, |
| 172 | - course as &CourseId, | 175 | + course.uuid(), |
| 173 | ) | 176 | ) |
| 174 | .fetch_all(db) | 177 | .fetch_all(db) |
| 175 | .await?; | 178 | .await?; |
| @@ -186,10 +189,10 @@ pub async fn delete(db: &Database, image: QuestionImage) -> Result<QuestionImage | |||
| 186 | r#"DELETE FROM question_image | 189 | r#"DELETE FROM question_image |
| 187 | WHERE question = $1 AND slot IS NOT DISTINCT FROM $2 | 190 | WHERE question = $1 AND slot IS NOT DISTINCT FROM $2 |
| 188 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", | 191 | RETURNING exam AS "exam: ExamId", question AS "question: ExamQuestionId", |
| 189 | - slot AS "slot: Option<ChoiceId>", file, | 192 | + slot AS "slot: ChoiceId", file, |
| 190 | content_type AS "content_type: FileContentType", size"#, | 193 | content_type AS "content_type: FileContentType", size"#, |
| 191 | - image.question as &ExamQuestionId, | 194 | + image.question.uuid(), |
| 192 | - image.slot, | 195 | + image.slot.as_ref().map(ChoiceId::as_str), |
| 193 | ) | 196 | ) |
| 194 | .fetch_optional(&mut *conn) | 197 | .fetch_optional(&mut *conn) |
| 195 | .await?; | 198 | .await?; |
src/db/rag_output.rsmodified+35 -20
| @@ -40,14 +40,20 @@ pub async fn create( | |||
| 40 | RagOutput, | 40 | RagOutput, |
| 41 | r#"INSERT INTO rag_output (id, course_note, course, sources, payload, generated_at) | 41 | r#"INSERT INTO rag_output (id, course_note, course, sources, payload, generated_at) |
| 42 | VALUES ($1, $2, $3, $4, $5, $6) | 42 | VALUES ($1, $2, $3, $4, $5, $6) |
| 43 | - RETURNING id, course_note, course, sources, | 43 | + RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", |
| 44 | - payload AS "payload: Json<Value>", generated_at"#, | 44 | + course AS "course: CourseId", |
| 45 | - row.id, | 45 | + sources AS "sources: Vec<CourseNoteFileId>", |
| 46 | - row.course_note, | 46 | + payload AS "payload: Json<Value>", |
| 47 | - row.course, | 47 | + generated_at AS "generated_at: Timestamp""#, |
| 48 | - &row.sources, | 48 | + row.id.uuid(), |
| 49 | - &row.payload, | 49 | + row.course_note.uuid(), |
| 50 | - row.generated_at | 50 | + row.course.uuid(), |
| 51 | + &row.sources | ||
| 52 | + .iter() | ||
| 53 | + .map(CourseNoteFileId::uuid) | ||
| 54 | + .collect::<Vec<uuid::Uuid>>(), | ||
| 55 | + row.payload.0, | ||
| 56 | + row.generated_at.as_millis() | ||
| 51 | ) | 57 | ) |
| 52 | .fetch_one(db) | 58 | .fetch_one(db) |
| 53 | .await?; | 59 | .await?; |
| @@ -57,10 +63,13 @@ pub async fn create( | |||
| 57 | pub async fn read(db: &Database, id: &RagOutputId) -> Result<Option<RagOutput>, AppError> { | 63 | pub async fn read(db: &Database, id: &RagOutputId) -> Result<Option<RagOutput>, AppError> { |
| 58 | let row = sqlx::query_as!( | 64 | let row = sqlx::query_as!( |
| 59 | RagOutput, | 65 | RagOutput, |
| 60 | - r#"SELECT id, course_note, course, sources, | 66 | + r#"SELECT id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", |
| 61 | - payload AS "payload: Json<Value>", generated_at | 67 | + course AS "course: CourseId", |
| 68 | + sources AS "sources: Vec<CourseNoteFileId>", | ||
| 69 | + payload AS "payload: Json<Value>", | ||
| 70 | + generated_at AS "generated_at: Timestamp" | ||
| 62 | FROM rag_output WHERE id = $1"#, | 71 | FROM rag_output WHERE id = $1"#, |
| 63 | - id | 72 | + id.uuid() |
| 64 | ) | 73 | ) |
| 65 | .fetch_optional(db) | 74 | .fetch_optional(db) |
| 66 | .await?; | 75 | .await?; |
| @@ -84,9 +93,12 @@ pub async fn delete(db: &Database, id: &RagOutputId) -> Result<RagOutput, AppErr | |||
| 84 | let deleted = sqlx::query_as!( | 93 | let deleted = sqlx::query_as!( |
| 85 | RagOutput, | 94 | RagOutput, |
| 86 | r#"DELETE FROM rag_output WHERE id = $1 | 95 | r#"DELETE FROM rag_output WHERE id = $1 |
| 87 | - RETURNING id, course_note, course, sources, | 96 | + RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", |
| 88 | - payload AS "payload: Json<Value>", generated_at"#, | 97 | + course AS "course: CourseId", |
| 89 | - id | 98 | + sources AS "sources: Vec<CourseNoteFileId>", |
| 99 | + payload AS "payload: Json<Value>", | ||
| 100 | + generated_at AS "generated_at: Timestamp""#, | ||
| 101 | + id.uuid() | ||
| 90 | ) | 102 | ) |
| 91 | .fetch_optional(db) | 103 | .fetch_optional(db) |
| 92 | .await?; | 104 | .await?; |
| @@ -96,7 +108,7 @@ pub async fn delete(db: &Database, id: &RagOutputId) -> Result<RagOutput, AppErr | |||
| 96 | /// Cascade: every output of `note`. Deleting none is a success — a note | 108 | /// Cascade: every output of `note`. Deleting none is a success — a note |
| 97 | /// no service ever indexed has nothing to drop. | 109 | /// no service ever indexed has nothing to drop. |
| 98 | pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> { | 110 | pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> { |
| 99 | - sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note) | 111 | + sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.uuid()) |
| 100 | .execute(db) | 112 | .execute(db) |
| 101 | .await?; | 113 | .await?; |
| 102 | Ok(()) | 114 | Ok(()) |
| @@ -119,8 +131,8 @@ pub async fn replace_for_note( | |||
| 119 | let created = create(db, note, course, sources, payload).await?; | 131 | let created = create(db, note, course, sources, payload).await?; |
| 120 | sqlx::query!( | 132 | sqlx::query!( |
| 121 | "DELETE FROM rag_output WHERE course_note = $1 AND id < $2", | 133 | "DELETE FROM rag_output WHERE course_note = $1 AND id < $2", |
| 122 | - note, | 134 | + note.uuid(), |
| 123 | - created.id | 135 | + created.id.uuid() |
| 124 | ) | 136 | ) |
| 125 | .execute(db) | 137 | .execute(db) |
| 126 | .await?; | 138 | .await?; |
| @@ -132,9 +144,12 @@ pub async fn replace_for_note( | |||
| 132 | /// source. The GIN index on `sources` turns the containment test into a | 144 | /// source. The GIN index on `sources` turns the containment test into a |
| 133 | /// lookup. | 145 | /// lookup. |
| 134 | pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> { | 146 | pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> { |
| 135 | - sqlx::query!("DELETE FROM rag_output WHERE $1 = ANY(sources)", file) | 147 | + sqlx::query!( |
| 136 | - .execute(db) | 148 | + "DELETE FROM rag_output WHERE $1 = ANY(sources)", |
| 137 | - .await?; | 149 | + file.uuid() |
| 150 | + ) | ||
| 151 | + .execute(db) | ||
| 152 | + .await?; | ||
| 138 | Ok(()) | 153 | Ok(()) |
| 139 | } | 154 | } |
| 140 | 155 | ||
src/db/registration.rsmodified+4 -1
| @@ -103,7 +103,10 @@ pub async fn remove( | |||
| 103 | user: &UserId, | 103 | user: &UserId, |
| 104 | ) -> Result<Option<Registration>, AppError> { | 104 | ) -> Result<Option<Registration>, AppError> { |
| 105 | // The seat comes back in the same transaction as the row that held it. | 105 | // The seat comes back in the same transaction as the row that held it. |
| 106 | - tx_with_retry(db, false, async |tx| { | 106 | + // Owned captures (`Send` rule of `tx_with_retry` closures). |
| 107 | + let event = event.clone(); | ||
| 108 | + let user = *user; | ||
| 109 | + tx_with_retry(db, false, async move |tx| { | ||
| 107 | let gone = query_as!( | 110 | let gone = query_as!( |
| 108 | Registration, | 111 | Registration, |
| 109 | "DELETE FROM registration WHERE event = $1 AND app_user = $2 | 112 | "DELETE FROM registration WHERE event = $1 AND app_user = $2 |
src/db/session.rsmodified+5 -5
| @@ -21,8 +21,8 @@ pub async fn create(db: &Database, user: &UserId) -> Result<Session, AppError> { | |||
| 21 | app_user AS "user: UserId", | 21 | app_user AS "user: UserId", |
| 22 | token AS "token: SessionToken", | 22 | token AS "token: SessionToken", |
| 23 | expires_at AS "expires_at: Timestamp""#, | 23 | expires_at AS "expires_at: Timestamp""#, |
| 24 | - id.0, | 24 | + id.uuid(), |
| 25 | - user.0, | 25 | + user.uuid(), |
| 26 | token.as_str(), | 26 | token.as_str(), |
| 27 | expires_at.as_millis(), | 27 | expires_at.as_millis(), |
| 28 | ) | 28 | ) |
| @@ -57,7 +57,7 @@ pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> | |||
| 57 | /// the new credential means nothing while a cookie minted under the old one | 57 | /// the new credential means nothing while a cookie minted under the old one |
| 58 | /// still authenticates. | 58 | /// still authenticates. |
| 59 | pub async fn delete_by_user(db: &Database, user: &UserId) -> Result<(), AppError> { | 59 | pub async fn delete_by_user(db: &Database, user: &UserId) -> Result<(), AppError> { |
| 60 | - sqlx::query!("DELETE FROM user_session WHERE app_user = $1", user.0) | 60 | + sqlx::query!("DELETE FROM user_session WHERE app_user = $1", user.uuid()) |
| 61 | .execute(db) | 61 | .execute(db) |
| 62 | .await?; | 62 | .await?; |
| 63 | Ok(()) | 63 | Ok(()) |
| @@ -69,7 +69,7 @@ pub async fn delete_by_user(db: &Database, user: &UserId) -> Result<(), AppError | |||
| 69 | /// forever. | 69 | /// forever. |
| 70 | pub async fn purge_expired(db: &Database) -> Result<u64, AppError> { | 70 | pub async fn purge_expired(db: &Database) -> Result<u64, AppError> { |
| 71 | let now = Timestamp::now().as_millis(); | 71 | let now = Timestamp::now().as_millis(); |
| 72 | - let (deleted,) = sqlx::query!( | 72 | + let row = sqlx::query!( |
| 73 | r#"WITH gone AS ( | 73 | r#"WITH gone AS ( |
| 74 | DELETE FROM user_session WHERE expires_at < $1 RETURNING 1 | 74 | DELETE FROM user_session WHERE expires_at < $1 RETURNING 1 |
| 75 | ) | 75 | ) |
| @@ -78,7 +78,7 @@ pub async fn purge_expired(db: &Database) -> Result<u64, AppError> { | |||
| 78 | ) | 78 | ) |
| 79 | .fetch_one(db) | 79 | .fetch_one(db) |
| 80 | .await?; | 80 | .await?; |
| 81 | - Ok(u64::try_from(deleted).unwrap_or(u64::MAX)) | 81 | + Ok(u64::try_from(row.deleted).unwrap_or(u64::MAX)) |
| 82 | } | 82 | } |
| 83 | 83 | ||
| 84 | #[cfg(test)] | 84 | #[cfg(test)] |
src/db/session_attendance.rsmodified+30 -23
| @@ -7,6 +7,7 @@ | |||
| 7 | use crate::database::{Database, tx_with_retry}; | 7 | use crate::database::{Database, tx_with_retry}; |
| 8 | use crate::db::page::PagedList; | 8 | use crate::db::page::PagedList; |
| 9 | use crate::domain::attendance::AttendanceStatus; | 9 | use crate::domain::attendance::AttendanceStatus; |
| 10 | +use crate::domain::course::CourseId; | ||
| 10 | use crate::domain::course_session::{CourseSession, CourseSessionId}; | 11 | use crate::domain::course_session::{CourseSession, CourseSessionId}; |
| 11 | use crate::domain::session_attendance::SessionAttendance; | 12 | use crate::domain::session_attendance::SessionAttendance; |
| 12 | use crate::domain::timestamp::Timestamp; | 13 | use crate::domain::timestamp::Timestamp; |
| @@ -93,7 +94,7 @@ pub async fn mark( | |||
| 93 | let sess = sqlx::query!( | 94 | let sess = sqlx::query!( |
| 94 | r#"SELECT teacher, starts_at, held_counted_at | 95 | r#"SELECT teacher, starts_at, held_counted_at |
| 95 | FROM course_session WHERE id = $1 FOR NO KEY UPDATE"#, | 96 | FROM course_session WHERE id = $1 FOR NO KEY UPDATE"#, |
| 96 | - session.id, | 97 | + session.id.uuid(), |
| 97 | ) | 98 | ) |
| 98 | .fetch_optional(&mut *tx) | 99 | .fetch_optional(&mut *tx) |
| 99 | .await?; | 100 | .await?; |
| @@ -105,8 +106,8 @@ pub async fn mark( | |||
| 105 | let was = sqlx::query!( | 106 | let was = sqlx::query!( |
| 106 | r#"SELECT status FROM session_attendance | 107 | r#"SELECT status FROM session_attendance |
| 107 | WHERE session = $1 AND app_user = $2"#, | 108 | WHERE session = $1 AND app_user = $2"#, |
| 108 | - session.id, | 109 | + session.id.uuid(), |
| 109 | - user, | 110 | + user.uuid(), |
| 110 | ) | 111 | ) |
| 111 | .fetch_optional(&mut *tx) | 112 | .fetch_optional(&mut *tx) |
| 112 | .await? | 113 | .await? |
| @@ -115,8 +116,8 @@ pub async fn mark( | |||
| 115 | // non-student — no badge to move; the service gate has already | 116 | // non-student — no badge to move; the service gate has already |
| 116 | // refused a vanished target before this write ran). | 117 | // refused a vanished target before this write ran). |
| 117 | let is_student = sqlx::query!( | 118 | let is_student = sqlx::query!( |
| 118 | - r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#, | 119 | + r#"SELECT role = 'student' AS "is_student!: bool" FROM app_user WHERE id = $1"#, |
| 119 | - user, | 120 | + user.uuid(), |
| 120 | ) | 121 | ) |
| 121 | .fetch_optional(&mut *tx) | 122 | .fetch_optional(&mut *tx) |
| 122 | .await? | 123 | .await? |
| @@ -128,12 +129,14 @@ pub async fn mark( | |||
| 128 | VALUES ($1, $2, $3, $4, $5) | 129 | VALUES ($1, $2, $3, $4, $5) |
| 129 | ON CONFLICT (session, app_user) DO UPDATE | 130 | ON CONFLICT (session, app_user) DO UPDATE |
| 130 | SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by | 131 | SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by |
| 131 | - RETURNING session, app_user AS "user", course, status, marked_by"#, | 132 | + RETURNING session AS "session: CourseSessionId", app_user AS "user: UserId", |
| 132 | - session.id, | 133 | + course AS "course: CourseId", status AS "status: AttendanceStatus", |
| 133 | - user, | 134 | + marked_by AS "marked_by: UserId""#, |
| 134 | - session.course, | 135 | + session.id.uuid(), |
| 135 | - status, | 136 | + user.uuid(), |
| 136 | - marked_by, | 137 | + session.course.uuid(), |
| 138 | + status.as_str(), | ||
| 139 | + marked_by.uuid(), | ||
| 137 | ) | 140 | ) |
| 138 | .fetch_one(&mut *tx) | 141 | .fetch_one(&mut *tx) |
| 139 | .await?; | 142 | .await?; |
| @@ -146,7 +149,7 @@ pub async fn mark( | |||
| 146 | r#"UPDATE app_user | 149 | r#"UPDATE app_user |
| 147 | SET lessons_attended_total = GREATEST(lessons_attended_total + $2, 0) | 150 | SET lessons_attended_total = GREATEST(lessons_attended_total + $2, 0) |
| 148 | WHERE id = $1"#, | 151 | WHERE id = $1"#, |
| 149 | - user, | 152 | + user.uuid(), |
| 150 | delta, | 153 | delta, |
| 151 | ) | 154 | ) |
| 152 | .execute(&mut *tx) | 155 | .execute(&mut *tx) |
| @@ -156,7 +159,7 @@ pub async fn mark( | |||
| 156 | if sess.held_counted_at.is_none() && sess.starts_at <= now.as_millis() { | 159 | if sess.held_counted_at.is_none() && sess.starts_at <= now.as_millis() { |
| 157 | sqlx::query!( | 160 | sqlx::query!( |
| 158 | r#"UPDATE course_session SET held_counted_at = $2 WHERE id = $1"#, | 161 | r#"UPDATE course_session SET held_counted_at = $2 WHERE id = $1"#, |
| 159 | - session.id, | 162 | + session.id.uuid(), |
| 160 | now.as_millis(), | 163 | now.as_millis(), |
| 161 | ) | 164 | ) |
| 162 | .execute(&mut *tx) | 165 | .execute(&mut *tx) |
| @@ -202,10 +205,12 @@ pub async fn list_for_user( | |||
| 202 | ) -> Result<Vec<SessionAttendance>, AppError> { | 205 | ) -> Result<Vec<SessionAttendance>, AppError> { |
| 203 | let rows = sqlx::query_as!( | 206 | let rows = sqlx::query_as!( |
| 204 | SessionAttendance, | 207 | SessionAttendance, |
| 205 | - r#"SELECT session, app_user AS "user", course, status, marked_by | 208 | + r#"SELECT session AS "session: CourseSessionId", app_user AS "user: UserId", |
| 209 | + course AS "course: CourseId", status AS "status: AttendanceStatus", | ||
| 210 | + marked_by AS "marked_by: UserId" | ||
| 206 | FROM session_attendance WHERE app_user = $1 | 211 | FROM session_attendance WHERE app_user = $1 |
| 207 | ORDER BY session DESC, app_user DESC"#, | 212 | ORDER BY session DESC, app_user DESC"#, |
| 208 | - user, | 213 | + user.uuid(), |
| 209 | ) | 214 | ) |
| 210 | .fetch_all(db) | 215 | .fetch_all(db) |
| 211 | .await?; | 216 | .await?; |
| @@ -235,12 +240,14 @@ pub async fn remove( | |||
| 235 | // transaction, and `None` here is simply "nothing to remove". | 240 | // transaction, and `None` here is simply "nothing to remove". |
| 236 | let Some(gone) = sqlx::query_as!( | 241 | let Some(gone) = sqlx::query_as!( |
| 237 | SessionAttendance, | 242 | SessionAttendance, |
| 238 | - r#"SELECT session, app_user AS "user", course, status, marked_by | 243 | + r#"SELECT session AS "session: CourseSessionId", app_user AS "user: UserId", |
| 244 | + course AS "course: CourseId", status AS "status: AttendanceStatus", | ||
| 245 | + marked_by AS "marked_by: UserId" | ||
| 239 | FROM session_attendance | 246 | FROM session_attendance |
| 240 | WHERE session = $1 AND app_user = $2 | 247 | WHERE session = $1 AND app_user = $2 |
| 241 | FOR UPDATE"#, | 248 | FOR UPDATE"#, |
| 242 | - session, | 249 | + session.uuid(), |
| 243 | - user, | 250 | + user.uuid(), |
| 244 | ) | 251 | ) |
| 245 | .fetch_optional(&mut *tx) | 252 | .fetch_optional(&mut *tx) |
| 246 | .await? | 253 | .await? |
| @@ -250,8 +257,8 @@ pub async fn remove( | |||
| 250 | if crate::domain::session_attendance::counts_as_attended(&gone.status) { | 257 | if crate::domain::session_attendance::counts_as_attended(&gone.status) { |
| 251 | // Student-only, live role: the same rule the mark pays. | 258 | // Student-only, live role: the same rule the mark pays. |
| 252 | let student = sqlx::query!( | 259 | let student = sqlx::query!( |
| 253 | - r#"SELECT role = 'student' AS "is_student" FROM app_user WHERE id = $1"#, | 260 | + r#"SELECT role = 'student' AS "is_student!: bool" FROM app_user WHERE id = $1"#, |
| 254 | - user, | 261 | + user.uuid(), |
| 255 | ) | 262 | ) |
| 256 | .fetch_optional(&mut *tx) | 263 | .fetch_optional(&mut *tx) |
| 257 | .await? | 264 | .await? |
| @@ -262,7 +269,7 @@ pub async fn remove( | |||
| 262 | r#"UPDATE app_user | 269 | r#"UPDATE app_user |
| 263 | SET lessons_attended_total = GREATEST(lessons_attended_total - 1, 0) | 270 | SET lessons_attended_total = GREATEST(lessons_attended_total - 1, 0) |
| 264 | WHERE id = $1"#, | 271 | WHERE id = $1"#, |
| 265 | - user, | 272 | + user.uuid(), |
| 266 | ) | 273 | ) |
| 267 | .execute(&mut *tx) | 274 | .execute(&mut *tx) |
| 268 | .await?; | 275 | .await?; |
| @@ -270,8 +277,8 @@ pub async fn remove( | |||
| 270 | } | 277 | } |
| 271 | sqlx::query!( | 278 | sqlx::query!( |
| 272 | r#"DELETE FROM session_attendance WHERE session = $1 AND app_user = $2"#, | 279 | r#"DELETE FROM session_attendance WHERE session = $1 AND app_user = $2"#, |
| 273 | - session, | 280 | + session.uuid(), |
| 274 | - user, | 281 | + user.uuid(), |
| 275 | ) | 282 | ) |
| 276 | .execute(&mut *tx) | 283 | .execute(&mut *tx) |
| 277 | .await?; | 284 | .await?; |
src/db/settings.rsmodified+45 -15
| @@ -34,6 +34,16 @@ pub async fn load(db: &Database) -> Result<Settings, AppError> { | |||
| 34 | /// wherever the new policy was merged from a loaded snapshot. | 34 | /// wherever the new policy was merged from a loaded snapshot. |
| 35 | pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppError> { | 35 | pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppError> { |
| 36 | // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged | 36 | // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged |
| 37 | + let exam_kinds = serde_json::to_value(&settings.exam_kinds.0) | ||
| 38 | + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; | ||
| 39 | + let grade_bands = serde_json::to_value(&settings.grade_bands.0) | ||
| 40 | + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; | ||
| 41 | + let meal_slots = settings | ||
| 42 | + .meal_slots | ||
| 43 | + .as_ref() | ||
| 44 | + .map(|slots| serde_json::to_value(&slots.0)) | ||
| 45 | + .transpose() | ||
| 46 | + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; | ||
| 37 | let saved = sqlx::query_as!( | 47 | let saved = sqlx::query_as!( |
| 38 | Settings, | 48 | Settings, |
| 39 | r#"INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands, | 49 | r#"INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands, |
| @@ -63,15 +73,15 @@ pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppErro | |||
| 63 | meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>", | 73 | meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>", |
| 64 | dietary_tags, | 74 | dietary_tags, |
| 65 | meal_cancel_cutoff_minutes"#, | 75 | meal_cancel_cutoff_minutes"#, |
| 66 | - settings.exam_kinds, | 76 | + exam_kinds, |
| 67 | - settings.attendance_statuses, | 77 | + settings.attendance_statuses.as_slice(), |
| 68 | - settings.grade_bands, | 78 | + grade_bands, |
| 69 | settings.max_file_bytes, | 79 | settings.max_file_bytes, |
| 70 | settings.chatbot_history_turns, | 80 | settings.chatbot_history_turns, |
| 71 | settings.max_chatbot_message_len, | 81 | settings.max_chatbot_message_len, |
| 72 | settings.max_chatbot_threads, | 82 | settings.max_chatbot_threads, |
| 73 | - settings.meal_slots, | 83 | + meal_slots, |
| 74 | - settings.dietary_tags, | 84 | + settings.dietary_tags.as_deref(), |
| 75 | settings.meal_cancel_cutoff_minutes, | 85 | settings.meal_cancel_cutoff_minutes, |
| 76 | ) | 86 | ) |
| 77 | .fetch_one(db) | 87 | .fetch_one(db) |
| @@ -114,6 +124,26 @@ pub async fn save_if_unchanged<'e, E>( | |||
| 114 | where | 124 | where |
| 115 | E: sqlx::PgExecutor<'e>, | 125 | E: sqlx::PgExecutor<'e>, |
| 116 | { | 126 | { |
| 127 | + let exam_kinds = serde_json::to_value(&settings.exam_kinds.0) | ||
| 128 | + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; | ||
| 129 | + let grade_bands = serde_json::to_value(&settings.grade_bands.0) | ||
| 130 | + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; | ||
| 131 | + let meal_slots = settings | ||
| 132 | + .meal_slots | ||
| 133 | + .as_ref() | ||
| 134 | + .map(|slots| serde_json::to_value(&slots.0)) | ||
| 135 | + .transpose() | ||
| 136 | + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; | ||
| 137 | + let expected_exam_kinds = serde_json::to_value(&expected.exam_kinds.0) | ||
| 138 | + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; | ||
| 139 | + let expected_grade_bands = serde_json::to_value(&expected.grade_bands.0) | ||
| 140 | + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; | ||
| 141 | + let expected_meal_slots = expected | ||
| 142 | + .meal_slots | ||
| 143 | + .as_ref() | ||
| 144 | + .map(|slots| serde_json::to_value(&slots.0)) | ||
| 145 | + .transpose() | ||
| 146 | + .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; | ||
| 117 | let saved = sqlx::query_as!( | 147 | let saved = sqlx::query_as!( |
| 118 | Settings, | 148 | Settings, |
| 119 | r#"INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands, | 149 | r#"INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands, |
| @@ -153,25 +183,25 @@ where | |||
| 153 | meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>", | 183 | meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>", |
| 154 | dietary_tags, | 184 | dietary_tags, |
| 155 | meal_cancel_cutoff_minutes"#, | 185 | meal_cancel_cutoff_minutes"#, |
| 156 | - settings.exam_kinds, | 186 | + exam_kinds, |
| 157 | - settings.attendance_statuses, | 187 | + settings.attendance_statuses.as_slice(), |
| 158 | - settings.grade_bands, | 188 | + grade_bands, |
| 159 | settings.max_file_bytes, | 189 | settings.max_file_bytes, |
| 160 | settings.chatbot_history_turns, | 190 | settings.chatbot_history_turns, |
| 161 | settings.max_chatbot_message_len, | 191 | settings.max_chatbot_message_len, |
| 162 | settings.max_chatbot_threads, | 192 | settings.max_chatbot_threads, |
| 163 | - settings.meal_slots, | 193 | + meal_slots, |
| 164 | - settings.dietary_tags, | 194 | + settings.dietary_tags.as_deref(), |
| 165 | settings.meal_cancel_cutoff_minutes, | 195 | settings.meal_cancel_cutoff_minutes, |
| 166 | - expected.exam_kinds, | 196 | + expected_exam_kinds, |
| 167 | - expected.attendance_statuses, | 197 | + expected.attendance_statuses.as_slice(), |
| 168 | - expected.grade_bands, | 198 | + expected_grade_bands, |
| 169 | expected.max_file_bytes, | 199 | expected.max_file_bytes, |
| 170 | expected.chatbot_history_turns, | 200 | expected.chatbot_history_turns, |
| 171 | expected.max_chatbot_message_len, | 201 | expected.max_chatbot_message_len, |
| 172 | expected.max_chatbot_threads, | 202 | expected.max_chatbot_threads, |
| 173 | - expected.meal_slots, | 203 | + expected_meal_slots, |
| 174 | - expected.dietary_tags, | 204 | + expected.dietary_tags.as_deref(), |
| 175 | expected.meal_cancel_cutoff_minutes, | 205 | expected.meal_cancel_cutoff_minutes, |
| 176 | ) | 206 | ) |
| 177 | .fetch_optional(db) | 207 | .fetch_optional(db) |
src/db/solution.rsmodified+52 -22
| @@ -11,6 +11,7 @@ use crate::db::page::PagedList; | |||
| 11 | use crate::domain::note_file::FileContentType; | 11 | use crate::domain::note_file::FileContentType; |
| 12 | use crate::domain::pool_question::PoolQuestionId; | 12 | use crate::domain::pool_question::PoolQuestionId; |
| 13 | use crate::domain::solution::{Solution, SolutionBody, SolutionId}; | 13 | use crate::domain::solution::{Solution, SolutionBody, SolutionId}; |
| 14 | +use crate::domain::timestamp::Timestamp; | ||
| 14 | use crate::error::AppError; | 15 | use crate::error::AppError; |
| 15 | 16 | ||
| 16 | /// Offer the solution. `NotFound` = the question is gone, and nothing was | 17 | /// Offer the solution. `NotFound` = the question is gone, and nothing was |
| @@ -29,12 +30,16 @@ pub async fn insert(db: &Database, solution: Solution) -> Result<Solution, AppEr | |||
| 29 | Solution, | 30 | Solution, |
| 30 | r#"INSERT INTO solution (id, question, author, body, offered_at) | 31 | r#"INSERT INTO solution (id, question, author, body, offered_at) |
| 31 | VALUES ($1, $2, $3, $4, $5) | 32 | VALUES ($1, $2, $3, $4, $5) |
| 32 | - RETURNING *"#, | 33 | + RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 33 | - solution.id, | 34 | + author AS "author: UserId", body AS "body: SolutionBody", |
| 34 | - solution.question, | 35 | + offered_at AS "offered_at: Timestamp", image_file, |
| 35 | - solution.author, | 36 | + image_content_type AS "image_content_type: Option<FileContentType>", |
| 36 | - solution.body, | 37 | + image_size"#, |
| 37 | - solution.offered_at, | 38 | + solution.id.uuid(), |
| 39 | + solution.question.uuid(), | ||
| 40 | + solution.author.uuid(), | ||
| 41 | + solution.body.as_str(), | ||
| 42 | + solution.offered_at.as_millis(), | ||
| 38 | ) | 43 | ) |
| 39 | .fetch_one(db) | 44 | .fetch_one(db) |
| 40 | .await | 45 | .await |
| @@ -60,9 +65,14 @@ pub async fn read_for( | |||
| 60 | ) -> Result<Option<Solution>, AppError> { | 65 | ) -> Result<Option<Solution>, AppError> { |
| 61 | let row = sqlx::query_as!( | 66 | let row = sqlx::query_as!( |
| 62 | Solution, | 67 | Solution, |
| 63 | - "SELECT * FROM solution WHERE id = $1 AND question = $2", | 68 | + r#"SELECT id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 64 | - id, | 69 | + author AS "author: UserId", body AS "body: SolutionBody", |
| 65 | - question | 70 | + offered_at AS "offered_at: Timestamp", image_file, |
| 71 | + image_content_type AS "image_content_type: Option<FileContentType>", | ||
| 72 | + image_size | ||
| 73 | + FROM solution WHERE id = $1 AND question = $2"#, | ||
| 74 | + id.uuid(), | ||
| 75 | + question.uuid() | ||
| 66 | ) | 76 | ) |
| 67 | .fetch_optional(db) | 77 | .fetch_optional(db) |
| 68 | .await?; | 78 | .await?; |
| @@ -100,7 +110,7 @@ pub async fn counts_for( | |||
| 100 | if questions.is_empty() { | 110 | if questions.is_empty() { |
| 101 | return Ok(HashMap::new()); | 111 | return Ok(HashMap::new()); |
| 102 | } | 112 | } |
| 103 | - let ids: Vec<PoolQuestionId> = questions.iter().copied().collect(); | 113 | + let ids: Vec<uuid::Uuid> = questions.iter().map(|id| id.uuid()).collect(); |
| 104 | let rows = sqlx::query!( | 114 | let rows = sqlx::query!( |
| 105 | r#"SELECT question AS "question: PoolQuestionId", count(*) AS n | 115 | r#"SELECT question AS "question: PoolQuestionId", count(*) AS n |
| 106 | FROM solution | 116 | FROM solution |
| @@ -126,9 +136,14 @@ pub async fn set_body( | |||
| 126 | ) -> Result<Option<Solution>, AppError> { | 136 | ) -> Result<Option<Solution>, AppError> { |
| 127 | let row = sqlx::query_as!( | 137 | let row = sqlx::query_as!( |
| 128 | Solution, | 138 | Solution, |
| 129 | - "UPDATE solution SET body = $2 WHERE id = $1 RETURNING *", | 139 | + r#"UPDATE solution SET body = $2 WHERE id = $1 |
| 130 | - id, | 140 | + RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 131 | - body | 141 | + author AS "author: UserId", body AS "body: SolutionBody", |
| 142 | + offered_at AS "offered_at: Timestamp", image_file, | ||
| 143 | + image_content_type AS "image_content_type: Option<FileContentType>", | ||
| 144 | + image_size"#, | ||
| 145 | + id.uuid(), | ||
| 146 | + body.as_str() | ||
| 132 | ) | 147 | ) |
| 133 | .fetch_optional(db) | 148 | .fetch_optional(db) |
| 134 | .await?; | 149 | .await?; |
| @@ -153,8 +168,13 @@ pub async fn set_image( | |||
| 153 | tx_with_retry(db, false, async |tx| { | 168 | tx_with_retry(db, false, async |tx| { |
| 154 | let before = sqlx::query_as!( | 169 | let before = sqlx::query_as!( |
| 155 | Solution, | 170 | Solution, |
| 156 | - "SELECT * FROM solution WHERE id = $1 FOR UPDATE", | 171 | + r#"SELECT id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 157 | - *id | 172 | + author AS "author: UserId", body AS "body: SolutionBody", |
| 173 | + offered_at AS "offered_at: Timestamp", image_file, | ||
| 174 | + image_content_type AS "image_content_type: Option<FileContentType>", | ||
| 175 | + image_size | ||
| 176 | + FROM solution WHERE id = $1 FOR UPDATE"#, | ||
| 177 | + id.uuid() | ||
| 158 | ) | 178 | ) |
| 159 | .fetch_optional(tx) | 179 | .fetch_optional(tx) |
| 160 | .await?; | 180 | .await?; |
| @@ -165,9 +185,9 @@ pub async fn set_image( | |||
| 165 | r#"UPDATE solution | 185 | r#"UPDATE solution |
| 166 | SET image_file = $2, image_content_type = $3, image_size = $4 | 186 | SET image_file = $2, image_content_type = $3, image_size = $4 |
| 167 | WHERE id = $1"#, | 187 | WHERE id = $1"#, |
| 168 | - *id, | 188 | + id.uuid(), |
| 169 | file, | 189 | file, |
| 170 | - content_type, | 190 | + content_type.as_str(), |
| 171 | size, | 191 | size, |
| 172 | ) | 192 | ) |
| 173 | .execute(tx) | 193 | .execute(tx) |
| @@ -183,8 +203,13 @@ pub async fn clear_image(db: &Database, id: &SolutionId) -> Result<Option<Soluti | |||
| 183 | tx_with_retry(db, false, async |tx| { | 203 | tx_with_retry(db, false, async |tx| { |
| 184 | let before = sqlx::query_as!( | 204 | let before = sqlx::query_as!( |
| 185 | Solution, | 205 | Solution, |
| 186 | - "SELECT * FROM solution WHERE id = $1 FOR UPDATE", | 206 | + r#"SELECT id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 187 | - *id | 207 | + author AS "author: UserId", body AS "body: SolutionBody", |
| 208 | + offered_at AS "offered_at: Timestamp", image_file, | ||
| 209 | + image_content_type AS "image_content_type: Option<FileContentType>", | ||
| 210 | + image_size | ||
| 211 | + FROM solution WHERE id = $1 FOR UPDATE"#, | ||
| 212 | + id.uuid() | ||
| 188 | ) | 213 | ) |
| 189 | .fetch_optional(tx) | 214 | .fetch_optional(tx) |
| 190 | .await?; | 215 | .await?; |
| @@ -195,7 +220,7 @@ pub async fn clear_image(db: &Database, id: &SolutionId) -> Result<Option<Soluti | |||
| 195 | r#"UPDATE solution | 220 | r#"UPDATE solution |
| 196 | SET image_file = NULL, image_content_type = NULL, image_size = NULL | 221 | SET image_file = NULL, image_content_type = NULL, image_size = NULL |
| 197 | WHERE id = $1"#, | 222 | WHERE id = $1"#, |
| 198 | - *id, | 223 | + id.uuid(), |
| 199 | ) | 224 | ) |
| 200 | .execute(tx) | 225 | .execute(tx) |
| 201 | .await?; | 226 | .await?; |
| @@ -207,8 +232,13 @@ pub async fn clear_image(db: &Database, id: &SolutionId) -> Result<Option<Soluti | |||
| 207 | pub async fn delete(db: &Database, solution: Solution) -> Result<Solution, AppError> { | 232 | pub async fn delete(db: &Database, solution: Solution) -> Result<Solution, AppError> { |
| 208 | let deleted = sqlx::query_as!( | 233 | let deleted = sqlx::query_as!( |
| 209 | Solution, | 234 | Solution, |
| 210 | - "DELETE FROM solution WHERE id = $1 RETURNING *", | 235 | + r#"DELETE FROM solution WHERE id = $1 |
| 211 | - solution.id | 236 | + RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 237 | + author AS "author: UserId", body AS "body: SolutionBody", | ||
| 238 | + offered_at AS "offered_at: Timestamp", image_file, | ||
| 239 | + image_content_type AS "image_content_type: Option<FileContentType>", | ||
| 240 | + image_size"#, | ||
| 241 | + solution.id.uuid() | ||
| 212 | ) | 242 | ) |
| 213 | .fetch_optional(db) | 243 | .fetch_optional(db) |
| 214 | .await?; | 244 | .await?; |
src/db/subject.rsmodified+20 -14
| @@ -33,11 +33,14 @@ pub async fn create( | |||
| 33 | Subject, | 33 | Subject, |
| 34 | r#"INSERT INTO subject (id, course, name, description, exam_question_count, homework_count) | 34 | r#"INSERT INTO subject (id, course, name, description, exam_question_count, homework_count) |
| 35 | VALUES ($1, $2, $3, $4, 0, 0) | 35 | VALUES ($1, $2, $3, $4, 0, 0) |
| 36 | - RETURNING id, course, name, description"#, | 36 | + RETURNING id AS "id: SubjectId", |
| 37 | - subject.id, | 37 | + course AS "course: CourseId", |
| 38 | - subject.course, | 38 | + name AS "name: SubjectName", |
| 39 | - subject.name, | 39 | + description AS "description: SubjectDescription""#, |
| 40 | - subject.description, | 40 | + subject.id.uuid(), |
| 41 | + subject.course.uuid(), | ||
| 42 | + subject.name.as_str(), | ||
| 43 | + subject.description.as_str(), | ||
| 41 | ) | 44 | ) |
| 42 | .fetch_one(db) | 45 | .fetch_one(db) |
| 43 | .await; | 46 | .await; |
| @@ -51,8 +54,8 @@ pub async fn create( | |||
| 51 | pub async fn read(db: &Database, id: &SubjectId) -> Result<Option<Subject>, AppError> { | 54 | pub async fn read(db: &Database, id: &SubjectId) -> Result<Option<Subject>, AppError> { |
| 52 | let subject = sqlx::query_as!( | 55 | let subject = sqlx::query_as!( |
| 53 | Subject, | 56 | Subject, |
| 54 | - r#"SELECT id, course, name, description FROM subject WHERE id = $1"#, | 57 | + r#"SELECT id AS "id: SubjectId", course AS "course: CourseId", name AS "name: SubjectName", description AS "description: SubjectDescription" FROM subject WHERE id = $1"#, |
| 55 | - id, | 58 | + id.uuid(), |
| 56 | ) | 59 | ) |
| 57 | .fetch_optional(db) | 60 | .fetch_optional(db) |
| 58 | .await?; | 61 | .await?; |
| @@ -65,11 +68,11 @@ pub async fn list_by_ids(db: &Database, ids: &[&SubjectId]) -> Result<Vec<Subjec | |||
| 65 | if ids.is_empty() { | 68 | if ids.is_empty() { |
| 66 | return Ok(Vec::new()); | 69 | return Ok(Vec::new()); |
| 67 | } | 70 | } |
| 68 | - let keys: Vec<SubjectId> = ids.iter().map(|id| **id).collect(); | 71 | + let keys: Vec<uuid::Uuid> = ids.iter().map(|id| id.uuid()).collect(); |
| 69 | let rows = sqlx::query_as!( | 72 | let rows = sqlx::query_as!( |
| 70 | Subject, | 73 | Subject, |
| 71 | - r#"SELECT id, course, name, description FROM subject WHERE id = ANY($1)"#, | 74 | + r#"SELECT id AS "id: SubjectId", course AS "course: CourseId", name AS "name: SubjectName", description AS "description: SubjectDescription" FROM subject WHERE id = ANY($1)"#, |
| 72 | - keys, | 75 | + &keys, |
| 73 | ) | 76 | ) |
| 74 | .fetch_all(db) | 77 | .fetch_all(db) |
| 75 | .await?; | 78 | .await?; |
| @@ -139,7 +142,7 @@ pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError | |||
| 139 | let held = sqlx::query!( | 142 | let held = sqlx::query!( |
| 140 | r#"SELECT exam_question_count, homework_count | 143 | r#"SELECT exam_question_count, homework_count |
| 141 | FROM subject WHERE id = $1 FOR UPDATE"#, | 144 | FROM subject WHERE id = $1 FOR UPDATE"#, |
| 142 | - subject.id, | 145 | + subject.id.uuid(), |
| 143 | ) | 146 | ) |
| 144 | .fetch_optional(&mut *tx) | 147 | .fetch_optional(&mut *tx) |
| 145 | .await?; | 148 | .await?; |
| @@ -157,14 +160,17 @@ pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError | |||
| 157 | let deleted = sqlx::query_as!( | 160 | let deleted = sqlx::query_as!( |
| 158 | Subject, | 161 | Subject, |
| 159 | r#"DELETE FROM subject WHERE id = $1 | 162 | r#"DELETE FROM subject WHERE id = $1 |
| 160 | - RETURNING id, course, name, description"#, | 163 | + RETURNING id AS "id: SubjectId", |
| 161 | - subject.id, | 164 | + course AS "course: CourseId", |
| 165 | + name AS "name: SubjectName", | ||
| 166 | + description AS "description: SubjectDescription""#, | ||
| 167 | + subject.id.uuid(), | ||
| 162 | ) | 168 | ) |
| 163 | .fetch_one(&mut *tx) | 169 | .fetch_one(&mut *tx) |
| 164 | .await?; | 170 | .await?; |
| 165 | sqlx::query!( | 171 | sqlx::query!( |
| 166 | r#"UPDATE bank_question SET subject = NULL WHERE subject = $1"#, | 172 | r#"UPDATE bank_question SET subject = NULL WHERE subject = $1"#, |
| 167 | - subject.id, | 173 | + subject.id.uuid(), |
| 168 | ) | 174 | ) |
| 169 | .execute(&mut *tx) | 175 | .execute(&mut *tx) |
| 170 | .await?; | 176 | .await?; |
src/db/term.rsmodified+21 -13
| @@ -29,11 +29,13 @@ pub async fn create( | |||
| 29 | Term, | 29 | Term, |
| 30 | r#"INSERT INTO term (id, name, starts_at, ends_at, archived_at) | 30 | r#"INSERT INTO term (id, name, starts_at, ends_at, archived_at) |
| 31 | VALUES ($1, $2, $3, $4, NULL) | 31 | VALUES ($1, $2, $3, $4, NULL) |
| 32 | - RETURNING id, name, starts_at, ends_at, archived_at"#, | 32 | + RETURNING id AS "id: TermId", name AS "name: TermName", |
| 33 | - term.id, | 33 | + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", |
| 34 | - term.name, | 34 | + archived_at AS "archived_at: Timestamp""#, |
| 35 | - term.starts_at, | 35 | + term.id.uuid(), |
| 36 | - term.ends_at, | 36 | + term.name.as_str(), |
| 37 | + term.starts_at.as_millis(), | ||
| 38 | + term.ends_at.as_millis(), | ||
| 37 | ) | 39 | ) |
| 38 | .fetch_one(db) | 40 | .fetch_one(db) |
| 39 | .await?; | 41 | .await?; |
| @@ -43,8 +45,10 @@ pub async fn create( | |||
| 43 | pub async fn read(db: &Database, id: &TermId) -> Result<Option<Term>, AppError> { | 45 | pub async fn read(db: &Database, id: &TermId) -> Result<Option<Term>, AppError> { |
| 44 | let term = sqlx::query_as!( | 46 | let term = sqlx::query_as!( |
| 45 | Term, | 47 | Term, |
| 46 | - r#"SELECT id, name, starts_at, ends_at, archived_at FROM term WHERE id = $1"#, | 48 | + r#"SELECT id AS "id: TermId", name AS "name: TermName", |
| 47 | - id, | 49 | + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", |
| 50 | + archived_at AS "archived_at: Timestamp" FROM term WHERE id = $1"#, | ||
| 51 | + id.uuid(), | ||
| 48 | ) | 52 | ) |
| 49 | .fetch_optional(db) | 53 | .fetch_optional(db) |
| 50 | .await?; | 54 | .await?; |
| @@ -101,7 +105,7 @@ pub async fn delete(db: &Database, term: Term) -> Result<bool, AppError> { | |||
| 101 | let gone = sqlx::query!( | 105 | let gone = sqlx::query!( |
| 102 | r#"DELETE FROM term | 106 | r#"DELETE FROM term |
| 103 | WHERE id = $1 AND course_count = 0 AND class_count = 0"#, | 107 | WHERE id = $1 AND course_count = 0 AND class_count = 0"#, |
| 104 | - term.id, | 108 | + term.id.uuid(), |
| 105 | ) | 109 | ) |
| 106 | .execute(db) | 110 | .execute(db) |
| 107 | .await?; | 111 | .await?; |
| @@ -124,9 +128,11 @@ pub async fn archive(db: &Database, term: Term) -> Result<Term, AppError> { | |||
| 124 | Term, | 128 | Term, |
| 125 | r#"UPDATE term SET archived_at = $2 | 129 | r#"UPDATE term SET archived_at = $2 |
| 126 | WHERE id = $1 AND archived_at IS NULL | 130 | WHERE id = $1 AND archived_at IS NULL |
| 127 | - RETURNING id, name, starts_at, ends_at, archived_at"#, | 131 | + RETURNING id AS "id: TermId", name AS "name: TermName", |
| 128 | - term.id, | 132 | + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", |
| 129 | - Timestamp::now(), | 133 | + archived_at AS "archived_at: Timestamp""#, |
| 134 | + term.id.uuid(), | ||
| 135 | + Timestamp::now().as_millis(), | ||
| 130 | ) | 136 | ) |
| 131 | .fetch_optional(db) | 137 | .fetch_optional(db) |
| 132 | .await?; | 138 | .await?; |
| @@ -144,8 +150,10 @@ pub async fn unarchive(db: &Database, term: Term) -> Result<Term, AppError> { | |||
| 144 | Term, | 150 | Term, |
| 145 | r#"UPDATE term SET archived_at = NULL | 151 | r#"UPDATE term SET archived_at = NULL |
| 146 | WHERE id = $1 AND archived_at IS NOT NULL | 152 | WHERE id = $1 AND archived_at IS NOT NULL |
| 147 | - RETURNING id, name, starts_at, ends_at, archived_at"#, | 153 | + RETURNING id AS "id: TermId", name AS "name: TermName", |
| 148 | - term.id, | 154 | + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", |
| 155 | + archived_at AS "archived_at: Timestamp""#, | ||
| 156 | + term.id.uuid(), | ||
| 149 | ) | 157 | ) |
| 150 | .fetch_optional(db) | 158 | .fetch_optional(db) |
| 151 | .await?; | 159 | .await?; |
src/db/user.rsmodified+23 -15
| @@ -75,7 +75,7 @@ pub async fn create_with_role( | |||
| 75 | id.uuid(), | 75 | id.uuid(), |
| 76 | username.as_str(), | 76 | username.as_str(), |
| 77 | password_hash.as_str(), | 77 | password_hash.as_str(), |
| 78 | - role, | 78 | + role.as_str(), |
| 79 | ) | 79 | ) |
| 80 | .fetch_one(db) | 80 | .fetch_one(db) |
| 81 | .await | 81 | .await |
| @@ -153,7 +153,7 @@ pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result<Vec<User>, App | |||
| 153 | avatar_content_type AS "avatar_content_type: FileContentType", | 153 | avatar_content_type AS "avatar_content_type: FileContentType", |
| 154 | avatar_size | 154 | avatar_size |
| 155 | FROM app_user WHERE id = ANY($1)"#, | 155 | FROM app_user WHERE id = ANY($1)"#, |
| 156 | - ids | 156 | + &ids |
| 157 | ) | 157 | ) |
| 158 | .fetch_all(db) | 158 | .fetch_all(db) |
| 159 | .await?; | 159 | .await?; |
| @@ -184,7 +184,7 @@ pub async fn list_by_role(db: &Database, role: Role) -> Result<Vec<User>, AppErr | |||
| 184 | avatar_content_type AS "avatar_content_type: FileContentType", | 184 | avatar_content_type AS "avatar_content_type: FileContentType", |
| 185 | avatar_size | 185 | avatar_size |
| 186 | FROM app_user WHERE role = $1 ORDER BY id DESC"#, | 186 | FROM app_user WHERE role = $1 ORDER BY id DESC"#, |
| 187 | - role | 187 | + role.as_str() |
| 188 | ) | 188 | ) |
| 189 | .fetch_all(db) | 189 | .fetch_all(db) |
| 190 | .await?; | 190 | .await?; |
| @@ -344,7 +344,10 @@ pub async fn set_role_cascade( | |||
| 344 | // One wall-clock read for the whole cascade, bound by every stamping | 344 | // One wall-clock read for the whole cascade, bound by every stamping |
| 345 | // statement — the old batch's single `$now`. | 345 | // statement — the old batch's single `$now`. |
| 346 | let now = Timestamp::now().as_millis(); | 346 | let now = Timestamp::now().as_millis(); |
| 347 | - tx_with_retry(db, true, async |tx| { | 347 | + // Owned capture: an `async move` closure holding a `&UserId` fails the |
| 348 | + // higher-ranked `Send` check `tx_with_retry`'s future must pass. | ||
| 349 | + let target = *target; | ||
| 350 | + tx_with_retry(db, true, async move |tx| { | ||
| 348 | // The role write, floor guard included. `$2 <> 'admin'` arms the | 351 | // The role write, floor guard included. `$2 <> 'admin'` arms the |
| 349 | // guard only for a demotion: a promotion or a same-role rewrite can | 352 | // guard only for a demotion: a promotion or a same-role rewrite can |
| 350 | // never orphan the admins. | 353 | // never orphan the admins. |
| @@ -374,7 +377,7 @@ pub async fn set_role_cascade( | |||
| 374 | avatar_content_type AS "avatar_content_type: FileContentType", | 377 | avatar_content_type AS "avatar_content_type: FileContentType", |
| 375 | avatar_size"#, | 378 | avatar_size"#, |
| 376 | target.uuid(), | 379 | target.uuid(), |
| 377 | - role, | 380 | + role.as_str(), |
| 378 | ) | 381 | ) |
| 379 | .fetch_optional(&mut *tx) | 382 | .fetch_optional(&mut *tx) |
| 380 | .await?; | 383 | .await?; |
| @@ -591,13 +594,13 @@ pub async fn set_profile( | |||
| 591 | value.map(|inner| Param::OptText(inner.map(str::to_string))) | 594 | value.map(|inner| Param::OptText(inner.map(str::to_string))) |
| 592 | } | 595 | } |
| 593 | FieldUpdate::new("app_user", id.uuid()) | 596 | FieldUpdate::new("app_user", id.uuid()) |
| 594 | - .set("name", text(name.map(|n| n.as_str()))) | 597 | + .set("name", text(name.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) |
| 595 | - .set("surname", text(surname.map(|n| n.as_str()))) | 598 | + .set("surname", text(surname.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) |
| 596 | - .set("email", text(email.map(|n| n.as_str()))) | 599 | + .set("email", text(email.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) |
| 597 | - .set("phone", text(phone.map(|n| n.as_str()))) | 600 | + .set("phone", text(phone.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) |
| 598 | - .set("birth_date", text(birth_date.map(|n| n.as_str()))) | 601 | + .set("birth_date", text(birth_date.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) |
| 599 | - .set("display_name", text(display_name.map(|n| n.as_str()))) | 602 | + .set("display_name", text(display_name.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) |
| 600 | - .set("bio", text(bio.map(|n| n.as_str()))) | 603 | + .set("bio", text(bio.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) |
| 601 | .run(db) | 604 | .run(db) |
| 602 | .await | 605 | .await |
| 603 | } | 606 | } |
| @@ -622,7 +625,11 @@ pub async fn set_avatar( | |||
| 622 | content_type: &FileContentType, | 625 | content_type: &FileContentType, |
| 623 | size: i64, | 626 | size: i64, |
| 624 | ) -> Result<Option<User>, AppError> { | 627 | ) -> Result<Option<User>, AppError> { |
| 625 | - tx_with_retry(db, false, async |tx| { | 628 | + // Owned captures, same `Send` rule as every `tx_with_retry` closure. |
| 629 | + let id = *id; | ||
| 630 | + let file = file.to_string(); | ||
| 631 | + let content_type = content_type.clone(); | ||
| 632 | + tx_with_retry(db, false, async move |tx| { | ||
| 626 | let before = sqlx::query_as!( | 633 | let before = sqlx::query_as!( |
| 627 | User, | 634 | User, |
| 628 | r#"SELECT id AS "id: UserId", | 635 | r#"SELECT id AS "id: UserId", |
| @@ -655,7 +662,7 @@ pub async fn set_avatar( | |||
| 655 | SET avatar_file = $2, avatar_content_type = $3, avatar_size = $4 | 662 | SET avatar_file = $2, avatar_content_type = $3, avatar_size = $4 |
| 656 | WHERE id = $1"#, | 663 | WHERE id = $1"#, |
| 657 | id.uuid(), | 664 | id.uuid(), |
| 658 | - file, | 665 | + file.as_str(), |
| 659 | content_type.as_str(), | 666 | content_type.as_str(), |
| 660 | size, | 667 | size, |
| 661 | ) | 668 | ) |
| @@ -669,7 +676,8 @@ pub async fn set_avatar( | |||
| 669 | /// Drop the avatar, returning the row as it was so the caller can delete | 676 | /// Drop the avatar, returning the row as it was so the caller can delete |
| 670 | /// the blob. Same pre-image contract as [`set_avatar`]. | 677 | /// the blob. Same pre-image contract as [`set_avatar`]. |
| 671 | pub async fn clear_avatar(db: &Database, id: &UserId) -> Result<Option<User>, AppError> { | 678 | pub async fn clear_avatar(db: &Database, id: &UserId) -> Result<Option<User>, AppError> { |
| 672 | - tx_with_retry(db, false, async |tx| { | 679 | + let id = *id; |
| 680 | + tx_with_retry(db, false, async move |tx| { | ||
| 673 | let before = sqlx::query_as!( | 681 | let before = sqlx::query_as!( |
| 674 | User, | 682 | User, |
| 675 | r#"SELECT id AS "id: UserId", | 683 | r#"SELECT id AS "id: UserId", |
src/db/work_entry.rsmodified+19 -19
| @@ -47,10 +47,10 @@ pub async fn check_in(db: &Database, user: &UserId) -> Result<WorkEntry, AppErro | |||
| 47 | let inserted = sqlx::query_as!( | 47 | let inserted = sqlx::query_as!( |
| 48 | WorkEntryRow, | 48 | WorkEntryRow, |
| 49 | "INSERT INTO work_entry (id, app_user, check_in) VALUES ($1, $2, $3) \ | 49 | "INSERT INTO work_entry (id, app_user, check_in) VALUES ($1, $2, $3) \ |
| 50 | - RETURNING id, app_user, check_in, check_out", | 50 | + RETURNING id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\"", |
| 51 | - id, | 51 | + id.uuid(), |
| 52 | - user, | 52 | + user.uuid(), |
| 53 | - check_in, | 53 | + check_in.as_millis(), |
| 54 | ) | 54 | ) |
| 55 | .fetch_one(db) | 55 | .fetch_one(db) |
| 56 | .await; | 56 | .await; |
| @@ -75,9 +75,9 @@ pub async fn check_out(db: &Database, user: &UserId) -> Result<WorkEntry, AppErr | |||
| 75 | WorkEntryRow, | 75 | WorkEntryRow, |
| 76 | "UPDATE work_entry SET check_out = $2 \ | 76 | "UPDATE work_entry SET check_out = $2 \ |
| 77 | WHERE app_user = $1 AND check_out IS NULL \ | 77 | WHERE app_user = $1 AND check_out IS NULL \ |
| 78 | - RETURNING id, app_user, check_in, check_out", | 78 | + RETURNING id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\"", |
| 79 | - user, | 79 | + user.uuid(), |
| 80 | - out, | 80 | + out.as_millis(), |
| 81 | ) | 81 | ) |
| 82 | .fetch_optional(db) | 82 | .fetch_optional(db) |
| 83 | .await?; | 83 | .await?; |
| @@ -89,8 +89,8 @@ pub async fn check_out(db: &Database, user: &UserId) -> Result<WorkEntry, AppErr | |||
| 89 | pub async fn read(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> { | 89 | pub async fn read(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> { |
| 90 | let row = sqlx::query_as!( | 90 | let row = sqlx::query_as!( |
| 91 | WorkEntryRow, | 91 | WorkEntryRow, |
| 92 | - "SELECT id, app_user, check_in, check_out FROM work_entry WHERE id = $1", | 92 | + "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", |
| 93 | - id, | 93 | + id.uuid(), |
| 94 | ) | 94 | ) |
| 95 | .fetch_optional(db) | 95 | .fetch_optional(db) |
| 96 | .await?; | 96 | .await?; |
| @@ -111,10 +111,10 @@ pub async fn list_for_user( | |||
| 111 | Some(limit) => { | 111 | Some(limit) => { |
| 112 | sqlx::query_as!( | 112 | sqlx::query_as!( |
| 113 | WorkEntryRow, | 113 | WorkEntryRow, |
| 114 | - "SELECT id, app_user, check_in, check_out FROM work_entry \ | 114 | + "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 \ |
| 115 | WHERE app_user = $1 ORDER BY check_in DESC, id DESC \ | 115 | WHERE app_user = $1 ORDER BY check_in DESC, id DESC \ |
| 116 | LIMIT $2 OFFSET $3", | 116 | LIMIT $2 OFFSET $3", |
| 117 | - user, | 117 | + user.uuid(), |
| 118 | limit, | 118 | limit, |
| 119 | offset, | 119 | offset, |
| 120 | ) | 120 | ) |
| @@ -124,10 +124,10 @@ pub async fn list_for_user( | |||
| 124 | None if offset > 0 => { | 124 | None if offset > 0 => { |
| 125 | sqlx::query_as!( | 125 | sqlx::query_as!( |
| 126 | WorkEntryRow, | 126 | WorkEntryRow, |
| 127 | - "SELECT id, app_user, check_in, check_out FROM work_entry \ | 127 | + "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 \ |
| 128 | WHERE app_user = $1 ORDER BY check_in DESC, id DESC \ | 128 | WHERE app_user = $1 ORDER BY check_in DESC, id DESC \ |
| 129 | OFFSET $2", | 129 | OFFSET $2", |
| 130 | - user, | 130 | + user.uuid(), |
| 131 | offset, | 131 | offset, |
| 132 | ) | 132 | ) |
| 133 | .fetch_all(db) | 133 | .fetch_all(db) |
| @@ -136,9 +136,9 @@ pub async fn list_for_user( | |||
| 136 | None => { | 136 | None => { |
| 137 | sqlx::query_as!( | 137 | sqlx::query_as!( |
| 138 | WorkEntryRow, | 138 | WorkEntryRow, |
| 139 | - "SELECT id, app_user, check_in, check_out FROM work_entry \ | 139 | + "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 \ |
| 140 | WHERE app_user = $1 ORDER BY check_in DESC, id DESC", | 140 | WHERE app_user = $1 ORDER BY check_in DESC, id DESC", |
| 141 | - user, | 141 | + user.uuid(), |
| 142 | ) | 142 | ) |
| 143 | .fetch_all(db) | 143 | .fetch_all(db) |
| 144 | .await? | 144 | .await? |
| @@ -147,10 +147,10 @@ pub async fn list_for_user( | |||
| 147 | // A window that can hide rows needs the count over the same WHERE; | 147 | // A window that can hide rows needs the count over the same WHERE; |
| 148 | // an unpaged read from row zero already holds every row. | 148 | // an unpaged read from row zero already holds every row. |
| 149 | let total = if limit.is_some() || offset > 0 { | 149 | let total = if limit.is_some() || offset > 0 { |
| 150 | - sqlx::query!("SELECT count(*) FROM work_entry WHERE app_user = $1", user) | 150 | + sqlx::query_scalar!("SELECT count(*) FROM work_entry WHERE app_user = $1", user.uuid()) |
| 151 | .fetch_one(db) | 151 | .fetch_one(db) |
| 152 | .await? | 152 | .await? |
| 153 | - .0 | 153 | + .unwrap_or(0) |
| 154 | } else { | 154 | } else { |
| 155 | rows.len() as i64 | 155 | rows.len() as i64 |
| 156 | }; | 156 | }; |
| @@ -185,8 +185,8 @@ pub async fn remove(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry> | |||
| 185 | let row = sqlx::query_as!( | 185 | let row = sqlx::query_as!( |
| 186 | WorkEntryRow, | 186 | WorkEntryRow, |
| 187 | "DELETE FROM work_entry WHERE id = $1 \ | 187 | "DELETE FROM work_entry WHERE id = $1 \ |
| 188 | - RETURNING id, app_user, check_in, check_out", | 188 | + RETURNING id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\"", |
| 189 | - id, | 189 | + id.uuid(), |
| 190 | ) | 190 | ) |
| 191 | .fetch_optional(db) | 191 | .fetch_optional(db) |
| 192 | .await?; | 192 | .await?; |
src/domain/appointment.rsmodified+0 -1
| @@ -25,7 +25,6 @@ | |||
| 25 | //! ([`crate::db::appointment::save_if_unchanged`]), decided by a conditional | 25 | //! ([`crate::db::appointment::save_if_unchanged`]), decided by a conditional |
| 26 | //! `UPDATE`. | 26 | //! `UPDATE`. |
| 27 | 27 | ||
| 28 | -use uuid::Uuid; | ||
| 29 | use crate::constant::{MAX_APPOINTMENT_REASON_LEN}; | 28 | use crate::constant::{MAX_APPOINTMENT_REASON_LEN}; |
| 30 | use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; | 29 | use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; |
| 31 | use crate::domain::monotonic_id::next_uuid; | 30 | use crate::domain::monotonic_id::next_uuid; |
src/domain/appointment_slot.rsmodified+0 -1
| @@ -19,7 +19,6 @@ | |||
| 19 | //! live in [`crate::db::appointment_slot`]; the publish and delete workflows | 19 | //! live in [`crate::db::appointment_slot`]; the publish and delete workflows |
| 20 | //! in [`crate::service::appointment_slot`]. | 20 | //! in [`crate::service::appointment_slot`]. |
| 21 | 21 | ||
| 22 | -use uuid::Uuid; | ||
| 23 | use crate::constant::{ | 22 | use crate::constant::{ |
| 24 | MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, | 23 | MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, |
| 25 | }; | 24 | }; |
src/domain/bank_question.rsmodified+8 -0
| @@ -151,6 +151,14 @@ impl BankQuestion { | |||
| 151 | self.correct.as_ref() | 151 | self.correct.as_ref() |
| 152 | } | 152 | } |
| 153 | 153 | ||
| 154 | + /// The stored options of a choice template (`None` for a text one) — the | ||
| 155 | + /// same shape [`crate::domain::exam_question::ExamQuestion::get_choices`] | ||
| 156 | + /// gives the exam side, so the web layer's response builder reads both | ||
| 157 | + /// alike. | ||
| 158 | + pub fn get_choices(&self) -> Option<&[Choice]> { | ||
| 159 | + self.choices.as_ref().map(|json| json.0.as_slice()) | ||
| 160 | + } | ||
| 161 | + | ||
| 154 | pub fn get_source_exam(&self) -> Option<&ExamId> { | 162 | pub fn get_source_exam(&self) -> Option<&ExamId> { |
| 155 | self.source_exam.as_ref() | 163 | self.source_exam.as_ref() |
| 156 | } | 164 | } |
src/domain/chatbot_message.rsmodified+0 -1
| @@ -9,7 +9,6 @@ | |||
| 9 | //! ([`ChatbotMessage::projected`]) — the durable repair for a dead process | 9 | //! ([`ChatbotMessage::projected`]) — the durable repair for a dead process |
| 10 | //! happens once, at mint, in `database.rs`'s school migration sweep. | 10 | //! happens once, at mint, in `database.rs`'s school migration sweep. |
| 11 | 11 | ||
| 12 | -use uuid::Uuid; | ||
| 13 | use crate::constant::{ | 12 | use crate::constant::{ |
| 14 | CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE, | 13 | CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE, |
| 15 | }; | 14 | }; |
src/domain/chatbot_thread.rsmodified+0 -1
| @@ -4,7 +4,6 @@ | |||
| 4 | //! [`crate::db::chatbot_message`], and deleting a thread cascades them; the | 4 | //! [`crate::db::chatbot_message`], and deleting a thread cascades them; the |
| 5 | //! threads' own persistence lives in [`crate::db::chatbot_thread`]. | 5 | //! threads' own persistence lives in [`crate::db::chatbot_thread`]. |
| 6 | 6 | ||
| 7 | -use uuid::Uuid; | ||
| 8 | use crate::constant::{MAX_CHATBOT_THREAD_TITLE_LEN}; | 7 | use crate::constant::{MAX_CHATBOT_THREAD_TITLE_LEN}; |
| 9 | use crate::domain::monotonic_id::next_uuid; | 8 | use crate::domain::monotonic_id::next_uuid; |
| 10 | use crate::domain::timestamp::Timestamp; | 9 | use crate::domain::timestamp::Timestamp; |
src/domain/event.rsmodified+2 -3
| @@ -7,7 +7,6 @@ use crate::domain::timestamp::Timestamp; | |||
| 7 | use crate::domain::user::UserId; | 7 | use crate::domain::user::UserId; |
| 8 | use crate::error::{AppError, ValidationError}; | 8 | use crate::error::{AppError, ValidationError}; |
| 9 | use crate::validate::{validate_optional, validate_required}; | 9 | use crate::validate::{validate_optional, validate_required}; |
| 10 | -use uuid::Uuid; | ||
| 11 | 10 | ||
| 12 | #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] | 11 | #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 13 | #[sqlx(transparent)] | 12 | #[sqlx(transparent)] |
| @@ -160,8 +159,8 @@ impl EventAudience { | |||
| 160 | Self { | 159 | Self { |
| 161 | kind: event.get_audience_kind(), | 160 | kind: event.get_audience_kind(), |
| 162 | role: event.get_audience_role(), | 161 | role: event.get_audience_role(), |
| 163 | - course: event.get_audience_course().copied(), | 162 | + course: event.get_audience_course().cloned(), |
| 164 | - class: event.get_audience_class().copied(), | 163 | + class: event.get_audience_class().cloned(), |
| 165 | capacity: event.get_audience_capacity(), | 164 | capacity: event.get_audience_capacity(), |
| 166 | } | 165 | } |
| 167 | } | 166 | } |
src/domain/exam.rsmodified+0 -1
| @@ -5,7 +5,6 @@ use crate::domain::settings::ExamKindDef; | |||
| 5 | use crate::domain::timestamp::Timestamp; | 5 | use crate::domain::timestamp::Timestamp; |
| 6 | use crate::domain::user::UserId; | 6 | use crate::domain::user::UserId; |
| 7 | use crate::error::{AppError, ValidationError}; | 7 | use crate::error::{AppError, ValidationError}; |
| 8 | -use uuid::Uuid; | ||
| 9 | 8 | ||
| 10 | /// The one spelling of the re-draft refusal, shared by the update workflow's | 9 | /// The one spelling of the re-draft refusal, shared by the update workflow's |
| 11 | /// pre-flight gate ([`crate::service::exam::update`]) and the in-transaction | 10 | /// pre-flight gate ([`crate::service::exam::update`]) and the in-transaction |
src/domain/exam_question.rsmodified+0 -1
| @@ -1,5 +1,4 @@ | |||
| 1 | use sqlx::types::Json; | 1 | use sqlx::types::Json; |
| 2 | -use uuid::Uuid; | ||
| 3 | 2 | ||
| 4 | use crate::constant::{ | 3 | use crate::constant::{ |
| 5 | MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, MIN_QUESTION_CHOICES, | 4 | MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, MIN_QUESTION_CHOICES, |
src/domain/fee_plan.rsmodified+0 -1
| @@ -13,7 +13,6 @@ | |||
| 13 | //! apply here. | 13 | //! apply here. |
| 14 | 14 | ||
| 15 | use sqlx::types::Json; | 15 | use sqlx::types::Json; |
| 16 | -use uuid::Uuid; | ||
| 17 | 16 | ||
| 18 | use crate::constant::{MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN}; | 17 | use crate::constant::{MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN}; |
| 19 | use crate::domain::monotonic_id::next_uuid; | 18 | use crate::domain::monotonic_id::next_uuid; |
src/domain/meal_ledger.rsmodified+1 -1
| @@ -333,7 +333,7 @@ impl MealLedger { | |||
| 333 | student: booking.get_student().clone(), | 333 | student: booking.get_student().clone(), |
| 334 | kind: MealLedgerKind::Reversal, | 334 | kind: MealLedgerKind::Reversal, |
| 335 | amount_minor: amount, | 335 | amount_minor: amount, |
| 336 | - source: Some(charge.key()), | 336 | + source: Some(charge.key().to_string()), |
| 337 | method: None, | 337 | method: None, |
| 338 | note: None, | 338 | note: None, |
| 339 | recorded_by: recorded_by.clone(), | 339 | recorded_by: recorded_by.clone(), |
src/domain/registration.rsmodified+2 -2
| @@ -15,7 +15,7 @@ pub struct RegistrationId { | |||
| 15 | impl RegistrationId { | 15 | impl RegistrationId { |
| 16 | pub fn composite(event: &EventId, user: &UserId) -> Self { | 16 | pub fn composite(event: &EventId, user: &UserId) -> Self { |
| 17 | Self { | 17 | Self { |
| 18 | - event: *event, | 18 | + event: event.clone(), |
| 19 | user: *user, | 19 | user: *user, |
| 20 | } | 20 | } |
| 21 | } | 21 | } |
| @@ -38,7 +38,7 @@ impl RegistrationId { | |||
| 38 | } | 38 | } |
| 39 | 39 | ||
| 40 | pub fn event(&self) -> EventId { | 40 | pub fn event(&self) -> EventId { |
| 41 | - self.event | 41 | + self.event.clone() |
| 42 | } | 42 | } |
| 43 | 43 | ||
| 44 | pub fn user(&self) -> UserId { | 44 | pub fn user(&self) -> UserId { |
src/domain/session_attendance.rsmodified+2 -2
| @@ -16,7 +16,7 @@ pub struct SessionAttendanceId { | |||
| 16 | impl SessionAttendanceId { | 16 | impl SessionAttendanceId { |
| 17 | pub fn composite(session: &CourseSessionId, user: &UserId) -> Self { | 17 | pub fn composite(session: &CourseSessionId, user: &UserId) -> Self { |
| 18 | Self { | 18 | Self { |
| 19 | - session: *session, | 19 | + session: session.clone(), |
| 20 | user: *user, | 20 | user: *user, |
| 21 | } | 21 | } |
| 22 | } | 22 | } |
| @@ -39,7 +39,7 @@ impl SessionAttendanceId { | |||
| 39 | } | 39 | } |
| 40 | 40 | ||
| 41 | pub fn session(&self) -> CourseSessionId { | 41 | pub fn session(&self) -> CourseSessionId { |
| 42 | - self.session | 42 | + self.session.clone() |
| 43 | } | 43 | } |
| 44 | 44 | ||
| 45 | pub fn user(&self) -> UserId { | 45 | pub fn user(&self) -> UserId { |
src/rate_limit.rsmodified+15 -11
| @@ -92,8 +92,8 @@ use axum::response::Response; | |||
| 92 | use tokio::time::Instant; | 92 | use tokio::time::Instant; |
| 93 | 93 | ||
| 94 | use crate::constant::{ | 94 | use crate::constant::{ |
| 95 | - PURGE_AT, RATE_LIMIT_OVERFLOW_MAX, RATE_LIMIT_TABLE, RATE_SYNC_INTERVAL_SECS, | 95 | + PURGE_AT, RATE_LIMIT_OVERFLOW_MAX, RATE_SYNC_INTERVAL_SECS, RATE_SYNC_MAX_KEYS, |
| 96 | - RATE_SYNC_MAX_KEYS, RATE_SYNC_TIMEOUT_SECS, | 96 | + RATE_SYNC_TIMEOUT_SECS, |
| 97 | }; | 97 | }; |
| 98 | use crate::database::Database; | 98 | use crate::database::Database; |
| 99 | use crate::domain::timestamp::Timestamp; | 99 | use crate::domain::timestamp::Timestamp; |
| @@ -474,9 +474,12 @@ where | |||
| 474 | // has passed can never be read again. | 474 | // has passed can never be read again. |
| 475 | if swept != epoch { | 475 | if swept != epoch { |
| 476 | swept = epoch; | 476 | swept = epoch; |
| 477 | - let sql = format!("DELETE FROM {RATE_LIMIT_TABLE} WHERE window_start < $1"); | 477 | + if let Err(err) = with_deadline( |
| 478 | - if let Err(err) = | 478 | + sqlx::query("DELETE FROM rate_limit WHERE window_start < $1") |
| 479 | - with_deadline(sqlx::query(&sql).bind(epoch).execute(&db)).await | 479 | + .bind(epoch) |
| 480 | + .execute(&db), | ||
| 481 | + ) | ||
| 482 | + .await | ||
| 480 | { | 483 | { |
| 481 | tracing::warn!(%err, "rate-limit sweep failed; retrying next window"); | 484 | tracing::warn!(%err, "rate-limit sweep failed; retrying next window"); |
| 482 | } | 485 | } |
| @@ -549,17 +552,18 @@ async fn sync_once<K: Eq + Hash + Clone + std::fmt::Display>( | |||
| 549 | // (`row_key` folds the epoch in), so a conflict can only be another | 552 | // (`row_key` folds the epoch in), so a conflict can only be another |
| 550 | // limiter of the same tier folding the same client inside the same window | 553 | // limiter of the same tier folding the same client inside the same window |
| 551 | // — the ON CONFLICT fold is exactly the replay that must add, not clobber. | 554 | // — the ON CONFLICT fold is exactly the replay that must add, not clobber. |
| 552 | - let mut fold = sqlx::QueryBuilder::<sqlx::Postgres>::new(); | 555 | + let mut fold = sqlx::QueryBuilder::<sqlx::Postgres>::new( |
| 553 | - fold.push("INSERT INTO ") | 556 | + "INSERT INTO rate_limit (id, hits, window_start) ", |
| 554 | - .push(RATE_LIMIT_TABLE) | 557 | + ); |
| 555 | - .push(" (id, hits, window_start) "); | ||
| 556 | fold.push_values(pending.iter(), |mut b, p| { | 558 | fold.push_values(pending.iter(), |mut b, p| { |
| 557 | b.push_bind(row_key(tier, &p.key, epoch)) | 559 | b.push_bind(row_key(tier, &p.key, epoch)) |
| 558 | .push_bind(i64::from(p.delta)) | 560 | .push_bind(i64::from(p.delta)) |
| 559 | .push_bind(epoch); | 561 | .push_bind(epoch); |
| 560 | }); | 562 | }); |
| 561 | - fold.push(" ON CONFLICT (id) DO UPDATE SET hits = rate_limit.hits + EXCLUDED.hits RETURNING id, hits"); | 563 | + fold.push( |
| 562 | - let rows: Vec<(String, i64)> = match with_deadline(fold.build_query_as()).await { | 564 | + " ON CONFLICT (id) DO UPDATE SET hits = rate_limit.hits + EXCLUDED.hits RETURNING id, hits", |
| 565 | + ); | ||
| 566 | + let rows: Vec<(String, i64)> = match with_deadline(fold.build_query_as().fetch_all(db)).await { | ||
| 563 | Ok(rows) => rows, | 567 | Ok(rows) => rows, |
| 564 | Err(err) => { | 568 | Err(err) => { |
| 565 | tracing::warn!(%err, tier, "rate-limit sync failed; counting locally until it recovers"); | 569 | tracing::warn!(%err, tier, "rate-limit sync failed; counting locally until it recovers"); |
src/service/appointment.rsmodified+7 -4
| @@ -175,7 +175,10 @@ async fn approve_inner( | |||
| 175 | decided_by: &UserId, | 175 | decided_by: &UserId, |
| 176 | accepting: Option<(Timestamp, Timestamp)>, | 176 | accepting: Option<(Timestamp, Timestamp)>, |
| 177 | ) -> Result<Appointment, AppError> { | 177 | ) -> Result<Appointment, AppError> { |
| 178 | - tx_with_retry(db, false, async |tx| { | 178 | + // Owned captures (`Send` rule of `tx_with_retry` closures). |
| 179 | + let id = id.clone(); | ||
| 180 | + let decided_by = *decided_by; | ||
| 181 | + tx_with_retry(db, false, async move |tx| { | ||
| 179 | // Serializable for the overlap decision below (module doc). `SET | 182 | // Serializable for the overlap decision below (module doc). `SET |
| 180 | // TRANSACTION` is legal only before the first query, so it goes | 183 | // TRANSACTION` is legal only before the first query, so it goes |
| 181 | // first; a `40001` from SSI is re-sent by the retry loop, and the | 184 | // first; a `40001` from SSI is re-sent by the retry loop, and the |
| @@ -183,7 +186,7 @@ async fn approve_inner( | |||
| 183 | sqlx::query!("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE") | 186 | sqlx::query!("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE") |
| 184 | .execute(&mut *tx) | 187 | .execute(&mut *tx) |
| 185 | .await?; | 188 | .await?; |
| 186 | - let expected = appointment::read_pending_on(&mut *tx, id).await?; | 189 | + let expected = appointment::read_pending_on(&mut *tx, &id).await?; |
| 187 | match accepting { | 190 | match accepting { |
| 188 | None if expected.has_proposal() => { | 191 | None if expected.has_proposal() => { |
| 189 | return Err(AppError::Conflict( | 192 | return Err(AppError::Conflict( |
| @@ -226,7 +229,7 @@ async fn approve_inner( | |||
| 226 | expected.get_requester(), | 229 | expected.get_requester(), |
| 227 | starts_at, | 230 | starts_at, |
| 228 | ends_at, | 231 | ends_at, |
| 229 | - Some(id), | 232 | + Some(&id), |
| 230 | ) | 233 | ) |
| 231 | .await? | 234 | .await? |
| 232 | { | 235 | { |
| @@ -236,7 +239,7 @@ async fn approve_inner( | |||
| 236 | } | 239 | } |
| 237 | let mut approved = expected.clone(); | 240 | let mut approved = expected.clone(); |
| 238 | approved.status = AppointmentStatus::Approved; | 241 | approved.status = AppointmentStatus::Approved; |
| 239 | - approved.decided_by = Some(decided_by.clone()); | 242 | + approved.decided_by = Some(decided_by); |
| 240 | match appointment::decision_cas(&mut *tx, &expected, approved).await? { | 243 | match appointment::decision_cas(&mut *tx, &expected, approved).await? { |
| 241 | Some(saved) => Ok(saved), | 244 | Some(saved) => Ok(saved), |
| 242 | // Unreachable under the row lock this transaction holds — kept | 245 | // Unreachable under the row lock this transaction holds — kept |
src/service/exam.rsmodified+2 -0
| @@ -8,6 +8,7 @@ | |||
| 8 | use crate::constant::CAS_UPDATE_RETRIES; | 8 | use crate::constant::CAS_UPDATE_RETRIES; |
| 9 | use crate::database::Database; | 9 | use crate::database::Database; |
| 10 | use crate::db::exam; | 10 | use crate::db::exam; |
| 11 | +use crate::db::exam_attempt::any_for_exam; | ||
| 11 | use crate::db::exam_result; | 12 | use crate::db::exam_result; |
| 12 | use crate::domain::course::CourseId; | 13 | use crate::domain::course::CourseId; |
| 13 | use crate::domain::exam::{ | 14 | use crate::domain::exam::{ |
| @@ -18,6 +19,7 @@ use crate::domain::timestamp::Timestamp; | |||
| 18 | use crate::domain::user::UserId; | 19 | use crate::domain::user::UserId; |
| 19 | use crate::error::AppError; | 20 | use crate::error::AppError; |
| 20 | use crate::service::course::require_open; | 21 | use crate::service::course::require_open; |
| 22 | +use crate::service::exam_attempt::course_of; | ||
| 21 | 23 | ||
| 22 | #[expect( | 24 | #[expect( |
| 23 | clippy::too_many_arguments, | 25 | clippy::too_many_arguments, |
src/service/exam_attempt.rsmodified+0 -1
| @@ -178,7 +178,6 @@ pub async fn start( | |||
| 178 | } | 178 | } |
| 179 | }; | 179 | }; |
| 180 | let attempt = ExamAttempt { | 180 | let attempt = ExamAttempt { |
| 181 | - id: ExamAttemptId::composite(exam.get_id(), user, next_seq), | ||
| 182 | exam: exam.get_id().clone(), | 181 | exam: exam.get_id().clone(), |
| 183 | user: user.clone(), | 182 | user: user.clone(), |
| 184 | seq: next_seq, | 183 | seq: next_seq, |
src/service/meal_booking.rsmodified+2 -3
| @@ -122,7 +122,6 @@ pub async fn book( | |||
| 122 | // booked-but-unbilled row behind. | 122 | // booked-but-unbilled row behind. |
| 123 | let price = meal_ledger::price_snapshot(db, menu).await?; | 123 | let price = meal_ledger::price_snapshot(db, menu).await?; |
| 124 | let fresh_row = MealBooking { | 124 | let fresh_row = MealBooking { |
| 125 | - id: id.clone(), | ||
| 126 | menu: menu.clone(), | 125 | menu: menu.clone(), |
| 127 | student: student.clone(), | 126 | student: student.clone(), |
| 128 | booked_by: booked_by.clone(), | 127 | booked_by: booked_by.clone(), |
| @@ -227,7 +226,7 @@ pub async fn cancel( | |||
| 227 | cutoff: &MealCutoff, | 226 | cutoff: &MealCutoff, |
| 228 | recorded_by: &UserId, | 227 | recorded_by: &UserId, |
| 229 | ) -> Result<MealBooking, AppError> { | 228 | ) -> Result<MealBooking, AppError> { |
| 230 | - let fresh = meal_booking::read(db, &cancelled.id) | 229 | + let fresh = meal_booking::read(db, &cancelled.id()) |
| 231 | .await? | 230 | .await? |
| 232 | .ok_or(AppError::NotFound)?; | 231 | .ok_or(AppError::NotFound)?; |
| 233 | if fresh.status == MealBookingStatus::Cancelled { | 232 | if fresh.status == MealBookingStatus::Cancelled { |
| @@ -245,7 +244,7 @@ pub async fn cancel( | |||
| 245 | let saved = match meal_booking::release_seat(db, &fresh, recorded_by).await? { | 244 | let saved = match meal_booking::release_seat(db, &fresh, recorded_by).await? { |
| 246 | Some(cancelled) => cancelled, | 245 | Some(cancelled) => cancelled, |
| 247 | None => { | 246 | None => { |
| 248 | - let live = meal_booking::read(db, &cancelled.id) | 247 | + let live = meal_booking::read(db, &cancelled.id()) |
| 249 | .await? | 248 | .await? |
| 250 | .ok_or(AppError::NotFound)?; | 249 | .ok_or(AppError::NotFound)?; |
| 251 | if !refundable_after_lost_flip(&fresh, &live)? { | 250 | if !refundable_after_lost_flip(&fresh, &live)? { |
src/service/payment_ledger.rsmodified+33 -19
| @@ -170,14 +170,23 @@ async fn against( | |||
| 170 | } | 170 | } |
| 171 | .into()); | 171 | .into()); |
| 172 | } | 172 | } |
| 173 | - tx_with_retry(db, false, async |tx| { | 173 | + // Owned captures: a closure holding a `&T` fails the higher-ranked |
| 174 | + // `Send` check `tx_with_retry`'s future must pass. | ||
| 175 | + let target = target.clone(); | ||
| 176 | + let recorded_by = *recorded_by; | ||
| 177 | + tx_with_retry(db, false, async move |tx| { | ||
| 174 | // Every writer that can move this target's arithmetic holds some row | 178 | // Every writer that can move this target's arithmetic holds some row |
| 175 | // on this chain; holding the whole walk to the root is what makes | 179 | // on this chain; holding the whole walk to the root is what makes |
| 176 | // the fold below and the append it authorizes one decision. | 180 | // the fold below and the append it authorizes one decision. |
| 177 | payment_ledger::lock_for_cap(&mut *tx, &target.id).await?; | 181 | payment_ledger::lock_for_cap(&mut *tx, &target.id).await?; |
| 178 | - if let Some(id) = keyed.clone() | 182 | + // Awaits sit in match arms, never in a `let`-chain condition: an |
| 179 | - && let Some(existing) = payment_ledger::read(&mut *tx, &id).await? | 183 | + // awaited condition poisons the closure future's higher-ranked |
| 180 | - { | 184 | + // `Send` that `tx_with_retry` requires. |
| 185 | + let replay = match keyed.clone() { | ||
| 186 | + Some(id) => payment_ledger::read(&mut *tx, &id).await?, | ||
| 187 | + None => None, | ||
| 188 | + }; | ||
| 189 | + if let Some(existing) = replay { | ||
| 181 | // A replay is answered from the stored line — but only if it is | 190 | // A replay is answered from the stored line — but only if it is |
| 182 | // the same money. The same key for a different amount or a | 191 | // the same money. The same key for a different amount or a |
| 183 | // different target is a client bug, and handing back the old | 192 | // different target is a client bug, and handing back the old |
| @@ -201,27 +210,29 @@ async fn against( | |||
| 201 | // bursar money had arrived when none ever did. The reversal's | 210 | // bursar money had arrived when none ever did. The reversal's |
| 202 | // id is derived from its target's, so telling the two apart is | 211 | // id is derived from its target's, so telling the two apart is |
| 203 | // one read, taken only on the refusal path. | 212 | // one read, taken only on the refusal path. |
| 204 | - if let Some(reversed) = reversed | 213 | + if let Some(text) = reversed { |
| 205 | - && payment_ledger::read(&mut *tx, &PaymentLedgerId::for_reversal(&target.id)) | 214 | + let reversed_there = |
| 206 | - .await? | 215 | + payment_ledger::read(&mut *tx, &PaymentLedgerId::for_reversal(&target.id)) |
| 207 | - .is_some() | 216 | + .await? |
| 208 | - { | 217 | + .is_some(); |
| 209 | - return Err(AppError::Conflict(reversed)); | 218 | + if reversed_there { |
| 219 | + return Err(AppError::Conflict(text)); | ||
| 220 | + } | ||
| 210 | } | 221 | } |
| 211 | return Err(AppError::Conflict(over)); | 222 | return Err(AppError::Conflict(over)); |
| 212 | } | 223 | } |
| 213 | payment_ledger::append( | 224 | payment_ledger::append( |
| 214 | &mut *tx, | 225 | &mut *tx, |
| 215 | PaymentLedger { | 226 | PaymentLedger { |
| 216 | - id: keyed.unwrap_or_else(PaymentLedgerId::generate), | 227 | + id: keyed.clone().unwrap_or_else(PaymentLedgerId::generate), |
| 217 | student: target.student.clone(), | 228 | student: target.student.clone(), |
| 218 | kind, | 229 | kind, |
| 219 | amount_minor, | 230 | amount_minor, |
| 220 | - source: Some(target.id.key()), | 231 | + source: Some(target.id.key().to_string()), |
| 221 | due_at: None, | 232 | due_at: None, |
| 222 | - method, | 233 | + method: method.clone(), |
| 223 | - note, | 234 | + note: note.clone(), |
| 224 | - recorded_by: recorded_by.clone(), | 235 | + recorded_by, |
| 225 | created_at: Timestamp::now(), | 236 | created_at: Timestamp::now(), |
| 226 | }, | 237 | }, |
| 227 | ) | 238 | ) |
| @@ -262,7 +273,10 @@ pub async fn reversal( | |||
| 262 | } | 273 | } |
| 263 | .into()); | 274 | .into()); |
| 264 | } | 275 | } |
| 265 | - tx_with_retry(db, false, async |tx| { | 276 | + // Owned captures (`Send` rule of `tx_with_retry` closures). |
| 277 | + let line = line.clone(); | ||
| 278 | + let recorded_by = *recorded_by; | ||
| 279 | + tx_with_retry(db, false, async move |tx| { | ||
| 266 | payment_ledger::lock_for_cap(&mut *tx, line.get_id()).await?; | 280 | payment_ledger::lock_for_cap(&mut *tx, line.get_id()).await?; |
| 267 | payment_ledger::append( | 281 | payment_ledger::append( |
| 268 | &mut *tx, | 282 | &mut *tx, |
| @@ -271,11 +285,11 @@ pub async fn reversal( | |||
| 271 | student: line.student.clone(), | 285 | student: line.student.clone(), |
| 272 | kind: PaymentLedgerKind::Reversal, | 286 | kind: PaymentLedgerKind::Reversal, |
| 273 | amount_minor: line.amount_minor, | 287 | amount_minor: line.amount_minor, |
| 274 | - source: Some(line.id.key()), | 288 | + source: Some(line.id.key().to_string()), |
| 275 | due_at: None, | 289 | due_at: None, |
| 276 | method: None, | 290 | method: None, |
| 277 | - note, | 291 | + note: note.clone(), |
| 278 | - recorded_by: recorded_by.clone(), | 292 | + recorded_by, |
| 279 | created_at: Timestamp::now(), | 293 | created_at: Timestamp::now(), |
| 280 | }, | 294 | }, |
| 281 | ) | 295 | ) |
src/service/settings.rsmodified+7 -7
| @@ -172,7 +172,7 @@ pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result<Settings, App | |||
| 172 | // Guards + save, one transaction. The removal refusals are the same | 172 | // Guards + save, one transaction. The removal refusals are the same |
| 173 | // 409s as ever; a stale save is the `STALE_SAVE` marker, answered by | 173 | // 409s as ever; a stale save is the `STALE_SAVE` marker, answered by |
| 174 | // another loop turn below; everything else surfaces. | 174 | // another loop turn below; everything else surfaces. |
| 175 | - let attempted = tx_with_retry(db, false, async |tx| { | 175 | + let attempted = tx_with_retry(db, false, async move |tx| { |
| 176 | // A name leaves a list by being *retired* on its reference | 176 | // A name leaves a list by being *retired* on its reference |
| 177 | // counter — one row-locked switch, which lands only while | 177 | // counter — one row-locked switch, which lands only while |
| 178 | // nothing references the name and refuses every claim from that | 178 | // nothing references the name and refuses every claim from that |
| @@ -239,7 +239,7 @@ async fn retire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppE | |||
| 239 | r#"SELECT retired AS "retired!: bool" FROM kind_ref WHERE name = $1 FOR UPDATE"#, | 239 | r#"SELECT retired AS "retired!: bool" FROM kind_ref WHERE name = $1 FOR UPDATE"#, |
| 240 | name | 240 | name |
| 241 | ) | 241 | ) |
| 242 | - .fetch_optional(tx) | 242 | + .fetch_optional(&mut *tx) |
| 243 | .await? | 243 | .await? |
| 244 | .map(|row| row.retired) | 244 | .map(|row| row.retired) |
| 245 | .unwrap_or(false); | 245 | .unwrap_or(false); |
| @@ -250,7 +250,7 @@ async fn retire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppE | |||
| 250 | RETURNING 1 AS "landed!: i64""#, | 250 | RETURNING 1 AS "landed!: i64""#, |
| 251 | name | 251 | name |
| 252 | ) | 252 | ) |
| 253 | - .fetch_optional(tx) | 253 | + .fetch_optional(&mut *tx) |
| 254 | .await? | 254 | .await? |
| 255 | .is_some(); | 255 | .is_some(); |
| 256 | match (landed, was) { | 256 | match (landed, was) { |
| @@ -270,7 +270,7 @@ async fn retire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppE | |||
| 270 | r#"SELECT retired AS "retired!: bool" FROM slot_ref WHERE name = $1 FOR UPDATE"#, | 270 | r#"SELECT retired AS "retired!: bool" FROM slot_ref WHERE name = $1 FOR UPDATE"#, |
| 271 | name | 271 | name |
| 272 | ) | 272 | ) |
| 273 | - .fetch_optional(tx) | 273 | + .fetch_optional(&mut *tx) |
| 274 | .await? | 274 | .await? |
| 275 | .map(|row| row.retired) | 275 | .map(|row| row.retired) |
| 276 | .unwrap_or(false); | 276 | .unwrap_or(false); |
| @@ -281,7 +281,7 @@ async fn retire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppE | |||
| 281 | RETURNING 1 AS "landed!: i64""#, | 281 | RETURNING 1 AS "landed!: i64""#, |
| 282 | name | 282 | name |
| 283 | ) | 283 | ) |
| 284 | - .fetch_optional(tx) | 284 | + .fetch_optional(&mut *tx) |
| 285 | .await? | 285 | .await? |
| 286 | .is_some(); | 286 | .is_some(); |
| 287 | match (landed, was) { | 287 | match (landed, was) { |
| @@ -305,7 +305,7 @@ async fn unretire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), Ap | |||
| 305 | RETURNING 1 AS "landed!: i64""#, | 305 | RETURNING 1 AS "landed!: i64""#, |
| 306 | name | 306 | name |
| 307 | ) | 307 | ) |
| 308 | - .fetch_optional(tx) | 308 | + .fetch_optional(&mut *tx) |
| 309 | .await?; | 309 | .await?; |
| 310 | Ok(()) | 310 | Ok(()) |
| 311 | } | 311 | } |
| @@ -319,7 +319,7 @@ async fn unretire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), Ap | |||
| 319 | RETURNING 1 AS "landed!: i64""#, | 319 | RETURNING 1 AS "landed!: i64""#, |
| 320 | name | 320 | name |
| 321 | ) | 321 | ) |
| 322 | - .fetch_optional(tx) | 322 | + .fetch_optional(&mut *tx) |
| 323 | .await?; | 323 | .await?; |
| 324 | Ok(()) | 324 | Ok(()) |
| 325 | } | 325 | } |
src/web/appointments.rsmodified+1 -1
| @@ -439,7 +439,7 @@ async fn list_slots( | |||
| 439 | .filter(|teacher| teacher.get_role().at_least(Role::Teacher)) | 439 | .filter(|teacher| teacher.get_role().at_least(Role::Teacher)) |
| 440 | .map(|teacher| (teacher.get_id().key().to_string(), PersonRef::new(teacher))) | 440 | .map(|teacher| (teacher.get_id().key().to_string(), PersonRef::new(teacher))) |
| 441 | .collect(); | 441 | .collect(); |
| 442 | - slots.retain(|slot| people.contains_key(slot.get_teacher().key())); | 442 | + slots.retain(|slot| people.contains_key(slot.get_teacher().key().as_str())); |
| 443 | (slots, people) | 443 | (slots, people) |
| 444 | }; | 444 | }; |
| 445 | let total = slots.len() as i64; | 445 | let total = slots.len() as i64; |
src/web/attendance.rsmodified+3 -3
| @@ -119,7 +119,7 @@ async fn build_report( | |||
| 119 | } | 119 | } |
| 120 | 120 | ||
| 121 | let courses = crate::service::course::list_by_ids(db, &course_ids).await?; | 121 | let courses = crate::service::course::list_by_ids(db, &course_ids).await?; |
| 122 | - let course_by_key: HashMap<&str, &Course> = | 122 | + let course_by_key: HashMap<String, &Course> = |
| 123 | courses.iter().map(|c| (c.get_id().key(), c)).collect(); | 123 | courses.iter().map(|c| (c.get_id().key(), c)).collect(); |
| 124 | let people = person_map(courses.iter().flat_map(course_people), db).await?; | 124 | let people = person_map(courses.iter().flat_map(course_people), db).await?; |
| 125 | 125 | ||
| @@ -128,13 +128,13 @@ async fn build_report( | |||
| 128 | for course_id in &course_ids { | 128 | for course_id in &course_ids { |
| 129 | // A row whose course is gone cannot happen given the delete cascade — | 129 | // A row whose course is gone cannot happen given the delete cascade — |
| 130 | // skip defensively rather than fabricate a course block. | 130 | // skip defensively rather than fabricate a course block. |
| 131 | - let Some(course) = course_by_key.get(course_id.key()) else { | 131 | + let Some(course) = course_by_key.get(course_id.key().as_str()) else { |
| 132 | continue; | 132 | continue; |
| 133 | }; | 133 | }; |
| 134 | if viewer.is_some_and(|viewer| !can_manage_course(course, viewer)) { | 134 | if viewer.is_some_and(|viewer| !can_manage_course(course, viewer)) { |
| 135 | continue; | 135 | continue; |
| 136 | } | 136 | } |
| 137 | - let rows = &by_course[course_id.key()]; | 137 | + let rows = &by_course[course_id.key().as_str()]; |
| 138 | visible_rows.extend(rows.iter().copied()); | 138 | visible_rows.extend(rows.iter().copied()); |
| 139 | blocks.push(CourseAttendance { | 139 | blocks.push(CourseAttendance { |
| 140 | course: CourseResponse::new(course, &people), | 140 | course: CourseResponse::new(course, &people), |
src/web/bank_questions.rsmodified+7 -5
| @@ -560,13 +560,13 @@ async fn list_questions( | |||
| 560 | let items = questions | 560 | let items = questions |
| 561 | .iter() | 561 | .iter() |
| 562 | .map(|question| { | 562 | .map(|question| { |
| 563 | - let images = buckets.get(question.get_id().key()).unwrap_or(&empty); | 563 | + let images = buckets.get(&question.get_id().key()).unwrap_or(&empty); |
| 564 | let subject_name = question | 564 | let subject_name = question |
| 565 | .get_subject() | 565 | .get_subject() |
| 566 | - .and_then(|subject| subject_names.get(subject.key()).cloned()) | 566 | + .and_then(|subject| subject_names.get(&subject.key()).cloned()) |
| 567 | .unwrap_or_default(); | 567 | .unwrap_or_default(); |
| 568 | let owner_name = people | 568 | let owner_name = people |
| 569 | - .get(question.get_owner().key()) | 569 | + .get(&question.get_owner().key()) |
| 570 | .map(|person| { | 570 | .map(|person| { |
| 571 | person | 571 | person |
| 572 | .display_name | 572 | .display_name |
| @@ -574,7 +574,7 @@ async fn list_questions( | |||
| 574 | .unwrap_or_else(|| person.username.clone()) | 574 | .unwrap_or_else(|| person.username.clone()) |
| 575 | }) | 575 | }) |
| 576 | .unwrap_or_default(); | 576 | .unwrap_or_default(); |
| 577 | - let used_count = used.get(question.get_id().key()).copied().unwrap_or(0); | 577 | + let used_count = used.get(&question.get_id().key()).copied().unwrap_or(0); |
| 578 | BankQuestionResponse::with_names(question, images, subject_name, owner_name, used_count) | 578 | BankQuestionResponse::with_names(question, images, subject_name, owner_name, used_count) |
| 579 | }) | 579 | }) |
| 580 | .collect(); | 580 | .collect(); |
| @@ -651,7 +651,9 @@ async fn update_question( | |||
| 651 | owned_question(&st, &user, &bid).await?; | 651 | owned_question(&st, &user, &bid).await?; |
| 652 | let patch = bank_question::BankQuestionPatch { | 652 | let patch = bank_question::BankQuestionPatch { |
| 653 | subject: match req.subject_id { | 653 | subject: match req.subject_id { |
| 654 | - Some(ref subject_id) => Some(crate::service::subject::must_exist(&st.db, subject_id).await?), | 654 | + Some(ref subject_id) => { |
| 655 | + Some(crate::service::subject::must_exist(&st.db, subject_id).await?) | ||
| 656 | + } | ||
| 655 | None => None, | 657 | None => None, |
| 656 | }, | 658 | }, |
| 657 | text: match req.text { | 659 | text: match req.text { |
src/web/board_ws.rsmodified+6 -6
| @@ -152,8 +152,8 @@ async fn room(mut socket: WebSocket, st: AppState, slug: Slug, board: BoardId, u | |||
| 152 | // lands between a replay's read and this subscribe would otherwise be lost | 152 | // lands between a replay's read and this subscribe would otherwise be lost |
| 153 | // outright, whereas one delivered twice is deduplicated by its id at the | 153 | // outright, whereas one delivered twice is deduplicated by its id at the |
| 154 | // client (which a resync forces anyway). | 154 | // client (which a resync forces anyway). |
| 155 | - let _connected = room::Connected::open(&st.metrics, "board", slug.as_str(), board.key()); | 155 | + let _connected = room::Connected::open(&st.metrics, "board", slug.as_str(), &board.key()); |
| 156 | - let mut feed = st.board_hub.subscribe(&slug, board.key()); | 156 | + let mut feed = st.board_hub.subscribe(&slug, &board.key()); |
| 157 | // The ids this socket drew, in the order they were published. The hub has | 157 | // The ids this socket drew, in the order they were published. The hub has |
| 158 | // no idea who is listening, so the room filters its own strokes back out | 158 | // no idea who is listening, so the room filters its own strokes back out |
| 159 | // here — a client that had to ignore the echo of every mark it just drew | 159 | // 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 | |||
| 193 | } | 193 | } |
| 194 | } | 194 | } |
| 195 | room::close(&mut socket).await; | 195 | room::close(&mut socket).await; |
| 196 | - st.board_hub.leave(&slug, board.key()); | 196 | + st.board_hub.leave(&slug, &board.key()); |
| 197 | } | 197 | } |
| 198 | 198 | ||
| 199 | type Step = Result<(), RoomClosed>; | 199 | type Step = Result<(), RoomClosed>; |
| @@ -475,7 +475,7 @@ async fn handle_message( | |||
| 475 | fanned["type"] = json!("stroke"); | 475 | fanned["type"] = json!("stroke"); |
| 476 | fanned["epoch"] = json!(stroke.get_epoch()); | 476 | fanned["epoch"] = json!(stroke.get_epoch()); |
| 477 | mine.push_back(stroke.get_id().key().to_string()); | 477 | mine.push_back(stroke.get_id().key().to_string()); |
| 478 | - st.board_hub.publish(slug, board.key(), fanned.to_string()); | 478 | + st.board_hub.publish(slug, &board.key(), fanned.to_string()); |
| 479 | let mut frame = json!({ "type": "saved", "id": stroke.get_id().key() }); | 479 | let mut frame = json!({ "type": "saved", "id": stroke.get_id().key() }); |
| 480 | with_client_seq(&mut frame, client_seq); | 480 | with_client_seq(&mut frame, client_seq); |
| 481 | send(socket, frame).await | 481 | send(socket, frame).await |
| @@ -499,7 +499,7 @@ async fn handle_message( | |||
| 499 | Ok(marker) => { | 499 | Ok(marker) => { |
| 500 | st.board_hub.publish( | 500 | st.board_hub.publish( |
| 501 | slug, | 501 | slug, |
| 502 | - board.key(), | 502 | + &board.key(), |
| 503 | json!({ | 503 | json!({ |
| 504 | "type": "cleared", | 504 | "type": "cleared", |
| 505 | "epoch": marker.get_epoch() + 1, | 505 | "epoch": marker.get_epoch() + 1, |
| @@ -518,7 +518,7 @@ async fn handle_message( | |||
| 518 | Ok(_) => { | 518 | Ok(_) => { |
| 519 | st.board_hub.publish( | 519 | st.board_hub.publish( |
| 520 | slug, | 520 | slug, |
| 521 | - board.key(), | 521 | + &board.key(), |
| 522 | json!({ "type": "locked", "locked": locked, "by": user.key() }).to_string(), | 522 | json!({ "type": "locked", "locked": locked, "by": user.key() }).to_string(), |
| 523 | ); | 523 | ); |
| 524 | Ok(()) | 524 | Ok(()) |
src/web/boards.rsmodified+2 -2
| @@ -63,7 +63,7 @@ pub fn routes() -> OpenApiRouter<AppState> { | |||
| 63 | /// Push one frame to whoever is in the room right now. An empty room is the | 63 | /// Push one frame to whoever is in the room right now. An empty room is the |
| 64 | /// normal case, not a failure. | 64 | /// normal case, not a failure. |
| 65 | fn fan_out(st: &AppState, slug: &Slug, board: &BoardId, frame: serde_json::Value) { | 65 | fn fan_out(st: &AppState, slug: &Slug, board: &BoardId, frame: serde_json::Value) { |
| 66 | - st.board_hub.publish(slug, board.key(), frame.to_string()); | 66 | + st.board_hub.publish(slug, &board.key(), frame.to_string()); |
| 67 | } | 67 | } |
| 68 | 68 | ||
| 69 | /// The roster frame every path that changes the invite list must publish. A | 69 | /// The roster frame every path that changes the invite list must publish. A |
| @@ -677,7 +677,7 @@ impl InviteSource { | |||
| 677 | field: "event", | 677 | field: "event", |
| 678 | reason: "no such event", | 678 | reason: "no such event", |
| 679 | }))?; | 679 | }))?; |
| 680 | - crate::service::event::members(db, event.get_audience(), event.get_id()).await | 680 | + crate::service::event::members(db, &event).await |
| 681 | } | 681 | } |
| 682 | } | 682 | } |
| 683 | } | 683 | } |
src/web/chatbot.rsmodified+1 -1
| @@ -386,7 +386,7 @@ async fn send_message( | |||
| 386 | ) -> Result<Response, AppError> { | 386 | ) -> Result<Response, AppError> { |
| 387 | // Charged first: a rejected turn must cost nothing and leave no row. | 387 | // Charged first: a rejected turn must cost nothing and leave no row. |
| 388 | st.chatbot_limit | 388 | st.chatbot_limit |
| 389 | - .enforce_user(&scoped_key(&slug, user.get_id().key()))?; | 389 | + .enforce_user(&scoped_key(&slug, user.get_id().key().as_str()))?; |
| 390 | 390 | ||
| 391 | let thread = own_thread(&id, user.get_id(), &st.db).await?; | 391 | let thread = own_thread(&id, user.get_id(), &st.db).await?; |
| 392 | let settings = service::settings::load(&st.db).await?; | 392 | let settings = service::settings::load(&st.db).await?; |
src/web/classes.rsmodified+2 -2
| @@ -301,7 +301,7 @@ async fn classes_page( | |||
| 301 | db: &Database, | 301 | db: &Database, |
| 302 | ) -> Result<Page<ClassResponse>, AppError> { | 302 | ) -> Result<Page<ClassResponse>, AppError> { |
| 303 | let classes = class_group::list_by_ids(db, ids).await?; | 303 | let classes = class_group::list_by_ids(db, ids).await?; |
| 304 | - let by_id: std::collections::HashMap<&str, &ClassGroup> = classes | 304 | + let by_id: std::collections::HashMap<String, &ClassGroup> = classes |
| 305 | .iter() | 305 | .iter() |
| 306 | .map(|class| (class.get_id().key(), class)) | 306 | .map(|class| (class.get_id().key(), class)) |
| 307 | .collect(); | 307 | .collect(); |
| @@ -314,7 +314,7 @@ async fn classes_page( | |||
| 314 | .await?; | 314 | .await?; |
| 315 | let items = ids | 315 | let items = ids |
| 316 | .iter() | 316 | .iter() |
| 317 | - .filter_map(|id| by_id.get(id.key())) | 317 | + .filter_map(|id| by_id.get(id.key().as_str())) |
| 318 | .map(|class| ClassResponse::new(class, &people, with_creator)) | 318 | .map(|class| ClassResponse::new(class, &people, with_creator)) |
| 319 | .collect(); | 319 | .collect(); |
| 320 | Ok(Page::new(items, total, limit, offset)) | 320 | Ok(Page::new(items, total, limit, offset)) |
src/web/course_notes.rsmodified+4 -4
| @@ -313,7 +313,7 @@ async fn delete_one( | |||
| 313 | // pre-read list — an upload that landed in between is in the cascade too. | 313 | // pre-read list — an upload that landed in between is in the cascade too. |
| 314 | let (_, files) = service::course_note::delete(&st.db, note).await?; | 314 | let (_, files) = service::course_note::delete(&st.db, note).await?; |
| 315 | for file in &files { | 315 | for file in &files { |
| 316 | - remove_blob(&st.files_path, file.get_id().key()).await; | 316 | + remove_blob(&st.files_path, &file.get_id().key()).await; |
| 317 | } | 317 | } |
| 318 | Ok(StatusCode::NO_CONTENT) | 318 | Ok(StatusCode::NO_CONTENT) |
| 319 | } | 319 | } |
| @@ -392,7 +392,7 @@ async fn upload_file( | |||
| 392 | // Blob first, row second — a stored row always points at a real blob. If | 392 | // Blob first, row second — a stored row always points at a real blob. If |
| 393 | // the row insert fails, take the fresh blob back out. | 393 | // the row insert fails, take the fresh blob back out. |
| 394 | let file = CourseNoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64); | 394 | let file = CourseNoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64); |
| 395 | - let path = blob_path(&st.files_path, file.get_id().key()); | 395 | + let path = blob_path(&st.files_path, &file.get_id().key()); |
| 396 | crate::web::ensure_files_dir(&st.files_path).await?; | 396 | crate::web::ensure_files_dir(&st.files_path).await?; |
| 397 | tokio::fs::write(&path, &upload.data) | 397 | tokio::fs::write(&path, &upload.data) |
| 398 | .await | 398 | .await |
| @@ -484,7 +484,7 @@ async fn download_file( | |||
| 484 | ) | 484 | ) |
| 485 | .await? | 485 | .await? |
| 486 | .ok_or(AppError::NotFound)?; | 486 | .ok_or(AppError::NotFound)?; |
| 487 | - let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key())) | 487 | + let bytes = tokio::fs::read(blob_path(&st.files_path, &file.get_id().key())) |
| 488 | .await | 488 | .await |
| 489 | .map_err(|err| { | 489 | .map_err(|err| { |
| 490 | // The row exists but its blob doesn't — that's server-side damage | 490 | // The row exists but its blob doesn't — that's server-side damage |
| @@ -553,7 +553,7 @@ async fn delete_file( | |||
| 553 | // blob; the re-index rebuilds from what is left, if a service is connected. | 553 | // blob; the re-index rebuilds from what is left, if a service is connected. |
| 554 | service::rag_output::delete_with_source(&st.db, file.get_id()).await?; | 554 | service::rag_output::delete_with_source(&st.db, file.get_id()).await?; |
| 555 | let file = service::course_note_file::delete(&st.db, file).await?; | 555 | let file = service::course_note_file::delete(&st.db, file).await?; |
| 556 | - remove_blob(&st.files_path, file.get_id().key()).await; | 556 | + remove_blob(&st.files_path, &file.get_id().key()).await; |
| 557 | spawn_index(&st, &tenant, note); | 557 | spawn_index(&st, &tenant, note); |
| 558 | Ok(StatusCode::NO_CONTENT) | 558 | Ok(StatusCode::NO_CONTENT) |
| 559 | } | 559 | } |
src/web/courses.rsmodified+1 -1
| @@ -273,7 +273,7 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Co | |||
| 273 | } | 273 | } |
| 274 | } | 274 | } |
| 275 | // Both sources come newest-first; re-sort so the merged list is too. | 275 | // Both sources come newest-first; re-sort so the merged list is too. |
| 276 | - courses.sort_by(|a, b| b.get_id().key().cmp(a.get_id().key())); | 276 | + courses.sort_by(|a, b| b.get_id().key().cmp(&a.get_id().key())); |
| 277 | Ok(courses) | 277 | Ok(courses) |
| 278 | } | 278 | } |
| 279 | 279 | ||
src/web/events.rsmodified+5 -5
| @@ -37,7 +37,7 @@ impl Scheduled for Event { | |||
| 37 | self.get_ends_at().map(|at| at.as_millis()) | 37 | self.get_ends_at().map(|at| at.as_millis()) |
| 38 | } | 38 | } |
| 39 | 39 | ||
| 40 | - fn order_key(&self) -> &str { | 40 | + fn order_key(&self) -> String { |
| 41 | self.get_id().key() | 41 | self.get_id().key() |
| 42 | } | 42 | } |
| 43 | } | 43 | } |
| @@ -723,9 +723,9 @@ async fn roster( | |||
| 723 | 723 | ||
| 724 | let mut members = service::event::members(&st.db, &event).await?; | 724 | let mut members = service::event::members(&st.db, &event).await?; |
| 725 | // ULID keys sort by creation instant — a stable order keeps pages coherent. | 725 | // ULID keys sort by creation instant — a stable order keeps pages coherent. |
| 726 | - members.sort_by(|a, b| a.key().cmp(b.key())); | 726 | + members.sort_by(|a, b| a.key().cmp(&b.key())); |
| 727 | let (marks, _) = crate::service::attendance::list_for_event(&st.db, &event_id, None, 0).await?; | 727 | let (marks, _) = crate::service::attendance::list_for_event(&st.db, &event_id, None, 0).await?; |
| 728 | - let by_user: HashMap<&str, &Attendance> = marks | 728 | + let by_user: HashMap<String, &Attendance> = marks |
| 729 | .iter() | 729 | .iter() |
| 730 | .map(|attendance| (attendance.get_user().key(), attendance)) | 730 | .map(|attendance| (attendance.get_user().key(), attendance)) |
| 731 | .collect(); | 731 | .collect(); |
| @@ -736,14 +736,14 @@ async fn roster( | |||
| 736 | let window = paginate(&members, limit, offset); | 736 | let window = paginate(&members, limit, offset); |
| 737 | let ids = window.iter().cloned().chain(window.iter().filter_map(|m| { | 737 | let ids = window.iter().cloned().chain(window.iter().filter_map(|m| { |
| 738 | by_user | 738 | by_user |
| 739 | - .get(m.key()) | 739 | + .get(m.key().as_str()) |
| 740 | .map(|attendance| attendance.get_marked_by().clone()) | 740 | .map(|attendance| attendance.get_marked_by().clone()) |
| 741 | })); | 741 | })); |
| 742 | let people = person_map(ids, &st.db).await?; | 742 | let people = person_map(ids, &st.db).await?; |
| 743 | let items = window | 743 | let items = window |
| 744 | .iter() | 744 | .iter() |
| 745 | .map(|member| { | 745 | .map(|member| { |
| 746 | - let mark = by_user.get(member.key()); | 746 | + let mark = by_user.get(member.key().as_str()); |
| 747 | RosterEntry { | 747 | RosterEntry { |
| 748 | user: PersonRef::resolve(&people, member), | 748 | user: PersonRef::resolve(&people, member), |
| 749 | status: mark.map(|attendance| attendance.get_status().as_str().to_string()), | 749 | status: mark.map(|attendance| attendance.get_status().as_str().to_string()), |
src/web/exam_ws.rsmodified+9 -4
| @@ -166,7 +166,12 @@ async fn room( | |||
| 166 | let attempt_id = attempt.get_id().clone(); | 166 | let attempt_id = attempt.get_id().clone(); |
| 167 | // The exam, not the attempt: an attempt names one student, and telemetry | 167 | // The exam, not the attempt: an attempt names one student, and telemetry |
| 168 | // never names a person. | 168 | // never names a person. |
| 169 | - let _connected = room::Connected::open(&st.metrics, "exam_room", slug.as_str(), exam_id.key()); | 169 | + let _connected = room::Connected::open( |
| 170 | + &st.metrics, | ||
| 171 | + "exam_room", | ||
| 172 | + slug.as_str(), | ||
| 173 | + exam_id.key().as_str(), | ||
| 174 | + ); | ||
| 170 | // Join: this socket counts as presence in the sitting's room until it | 175 | // Join: this socket counts as presence in the sitting's room until it |
| 171 | // closes, and joining clears the walk-out marker — the clear is one | 176 | // closes, and joining clears the walk-out marker — the clear is one |
| 172 | // unconditional statement against the sitting's row, so it always | 177 | // unconditional statement against the sitting's row, so it always |
| @@ -174,7 +179,7 @@ async fn room( | |||
| 174 | // predate a stamp that raced the upgrade; clearing regardless is what | 179 | // predate a stamp that raced the upgrade; clearing regardless is what |
| 175 | // keeps a reconnecting student unmarked. Best-effort — a failed clear | 180 | // keeps a reconnecting student unmarked. Best-effort — a failed clear |
| 176 | // leaves the stamp for the next join or the teacher's door. | 181 | // leaves the stamp for the next join or the teacher's door. |
| 177 | - st.exam_presence.enter(&slug, attempt_id.key()); | 182 | + st.exam_presence.enter(&slug, attempt_id.key().as_str()); |
| 178 | if let Err(err) = set_left(&st.db, attempt, None).await { | 183 | if let Err(err) = set_left(&st.db, attempt, None).await { |
| 179 | tracing::warn!("exam room could not clear left_at on join: {err}"); | 184 | tracing::warn!("exam room could not clear left_at on join: {err}"); |
| 180 | } | 185 | } |
| @@ -211,7 +216,7 @@ async fn room( | |||
| 211 | // stamped. With `allow_rejoin` off this is what locks further | 216 | // stamped. With `allow_rejoin` off this is what locks further |
| 212 | // answering. Best-effort: a failed stamp only means it goes | 217 | // answering. Best-effort: a failed stamp only means it goes |
| 213 | // unrecorded. | 218 | // unrecorded. |
| 214 | - if st.exam_presence.leave(&slug, attempt_id.key()) { | 219 | + if st.exam_presence.leave(&slug, attempt_id.key().as_str()) { |
| 215 | crate::db::exam_attempt::stamp_left_if_running(&st.db, &attempt_id, Timestamp::now()) | 220 | crate::db::exam_attempt::stamp_left_if_running(&st.db, &attempt_id, Timestamp::now()) |
| 216 | .await | 221 | .await |
| 217 | .unwrap_or_else(|err| { | 222 | .unwrap_or_else(|err| { |
| @@ -233,7 +238,7 @@ async fn writable_room_attempt( | |||
| 233 | db: &Database, | 238 | db: &Database, |
| 234 | ) -> Result<ExamAttempt, AppError> { | 239 | ) -> Result<ExamAttempt, AppError> { |
| 235 | let attempt = writable_attempt(exam, user, db).await?; | 240 | let attempt = writable_attempt(exam, user, db).await?; |
| 236 | - if attempt.get_id() != attempt_id { | 241 | + if &attempt.get_id() != attempt_id { |
| 237 | return Err(AppError::Conflict( | 242 | return Err(AppError::Conflict( |
| 238 | "this room's sitting is over — reconnect to continue in the new attempt", | 243 | "this room's sitting is over — reconnect to continue in the new attempt", |
| 239 | )); | 244 | )); |
src/web/exams/attempts.rsmodified+12 -12
| @@ -386,7 +386,7 @@ pub(crate) async fn live_snapshot( | |||
| 386 | .iter() | 386 | .iter() |
| 387 | .map(|enrollment| { | 387 | .map(|enrollment| { |
| 388 | let key = enrollment.get_user().key(); | 388 | let key = enrollment.get_user().key(); |
| 389 | - let attempt = attempts.get(key); | 389 | + let attempt = attempts.get(&key); |
| 390 | let status = attempt.map(|a| a.status(exam, now)); | 390 | let status = attempt.map(|a| a.status(exam, now)); |
| 391 | let deadline = attempt.and_then(|a| a.deadline(exam)); | 391 | let deadline = attempt.and_then(|a| a.deadline(exam)); |
| 392 | LiveStudentResponse { | 392 | LiveStudentResponse { |
| @@ -398,7 +398,7 @@ pub(crate) async fn live_snapshot( | |||
| 398 | } | 398 | } |
| 399 | .to_string(), | 399 | .to_string(), |
| 400 | attempt: attempt.map(ExamAttempt::get_seq), | 400 | attempt: attempt.map(ExamAttempt::get_seq), |
| 401 | - attempts_used: used.get(key).copied().unwrap_or(0), | 401 | + attempts_used: used.get(&key).copied().unwrap_or(0), |
| 402 | started_at: attempt.map(|a| a.get_started_at().as_millis()), | 402 | started_at: attempt.map(|a| a.get_started_at().as_millis()), |
| 403 | finished_at: attempt | 403 | finished_at: attempt |
| 404 | .and_then(|a| a.get_finished_at()) | 404 | .and_then(|a| a.get_finished_at()) |
| @@ -408,9 +408,9 @@ pub(crate) async fn live_snapshot( | |||
| 408 | remaining_ms: (status == Some(AttemptStatus::InProgress)) | 408 | remaining_ms: (status == Some(AttemptStatus::InProgress)) |
| 409 | .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0))) | 409 | .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0))) |
| 410 | .flatten(), | 410 | .flatten(), |
| 411 | - mark: marks.get(key).copied(), | 411 | + mark: marks.get(&key).copied(), |
| 412 | - answered: progress.get(key).map_or(0, |p| p.0), | 412 | + answered: progress.get(&key).map_or(0, |p| p.0), |
| 413 | - last_activity: progress.get(key).map(|p| p.1), | 413 | + last_activity: progress.get(&key).map(|p| p.1), |
| 414 | } | 414 | } |
| 415 | }) | 415 | }) |
| 416 | .collect(); | 416 | .collect(); |
| @@ -604,7 +604,7 @@ pub(crate) async fn attempt_questions( | |||
| 604 | .iter() | 604 | .iter() |
| 605 | .map(|question| { | 605 | .map(|question| { |
| 606 | let question_images = images | 606 | let question_images = images |
| 607 | - .get(question.get_id().key()) | 607 | + .get(question.get_id().key().as_str()) |
| 608 | .map_or(&[][..], Vec::as_slice); | 608 | .map_or(&[][..], Vec::as_slice); |
| 609 | AttemptQuestionResponse { | 609 | AttemptQuestionResponse { |
| 610 | id: question.get_id().key().to_string(), | 610 | id: question.get_id().key().to_string(), |
| @@ -615,11 +615,11 @@ pub(crate) async fn attempt_questions( | |||
| 615 | choices: ChoiceResponse::list(question.get_choices()), | 615 | choices: ChoiceResponse::list(question.get_choices()), |
| 616 | image: image_meta(question_images, None), | 616 | image: image_meta(question_images, None), |
| 617 | choice_images: choice_image_metas(question, question_images), | 617 | choice_images: choice_image_metas(question, question_images), |
| 618 | - answer: answers.get(question.get_id().key()).map(|answer| { | 618 | + answer: answers.get(question.get_id().key().as_str()).map(|answer| { |
| 619 | AnswerStateResponse::new( | 619 | AnswerStateResponse::new( |
| 620 | answer, | 620 | answer, |
| 621 | answer_images | 621 | answer_images |
| 622 | - .get(question.get_id().key()) | 622 | + .get(question.get_id().key().as_str()) |
| 623 | .map(ImageMetaResponse::from_answer), | 623 | .map(ImageMetaResponse::from_answer), |
| 624 | ) | 624 | ) |
| 625 | }), | 625 | }), |
| @@ -747,7 +747,7 @@ pub(crate) async fn answer_sheet( | |||
| 747 | ) -> Result<AttemptAnswersResponse, AppError> { | 747 | ) -> Result<AttemptAnswersResponse, AppError> { |
| 748 | let (mut questions, _) = | 748 | let (mut questions, _) = |
| 749 | crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0).await?; | 749 | crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0).await?; |
| 750 | - questions.retain(|question| !hidden.contains(question.get_id().key())); | 750 | + questions.retain(|question| !hidden.contains(question.get_id().key().as_str())); |
| 751 | let answers = | 751 | let answers = |
| 752 | crate::service::exam_answer::list_for_exam_user(db, exam.get_id(), target, seq).await?; | 752 | crate::service::exam_answer::list_for_exam_user(db, exam.get_id(), target, seq).await?; |
| 753 | let answer_images: HashMap<String, AnswerImage> = | 753 | let answer_images: HashMap<String, AnswerImage> = |
| @@ -756,7 +756,7 @@ pub(crate) async fn answer_sheet( | |||
| 756 | .into_iter() | 756 | .into_iter() |
| 757 | .map(|image| (image.get_question().key().to_string(), image)) | 757 | .map(|image| (image.get_question().key().to_string(), image)) |
| 758 | .collect(); | 758 | .collect(); |
| 759 | - let by_question: HashMap<&str, &ExamQuestion> = questions | 759 | + let by_question: HashMap<String, &ExamQuestion> = questions |
| 760 | .iter() | 760 | .iter() |
| 761 | .map(|question| (question.get_id().key(), question)) | 761 | .map(|question| (question.get_id().key(), question)) |
| 762 | .collect(); | 762 | .collect(); |
| @@ -773,10 +773,10 @@ pub(crate) async fn answer_sheet( | |||
| 773 | text: answer.get_text().map(|t| t.as_str().to_string()), | 773 | text: answer.get_text().map(|t| t.as_str().to_string()), |
| 774 | updated_at: answer.get_updated_at().as_millis(), | 774 | updated_at: answer.get_updated_at().as_millis(), |
| 775 | is_correct: by_question | 775 | is_correct: by_question |
| 776 | - .get(answer.get_question().key()) | 776 | + .get(answer.get_question().key().as_str()) |
| 777 | .and_then(|question| answer.is_correct(question)), | 777 | .and_then(|question| answer.is_correct(question)), |
| 778 | answer_image: answer_images | 778 | answer_image: answer_images |
| 779 | - .get(answer.get_question().key()) | 779 | + .get(answer.get_question().key().as_str()) |
| 780 | .map(ImageMetaResponse::from_answer), | 780 | .map(ImageMetaResponse::from_answer), |
| 781 | }) | 781 | }) |
| 782 | .collect(), | 782 | .collect(), |
src/web/exams/mod.rsmodified+2 -2
| @@ -59,7 +59,7 @@ impl Scheduled for Exam { | |||
| 59 | self.get_ends_at().map(|at| at.as_millis()) | 59 | self.get_ends_at().map(|at| at.as_millis()) |
| 60 | } | 60 | } |
| 61 | 61 | ||
| 62 | - fn order_key(&self) -> &str { | 62 | + fn order_key(&self) -> String { |
| 63 | self.get_id().key() | 63 | self.get_id().key() |
| 64 | } | 64 | } |
| 65 | } | 65 | } |
| @@ -268,7 +268,7 @@ async fn list_exams( | |||
| 268 | let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect(); | 268 | let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect(); |
| 269 | // Drafts show only where the caller manages the course (as its | 269 | // Drafts show only where the caller manages the course (as its |
| 270 | // creator — the manager+ path above already saw everything). | 270 | // creator — the manager+ path above already saw everything). |
| 271 | - let managed: Vec<&str> = courses | 271 | + let managed: Vec<String> = courses |
| 272 | .iter() | 272 | .iter() |
| 273 | .filter(|c| can_manage_course(c, &user)) | 273 | .filter(|c| can_manage_course(c, &user)) |
| 274 | .map(|c| c.get_id().key()) | 274 | .map(|c| c.get_id().key()) |
src/web/exams/questions.rsmodified+2 -2
| @@ -261,10 +261,10 @@ pub(crate) async fn question_page( | |||
| 261 | let mut item = QuestionResponse::new( | 261 | let mut item = QuestionResponse::new( |
| 262 | question, | 262 | question, |
| 263 | images | 263 | images |
| 264 | - .get(question.get_id().key()) | 264 | + .get(question.get_id().key().as_str()) |
| 265 | .map_or(&[][..], Vec::as_slice), | 265 | .map_or(&[][..], Vec::as_slice), |
| 266 | ); | 266 | ); |
| 267 | - if hidden.contains(question.get_id().key()) { | 267 | + if hidden.contains(question.get_id().key().as_str()) { |
| 268 | item.correct = None; | 268 | item.correct = None; |
| 269 | } | 269 | } |
| 270 | item | 270 | item |
src/web/marks.rsmodified+2 -2
| @@ -108,7 +108,7 @@ async fn build_report( | |||
| 108 | let mut blocks = Vec::with_capacity(courses.len()); | 108 | let mut blocks = Vec::with_capacity(courses.len()); |
| 109 | for course in &courses { | 109 | for course in &courses { |
| 110 | let exams = crate::service::exam::list_for_course(db, course.get_id()).await?; | 110 | let exams = crate::service::exam::list_for_course(db, course.get_id()).await?; |
| 111 | - let by_key: HashMap<&str, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect(); | 111 | + let by_key: HashMap<String, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect(); |
| 112 | 112 | ||
| 113 | let results = | 113 | let results = |
| 114 | crate::service::exam_result::list_for_user_in_course(db, course.get_id(), user).await?; | 114 | crate::service::exam_result::list_for_user_in_course(db, course.get_id(), user).await?; |
| @@ -117,7 +117,7 @@ async fn build_report( | |||
| 117 | for result in &results { | 117 | for result in &results { |
| 118 | // A result whose exam is gone cannot happen given the delete | 118 | // A result whose exam is gone cannot happen given the delete |
| 119 | // cascade — skip defensively rather than corrupt the average. | 119 | // cascade — skip defensively rather than corrupt the average. |
| 120 | - let Some(exam) = by_key.get(result.get_exam().key()) else { | 120 | + let Some(exam) = by_key.get(result.get_exam().key().as_str()) else { |
| 121 | continue; | 121 | continue; |
| 122 | }; | 122 | }; |
| 123 | // The kind's current settings weight; an exam keeps a retired | 123 | // The kind's current settings weight; an exam keeps a retired |
src/web/meals.rsmodified+5 -7
| @@ -20,7 +20,7 @@ use utoipa_axum::routes; | |||
| 20 | 20 | ||
| 21 | use crate::database::Database; | 21 | use crate::database::Database; |
| 22 | use crate::domain::dietary_profile::{DietaryNote, DietaryTags, conflicts}; | 22 | use crate::domain::dietary_profile::{DietaryNote, DietaryTags, conflicts}; |
| 23 | -use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; | 23 | +use crate::domain::meal_attendance::{MealAttendance, MealAttendanceId, MealAttendanceStatus}; |
| 24 | use crate::domain::meal_booking::{MealBooking, MealBookingId, MealCutoff}; | 24 | use crate::domain::meal_booking::{MealBooking, MealBookingId, MealCutoff}; |
| 25 | use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger}; | 25 | use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger}; |
| 26 | use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, validate_capacity}; | 26 | use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, validate_capacity}; |
| @@ -726,7 +726,7 @@ struct BookingResponse { | |||
| 726 | impl BookingResponse { | 726 | impl BookingResponse { |
| 727 | fn new(booking: &MealBooking, people: &std::collections::HashMap<String, PersonRef>) -> Self { | 727 | fn new(booking: &MealBooking, people: &std::collections::HashMap<String, PersonRef>) -> Self { |
| 728 | Self { | 728 | Self { |
| 729 | - id: booking.get_id().key().to_string(), | 729 | + id: booking.id().key(), |
| 730 | menu_id: booking.get_menu().key().to_string(), | 730 | menu_id: booking.get_menu().key().to_string(), |
| 731 | student: PersonRef::resolve(people, booking.get_student()), | 731 | student: PersonRef::resolve(people, booking.get_student()), |
| 732 | booked_by: PersonRef::resolve(people, booking.get_booked_by()), | 732 | booked_by: PersonRef::resolve(people, booking.get_booked_by()), |
| @@ -1005,10 +1005,8 @@ async fn cancel_booking( | |||
| 1005 | // gets the same 403 either way, and learns nothing. | 1005 | // gets the same 403 either way, and learns nothing. |
| 1006 | // | 1006 | // |
| 1007 | // Same door as booking: whoever may take the seat may give it back. | 1007 | // Same door as booking: whoever may take the seat may give it back. |
| 1008 | - let student = id | 1008 | + let student = id.student(); |
| 1009 | - .student() | 1009 | + let target = booking_target(&user, Some(student.key().as_str()), &st.db).await?; |
| 1010 | - .ok_or(AppError::Forbidden("not your booking"))?; | ||
| 1011 | - let target = booking_target(&user, Some(student.key()), &st.db).await?; | ||
| 1012 | if target != student { | 1010 | if target != student { |
| 1013 | return Err(AppError::Forbidden("not your booking")); | 1011 | return Err(AppError::Forbidden("not your booking")); |
| 1014 | } | 1012 | } |
| @@ -1067,7 +1065,7 @@ struct MealAttendanceResponse { | |||
| 1067 | impl MealAttendanceResponse { | 1065 | impl MealAttendanceResponse { |
| 1068 | fn new(row: &MealAttendance, people: &std::collections::HashMap<String, PersonRef>) -> Self { | 1066 | fn new(row: &MealAttendance, people: &std::collections::HashMap<String, PersonRef>) -> Self { |
| 1069 | Self { | 1067 | Self { |
| 1070 | - id: row.get_id().key().to_string(), | 1068 | + id: MealAttendanceId::composite(row.get_menu(), &row.get_student()).key(), |
| 1071 | menu_id: row.get_menu().key().to_string(), | 1069 | menu_id: row.get_menu().key().to_string(), |
| 1072 | student: PersonRef::resolve(people, row.get_student()), | 1070 | student: PersonRef::resolve(people, row.get_student()), |
| 1073 | status: row.get_status().as_str().to_string(), | 1071 | status: row.get_status().as_str().to_string(), |
src/web/messages.rsmodified+1 -1
| @@ -127,7 +127,7 @@ async fn load_people(messages: &[Message], db: &Database) -> Result<People, AppE | |||
| 127 | 127 | ||
| 128 | impl MessageResponse { | 128 | impl MessageResponse { |
| 129 | fn new(message: &Message, caller: &UserId, people: &People) -> Self { | 129 | fn new(message: &Message, caller: &UserId, people: &People) -> Self { |
| 130 | - let resolve = |id: &UserId| match people.get(id.key()) { | 130 | + let resolve = |id: &UserId| match people.get(id.key().as_str()) { |
| 131 | Some((person, role)) => (person.clone(), Some(*role)), | 131 | Some((person, role)) => (person.clone(), Some(*role)), |
| 132 | None => ( | 132 | None => ( |
| 133 | PersonRef { | 133 | PersonRef { |
src/web/notes.rsmodified+4 -4
| @@ -211,7 +211,7 @@ async fn delete_one( | |||
| 211 | // pre-read list — an upload that landed in between is in the cascade too. | 211 | // pre-read list — an upload that landed in between is in the cascade too. |
| 212 | let (_, files) = service::note::delete(&st.db, note).await?; | 212 | let (_, files) = service::note::delete(&st.db, note).await?; |
| 213 | for file in &files { | 213 | for file in &files { |
| 214 | - remove_blob(&st.files_path, file.get_id().key()).await; | 214 | + remove_blob(&st.files_path, &file.get_id().key()).await; |
| 215 | } | 215 | } |
| 216 | Ok(StatusCode::NO_CONTENT) | 216 | Ok(StatusCode::NO_CONTENT) |
| 217 | } | 217 | } |
| @@ -284,7 +284,7 @@ async fn upload_file( | |||
| 284 | // Blob first, row second — a stored row always points at a real blob. If | 284 | // Blob first, row second — a stored row always points at a real blob. If |
| 285 | // the row insert fails, take the fresh blob back out. | 285 | // the row insert fails, take the fresh blob back out. |
| 286 | let file = NoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64); | 286 | let file = NoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64); |
| 287 | - let path = blob_path(&st.files_path, file.get_id().key()); | 287 | + let path = blob_path(&st.files_path, &file.get_id().key()); |
| 288 | crate::web::ensure_files_dir(&st.files_path).await?; | 288 | crate::web::ensure_files_dir(&st.files_path).await?; |
| 289 | tokio::fs::write(&path, &upload.data) | 289 | tokio::fs::write(&path, &upload.data) |
| 290 | .await | 290 | .await |
| @@ -356,7 +356,7 @@ async fn download_file( | |||
| 356 | let file = service::note_file::read_for(&st.db, &NoteFileId::from_key(&file_id), note.get_id()) | 356 | let file = service::note_file::read_for(&st.db, &NoteFileId::from_key(&file_id), note.get_id()) |
| 357 | .await? | 357 | .await? |
| 358 | .ok_or(AppError::NotFound)?; | 358 | .ok_or(AppError::NotFound)?; |
| 359 | - let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key())) | 359 | + let bytes = tokio::fs::read(blob_path(&st.files_path, &file.get_id().key())) |
| 360 | .await | 360 | .await |
| 361 | .map_err(|err| { | 361 | .map_err(|err| { |
| 362 | // The row exists but its blob doesn't — that's server-side damage | 362 | // The row exists but its blob doesn't — that's server-side damage |
| @@ -410,7 +410,7 @@ async fn delete_file( | |||
| 410 | .await? | 410 | .await? |
| 411 | .ok_or(AppError::NotFound)?; | 411 | .ok_or(AppError::NotFound)?; |
| 412 | let file = service::note_file::delete(&st.db, file).await?; | 412 | let file = service::note_file::delete(&st.db, file).await?; |
| 413 | - remove_blob(&st.files_path, file.get_id().key()).await; | 413 | + remove_blob(&st.files_path, &file.get_id().key()).await; |
| 414 | Ok(StatusCode::NO_CONTENT) | 414 | Ok(StatusCode::NO_CONTENT) |
| 415 | } | 415 | } |
| 416 | 416 | ||
src/web/page.rsmodified+2 -2
| @@ -61,7 +61,7 @@ impl PageParams { | |||
| 61 | pub trait Scheduled { | 61 | pub trait Scheduled { |
| 62 | fn starts_at_ms(&self) -> Option<i64>; | 62 | fn starts_at_ms(&self) -> Option<i64>; |
| 63 | fn ends_at_ms(&self) -> Option<i64>; | 63 | fn ends_at_ms(&self) -> Option<i64>; |
| 64 | - fn order_key(&self) -> &str; | 64 | + fn order_key(&self) -> String; |
| 65 | } | 65 | } |
| 66 | 66 | ||
| 67 | /// The optional `?starts_after=&ends_after=` schedule window on a list of | 67 | /// The optional `?starts_after=&ends_after=` schedule window on a list of |
| @@ -116,7 +116,7 @@ impl WindowParams { | |||
| 116 | let key = |item: &T| item.starts_at_ms().or_else(|| item.ends_at_ms()); | 116 | let key = |item: &T| item.starts_at_ms().or_else(|| item.ends_at_ms()); |
| 117 | key(a) | 117 | key(a) |
| 118 | .cmp(&key(b)) | 118 | .cmp(&key(b)) |
| 119 | - .then_with(|| a.order_key().cmp(b.order_key())) | 119 | + .then_with(|| a.order_key().cmp(&b.order_key())) |
| 120 | }); | 120 | }); |
| 121 | Ok(items) | 121 | Ok(items) |
| 122 | } | 122 | } |
src/web/payments.rsmodified+5 -4
| @@ -546,7 +546,8 @@ async fn appended( | |||
| 546 | } | 546 | } |
| 547 | 547 | ||
| 548 | async fn require_line(id: &str, db: &Database) -> Result<PaymentLedger, AppError> { | 548 | async fn require_line(id: &str, db: &Database) -> Result<PaymentLedger, AppError> { |
| 549 | - service::payment_ledger::read(db, &PaymentLedgerId::from_key(id)) | 549 | + let id = PaymentLedgerId::from_key(id); |
| 550 | + service::payment_ledger::read(db, &id) | ||
| 550 | .await? | 551 | .await? |
| 551 | .ok_or(AppError::NotFound) | 552 | .ok_or(AppError::NotFound) |
| 552 | } | 553 | } |
| @@ -877,10 +878,10 @@ async fn statement_response( | |||
| 877 | let (assignments, _) = | 878 | let (assignments, _) = |
| 878 | service::fee_plan_assignment::list_for_student(db, student, None, 0).await?; | 879 | service::fee_plan_assignment::list_for_student(db, student, None, 0).await?; |
| 879 | let mut plan_names: HashMap<String, Option<String>> = HashMap::new(); | 880 | let mut plan_names: HashMap<String, Option<String>> = HashMap::new(); |
| 880 | - let mut plan_of: HashMap<&str, &FeePlanId> = HashMap::new(); | 881 | + let mut plan_of: HashMap<String, &FeePlanId> = HashMap::new(); |
| 881 | for assignment in &assignments { | 882 | for assignment in &assignments { |
| 882 | let plan = assignment.get_plan(); | 883 | let plan = assignment.get_plan(); |
| 883 | - if !plan_names.contains_key(plan.key()) { | 884 | + if !plan_names.contains_key(plan.key().as_str()) { |
| 884 | let name = service::fee_plan::read(db, plan) | 885 | let name = service::fee_plan::read(db, plan) |
| 885 | .await? | 886 | .await? |
| 886 | .map(|plan| plan.get_name().as_str().to_string()); | 887 | .map(|plan| plan.get_name().as_str().to_string()); |
| @@ -935,7 +936,7 @@ async fn statement_response( | |||
| 935 | StatementEntry { | 936 | StatementEntry { |
| 936 | charge_id: charge.get_id().key().to_string(), | 937 | charge_id: charge.get_id().key().to_string(), |
| 937 | plan: plan.map(|plan| plan.key().to_string()), | 938 | plan: plan.map(|plan| plan.key().to_string()), |
| 938 | - plan_name: plan.and_then(|plan| plan_names.get(plan.key()).cloned().flatten()), | 939 | + plan_name: plan.and_then(|plan| plan_names.get(plan.key().as_str()).cloned().flatten()), |
| 939 | amount_minor: charge.get_amount_minor().as_minor(), | 940 | amount_minor: charge.get_amount_minor().as_minor(), |
| 940 | due_at, | 941 | due_at, |
| 941 | credited_minor: credited, | 942 | credited_minor: credited, |
src/web/questions.rsmodified+1 -1
| @@ -232,7 +232,7 @@ async fn question_responses( | |||
| 232 | Ok(questions | 232 | Ok(questions |
| 233 | .iter() | 233 | .iter() |
| 234 | .map(|question| { | 234 | .map(|question| { |
| 235 | - let count = counts.get(question.get_id().key()).copied().unwrap_or(0); | 235 | + let count = counts.get(&question.get_id().key()).copied().unwrap_or(0); |
| 236 | PoolQuestionResponse::new(question, &people, count) | 236 | PoolQuestionResponse::new(question, &people, count) |
| 237 | }) | 237 | }) |
| 238 | .collect()) | 238 | .collect()) |
src/web/sessions.rsmodified+2 -2
| @@ -15,7 +15,7 @@ use crate::domain::course::Course; | |||
| 15 | use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; | 15 | use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; |
| 16 | 16 | ||
| 17 | use crate::domain::role::Role; | 17 | use crate::domain::role::Role; |
| 18 | -use crate::domain::session_attendance::SessionAttendance; | 18 | +use crate::domain::session_attendance::{SessionAttendance, SessionAttendanceId}; |
| 19 | use crate::domain::timestamp::Timestamp; | 19 | use crate::domain::timestamp::Timestamp; |
| 20 | use crate::domain::user::{User, UserId}; | 20 | use crate::domain::user::{User, UserId}; |
| 21 | use crate::error::{AppError, ErrorResponse}; | 21 | use crate::error::{AppError, ErrorResponse}; |
| @@ -77,7 +77,7 @@ struct SessionAttendanceResponse { | |||
| 77 | impl SessionAttendanceResponse { | 77 | impl SessionAttendanceResponse { |
| 78 | fn new(attendance: &SessionAttendance, people: &HashMap<String, PersonRef>) -> Self { | 78 | fn new(attendance: &SessionAttendance, people: &HashMap<String, PersonRef>) -> Self { |
| 79 | Self { | 79 | Self { |
| 80 | - id: attendance.get_id().key().to_string(), | 80 | + id: SessionAttendanceId::composite(attendance.get_session(), &attendance.get_user()).key(), |
| 81 | session: attendance.get_session().key().to_string(), | 81 | session: attendance.get_session().key().to_string(), |
| 82 | course: attendance.get_course().key().to_string(), | 82 | course: attendance.get_course().key().to_string(), |
| 83 | user: PersonRef::resolve(people, attendance.get_user()), | 83 | user: PersonRef::resolve(people, attendance.get_user()), |
src/web/users.rsmodified+2 -2
| @@ -490,7 +490,7 @@ async fn set_role( | |||
| 490 | for board in boards { | 490 | for board in boards { |
| 491 | st.board_hub.publish( | 491 | st.board_hub.publish( |
| 492 | &slug, | 492 | &slug, |
| 493 | - board.get_id().key(), | 493 | + board.get_id().key().as_str(), |
| 494 | json!({ | 494 | json!({ |
| 495 | "type": "participants", | 495 | "type": "participants", |
| 496 | "creator": board.get_creator().key(), | 496 | "creator": board.get_creator().key(), |
| @@ -505,7 +505,7 @@ async fn set_role( | |||
| 505 | if let Some(closed_at) = board.get_closed_at() { | 505 | if let Some(closed_at) = board.get_closed_at() { |
| 506 | st.board_hub.publish( | 506 | st.board_hub.publish( |
| 507 | &slug, | 507 | &slug, |
| 508 | - board.get_id().key(), | 508 | + board.get_id().key().as_str(), |
| 509 | json!({"type": "closed", "closed_at": closed_at.as_millis()}).to_string(), | 509 | json!({"type": "closed", "closed_at": closed_at.as_millis()}).to_string(), |
| 510 | ); | 510 | ); |
| 511 | } | 511 | } |