forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

exam_weight.rs239 lines, 7.8 KiBHistoryRawDownload
1//! The `offering_exam_weight` / `class_course_exam_weight` tables: per-kind
2//! weight overrides under the grade-level template and the class section.
3//!
4//! Every class-owned write keeps the override flag honest **in the same
5//! statement**: a data-modifying CTE flips `class_course.exam_weights_inherited`
6//! to `FALSE` while the weight row is written (or dropped), so a crash between
7//! "row changed" and "flag changed" is impossible and
8//! `class_course`'s own module never enters the picture. The reset deletes the
9//! section's rows and restores `TRUE` in one statement too — the shape
10//! [`crate::db::class_course::clear_overrides`] uses for the scalar overrides.
11//!
12//! The chain that *reads* these rows lives in
13//! [`crate::service::exam_weight`]; this file is the SQL executor only.
14
15use crate::database::Database;
16use crate::domain::class_course::ClassCourseId;
17use crate::domain::course_offering::CourseOfferingId;
18use crate::domain::exam_weight::ExamWeight;
19use crate::error::AppError;
20
21/// The offering's own weight rows, by kind — the override set of the
22/// grade-level template.
23pub async fn list_for_offering(
24 db: &Database,
25 offering: &CourseOfferingId,
26) -> Result<Vec<ExamWeight>, AppError> {
27 let rows = sqlx::query!(
28 r#"SELECT kind, weight::bigint AS "weight!: i64"
29 FROM offering_exam_weight WHERE offering = $1
30 ORDER BY kind"#,
31 offering.uuid(),
32 )
33 .fetch_all(db)
34 .await?;
35 Ok(rows
36 .into_iter()
37 .map(|row| ExamWeight {
38 kind: row.kind,
39 weight: row.weight,
40 })
41 .collect())
42}
43
44/// One offering weight row, or `None` when the pair holds none — the second
45/// step of [`crate::service::exam_weight::resolve`].
46pub async fn offering_weight(
47 db: &Database,
48 offering: &CourseOfferingId,
49 kind: &str,
50) -> Result<Option<ExamWeight>, AppError> {
51 let row = sqlx::query!(
52 r#"SELECT kind, weight::bigint AS "weight!: i64"
53 FROM offering_exam_weight WHERE offering = $1 AND kind = $2"#,
54 offering.uuid(),
55 kind,
56 )
57 .fetch_optional(db)
58 .await?;
59 Ok(row.map(|row| ExamWeight {
60 kind: row.kind,
61 weight: row.weight,
62 }))
63}
64
65/// Upsert one weight on the template. A duplicate (offering, kind) pair
66/// *rewrites* the weight — a PATCH of an existing kind is the normal path, not
67/// a conflict.
68pub async fn upsert_for_offering(
69 db: &Database,
70 offering: &CourseOfferingId,
71 kind: &str,
72 weight: &ExamWeight,
73) -> Result<(), AppError> {
74 sqlx::query!(
75 r#"INSERT INTO offering_exam_weight (offering, kind, weight)
76 VALUES ($1, $2, $3::bigint::smallint)
77 ON CONFLICT (offering, kind) DO UPDATE SET weight = EXCLUDED.weight"#,
78 offering.uuid(),
79 kind,
80 weight.get_weight(),
81 )
82 .execute(db)
83 .await?;
84 Ok(())
85}
86
87/// Drop one weight row from the template. `false` when the pair held no row —
88/// the caller's 404.
89pub async fn delete_from_offering(
90 db: &Database,
91 offering: &CourseOfferingId,
92 kind: &str,
93) -> Result<bool, AppError> {
94 let result = sqlx::query!(
95 r#"DELETE FROM offering_exam_weight WHERE offering = $1 AND kind = $2"#,
96 offering.uuid(),
97 kind,
98 )
99 .execute(db)
100 .await?;
101 Ok(result.rows_affected() > 0)
102}
103
104/// The section's own weight rows, by kind — authoritative exactly while
105/// `exam_weights_inherited` is `FALSE`, **including when empty**.
106pub async fn list_for_class(
107 db: &Database,
108 instance: &ClassCourseId,
109) -> Result<Vec<ExamWeight>, AppError> {
110 let rows = sqlx::query!(
111 r#"SELECT kind, weight::bigint AS "weight!: i64"
112 FROM class_course_exam_weight WHERE class_course = $1
113 ORDER BY kind"#,
114 instance.uuid(),
115 )
116 .fetch_all(db)
117 .await?;
118 Ok(rows
119 .into_iter()
120 .map(|row| ExamWeight {
121 kind: row.kind,
122 weight: row.weight,
123 })
124 .collect())
125}
126
127/// One section weight row, or `None` — the first step of
128/// [`crate::service::exam_weight::resolve`] while the section's own set is in
129/// force.
130pub async fn class_weight(
131 db: &Database,
132 instance: &ClassCourseId,
133 kind: &str,
134) -> Result<Option<ExamWeight>, AppError> {
135 let row = sqlx::query!(
136 r#"SELECT kind, weight::bigint AS "weight!: i64"
137 FROM class_course_exam_weight WHERE class_course = $1 AND kind = $2"#,
138 instance.uuid(),
139 kind,
140 )
141 .fetch_optional(db)
142 .await?;
143 Ok(row.map(|row| ExamWeight {
144 kind: row.kind,
145 weight: row.weight,
146 }))
147}
148
149/// Upsert one weight on the section **and** take the set own — both in the
150/// statement that writes the row, so `exam_weights_inherited` can never claim
151/// "inherit" over a row the section actually carries. `Err(NotFound)` when the
152/// instance is gone (the CTE's UPDATE finds no row).
153pub async fn upsert_for_class(
154 db: &Database,
155 instance: &ClassCourseId,
156 kind: &str,
157 weight: &ExamWeight,
158) -> Result<(), AppError> {
159 sqlx::query!(
160 r#"WITH updated AS (
161 UPDATE class_course
162 SET exam_weights_inherited = FALSE
163 WHERE id = $1
164 RETURNING id
165 ), written AS (
166 INSERT INTO class_course_exam_weight (class_course, kind, weight)
167 SELECT $1, $2, $3::bigint::smallint
168 WHERE EXISTS (SELECT 1 FROM updated)
169 ON CONFLICT (class_course, kind) DO UPDATE SET weight = EXCLUDED.weight
170 RETURNING class_course
171 )
172 SELECT u.id AS "id: ClassCourseId" FROM updated u"#,
173 instance.uuid(),
174 kind,
175 weight.get_weight(),
176 )
177 .fetch_optional(db)
178 .await?
179 .ok_or(AppError::NotFound)?;
180 Ok(())
181}
182
183/// Drop one weight row from the section, flipping the flag to `FALSE` **only
184/// when a row was actually dropped** — a DELETE naming a kind the section
185/// carries no row for mutates nothing and answers `false` (the caller's 404),
186/// so a refused delete never changes the inheritance state. `Err(NotFound)`
187/// when the instance itself is gone.
188pub async fn delete_from_class(
189 db: &Database,
190 instance: &ClassCourseId,
191 kind: &str,
192) -> Result<bool, AppError> {
193 let row = sqlx::query!(
194 r#"WITH kicked AS (
195 DELETE FROM class_course_exam_weight
196 WHERE class_course = $1 AND kind = $2
197 RETURNING class_course
198 ), updated AS (
199 UPDATE class_course
200 SET exam_weights_inherited =
201 CASE WHEN EXISTS (SELECT 1 FROM kicked)
202 THEN FALSE ELSE exam_weights_inherited END
203 WHERE id = $1
204 RETURNING exam_weights_inherited
205 )
206 SELECT u.exam_weights_inherited AS "inherited: bool",
207 (SELECT count(*)::bigint FROM kicked) AS "removed!: i64"
208 FROM updated u"#,
209 instance.uuid(),
210 kind,
211 )
212 .fetch_optional(db)
213 .await?
214 .ok_or(AppError::NotFound)?;
215 Ok(row.removed > 0)
216}
217
218/// The reset door: delete every section weight row and restore
219/// `exam_weights_inherited = TRUE` in one statement — the offering's set (then
220/// the settings, then 1) applies again. `Err(NotFound)` when the instance is
221/// gone; otherwise idempotent.
222pub async fn reset_class(db: &Database, instance: &ClassCourseId) -> Result<(), AppError> {
223 sqlx::query!(
224 r#"WITH kicked AS (
225 DELETE FROM class_course_exam_weight WHERE class_course = $1
226 ), updated AS (
227 UPDATE class_course
228 SET exam_weights_inherited = TRUE
229 WHERE id = $1
230 RETURNING id
231 )
232 SELECT u.id AS "id: ClassCourseId" FROM updated u"#,
233 instance.uuid(),
234 )
235 .fetch_optional(db)
236 .await?
237 .ok_or(AppError::NotFound)?;
238 Ok(())
239}