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

class_course.rs412 lines, 18.1 KiBHistoryRawDownload
1//! The `class_course` table: the course-axis attach entry point and the
2//! instance reads behind `/instances`. The refusals-to-errors policy and the
3//! detach that turns a zero-row sweep into a 404 live in
4//! [`crate::service::class_course`]; the transaction itself is the pump's,
5//! [`crate::db::class_pump`].
6//!
7//! An instance is the academic anchor now: it points at its grade-level
8//! **offering** template, carries its own content *overrides* (title,
9//! description, and the nullable `ders_saati` / `counts_toward_karne` — a
10//! `NULL` inherits from the offering chain, so every read goes through
11//! [`crate::service::class_course::resolve_policy`], never a blind unwrap),
12//! the three `*_inherited` set flags, and the roster counter its own teachers
13//! ([`crate::db::class_course_teacher`]). Reads speak the *bare uuid* id of
14//! the instance; the (class, course) pair survives as the UNIQUE key the
15//! attach gates on.
16
17use crate::constant::CLASS_COURSE_TABLE;
18use crate::database::Database;
19use crate::db::class_pump::Attached;
20use crate::db::page::PagedList;
21use crate::domain::class_blueprint::ClassBlueprintId;
22use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati, OverrideField};
23use crate::domain::class_group::ClassGroupId;
24use crate::domain::course::{CourseDescription, CourseId, CourseTitle};
25use crate::domain::course_offering::CourseOfferingId;
26use crate::domain::timestamp::Timestamp;
27use crate::domain::user::UserId;
28use crate::error::AppError;
29
30/// The projection every instance read shares.
31///
32/// Three translations ride it: `source` is stored as the blueprint's surrogate
33/// uuid while the domain speaks the grade label the API does (a hand attach,
34/// source NULL, survives the LEFT JOIN as NULL), `ders_saati` is a *nullable*
35/// `SMALLINT` column while [`DersSaati`] is an `i64` newtype — decoded
36/// through a `bigint` cast so the type the driver checks is the one the
37/// newtype names, its `NULL` meaning *inherit* — and the overrides/flags ride
38/// along as their plain column shapes.
39const INSTANCE_COLUMNS: &str = "cc.id, cc.class, cc.course, cc.offering, cc.attached_by, \
40 b.grade_level AS source, cc.title, cc.description, \
41 cc.ders_saati::bigint AS ders_saati, cc.counts_toward_karne, \
42 cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited, \
43 cc.enrollment_count, cc.attached_at";
44
45/// The attach itself, with the refusals left *unmapped*.
46///
47/// A hand attach ([`crate::service::class_course::attach`]) turns each of them
48/// into the error the route answers with, because one call is one course and a
49/// refusal is that call's whole answer. A blueprint pump cannot: it runs
50/// one of these per (class, course), and a course that does not fit one
51/// section must not abort the other eleven — so it needs to *read* the
52/// refusal and carry on ([`crate::domain::class_blueprint`]).
53///
54/// `source` is the provenance tag, and it is written by the same statement
55/// that writes the link, so no attachment can exist without the answer to
56/// "may a blueprint take this back". It is also *claimed* in that
57/// transaction ([`Attached::SourceGone`]): a blueprint deleted while this
58/// pump ran has already swept by that tag, so a row landing afterwards
59/// would carry a name nothing can reach.
60pub(crate) async fn attach_sourced(
61 db: &Database,
62 class: &ClassGroupId,
63 course: &CourseId,
64 attached_by: &UserId,
65 source: Option<&ClassBlueprintId>,
66) -> Result<Attached<ClassCourse>, AppError> {
67 crate::db::class_pump::attach_course(db, class, course, attached_by, source).await
68}
69
70/// The instances a class carries, newest first — by when they were attached,
71/// the instance id breaking the tie (v7 ids sort in mint order, so the order
72/// is total and reads as creation order within one instant).
73pub async fn list_for_class(
74 db: &Database,
75 class: &ClassGroupId,
76 limit: Option<i64>,
77 offset: i64,
78) -> Result<(Vec<ClassCourse>, i64), AppError> {
79 PagedList::new(
80 format!(
81 "(SELECT {INSTANCE_COLUMNS} FROM {CLASS_COURSE_TABLE} cc \
82 LEFT JOIN class_blueprint b ON b.id = cc.source) \
83 AS {CLASS_COURSE_TABLE} WHERE class = $1"
84 ),
85 "ORDER BY attached_at DESC, id DESC",
86 )
87 .bind(class.uuid())
88 .run(limit, offset, db)
89 .await
90}
91
92/// The instances one catalog course is taught in, newest first — the read
93/// behind "which sections run this course".
94pub async fn list_for_course(
95 db: &Database,
96 course: &CourseId,
97 limit: Option<i64>,
98 offset: i64,
99) -> Result<(Vec<ClassCourse>, i64), AppError> {
100 PagedList::new(
101 format!(
102 "(SELECT {INSTANCE_COLUMNS} FROM {CLASS_COURSE_TABLE} cc \
103 LEFT JOIN class_blueprint b ON b.id = cc.source) \
104 AS {CLASS_COURSE_TABLE} WHERE course = $1"
105 ),
106 "ORDER BY attached_at DESC, id DESC",
107 )
108 .bind(course.uuid())
109 .run(limit, offset, db)
110 .await
111}
112
113/// Every instance held by any of `classes` (one query, unpaged) — the join
114/// half of the class-layer reads that already hold class ids (a roster read,
115/// a blueprint status diff). Ids that name no class are simply absent from
116/// the result.
117pub async fn list_for_class_ids(
118 db: &Database,
119 classes: &[ClassGroupId],
120) -> Result<Vec<ClassCourse>, AppError> {
121 if classes.is_empty() {
122 return Ok(Vec::new());
123 }
124 let ids: Vec<uuid::Uuid> = classes.iter().map(ClassGroupId::uuid).collect();
125 let rows = sqlx::query_as!(
126 ClassCourse,
127 r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId",
128 cc.course AS "course: CourseId", cc.offering AS "offering: CourseOfferingId",
129 cc.attached_by AS "attached_by: UserId",
130 b.grade_level AS "source?: ClassBlueprintId",
131 cc.title AS "title?: CourseTitle",
132 cc.description AS "description?: CourseDescription",
133 cc.ders_saati::bigint AS "ders_saati?: DersSaati",
134 cc.counts_toward_karne,
135 cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited,
136 cc.enrollment_count,
137 cc.attached_at AS "attached_at: Timestamp"
138 FROM class_course cc
139 LEFT JOIN class_blueprint b ON b.id = cc.source
140 WHERE cc.class = ANY($1)
141 ORDER BY cc.attached_at DESC, cc.id DESC"#,
142 &ids,
143 )
144 .fetch_all(db)
145 .await?;
146 Ok(rows)
147}
148
149/// Every instance of any of `courses` (one query, unpaged) — the batched twin
150/// of [`list_for_course`]: the catalogue page reads one query per page, not
151/// one per course. Ids that name no course are simply absent from the result.
152pub async fn list_for_course_ids(
153 db: &Database,
154 courses: &[CourseId],
155) -> Result<Vec<ClassCourse>, AppError> {
156 if courses.is_empty() {
157 return Ok(Vec::new());
158 }
159 let ids: Vec<uuid::Uuid> = courses.iter().map(CourseId::uuid).collect();
160 let rows = sqlx::query_as!(
161 ClassCourse,
162 r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId",
163 cc.course AS "course: CourseId", cc.offering AS "offering: CourseOfferingId",
164 cc.attached_by AS "attached_by: UserId",
165 b.grade_level AS "source?: ClassBlueprintId",
166 cc.title AS "title?: CourseTitle",
167 cc.description AS "description?: CourseDescription",
168 cc.ders_saati::bigint AS "ders_saati?: DersSaati",
169 cc.counts_toward_karne,
170 cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited,
171 cc.enrollment_count,
172 cc.attached_at AS "attached_at: Timestamp"
173 FROM class_course cc
174 LEFT JOIN class_blueprint b ON b.id = cc.source
175 WHERE cc.course = ANY($1)
176 ORDER BY cc.attached_at DESC, cc.id DESC"#,
177 &ids,
178 )
179 .fetch_all(db)
180 .await?;
181 Ok(rows)
182}
183
184/// Every instance `teacher` is assigned to (one query, unpaged) — the batched
185/// replacement for [`list_for_teacher`]-then-[`list_for_course`]-per-course:
186/// a reach read walks the assignment junction directly, so a teacher's
187/// catalogue page costs one query, not one per taught course. A teacher
188/// assigned to two sections of one course gets both rows; an id that names no
189/// assignment is simply absent.
190pub async fn list_for_teacher_ids(
191 db: &Database,
192 teacher: &UserId,
193) -> Result<Vec<ClassCourse>, AppError> {
194 let rows = sqlx::query_as!(
195 ClassCourse,
196 r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId",
197 cc.course AS "course: CourseId", cc.offering AS "offering: CourseOfferingId",
198 cc.attached_by AS "attached_by: UserId",
199 b.grade_level AS "source?: ClassBlueprintId",
200 cc.title AS "title?: CourseTitle",
201 cc.description AS "description?: CourseDescription",
202 cc.ders_saati::bigint AS "ders_saati?: DersSaati",
203 cc.counts_toward_karne,
204 cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited,
205 cc.enrollment_count,
206 cc.attached_at AS "attached_at: Timestamp"
207 FROM class_course cc
208 JOIN class_course_teacher t ON t.class_course = cc.id
209 LEFT JOIN class_blueprint b ON b.id = cc.source
210 WHERE t.teacher = $1
211 ORDER BY cc.attached_at DESC, cc.id DESC"#,
212 teacher.uuid(),
213 )
214 .fetch_all(db)
215 .await?;
216 Ok(rows)
217}
218
219/// Load every instance behind `ids` (one query) — the join half of the reads
220/// that already hold instance ids (a marks report's per-instance blocks).
221pub async fn list_by_ids(
222 db: &Database,
223 ids: &[ClassCourseId],
224) -> Result<Vec<ClassCourse>, AppError> {
225 if ids.is_empty() {
226 return Ok(Vec::new());
227 }
228 let keys: Vec<uuid::Uuid> = ids.iter().map(ClassCourseId::uuid).collect();
229 let rows = sqlx::query_as!(
230 ClassCourse,
231 r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId",
232 cc.course AS "course: CourseId", cc.offering AS "offering: CourseOfferingId",
233 cc.attached_by AS "attached_by: UserId",
234 b.grade_level AS "source?: ClassBlueprintId",
235 cc.title AS "title?: CourseTitle",
236 cc.description AS "description?: CourseDescription",
237 cc.ders_saati::bigint AS "ders_saati?: DersSaati",
238 cc.counts_toward_karne,
239 cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited,
240 cc.enrollment_count,
241 cc.attached_at AS "attached_at: Timestamp"
242 FROM class_course cc
243 LEFT JOIN class_blueprint b ON b.id = cc.source
244 WHERE cc.id = ANY($1)
245 ORDER BY cc.attached_at DESC, cc.id DESC"#,
246 &keys,
247 )
248 .fetch_all(db)
249 .await?;
250 Ok(rows)
251}
252
253/// One instance, or `None` when the id names no row.
254pub async fn read(db: &Database, id: &ClassCourseId) -> Result<Option<ClassCourse>, AppError> {
255 let row = sqlx::query_as!(
256 ClassCourse,
257 r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId",
258 cc.course AS "course: CourseId", cc.offering AS "offering: CourseOfferingId",
259 cc.attached_by AS "attached_by: UserId",
260 b.grade_level AS "source?: ClassBlueprintId",
261 cc.title AS "title?: CourseTitle",
262 cc.description AS "description?: CourseDescription",
263 cc.ders_saati::bigint AS "ders_saati?: DersSaati",
264 cc.counts_toward_karne,
265 cc.subjects_inherited, cc.exam_weights_inherited, cc.weekly_plan_inherited,
266 cc.enrollment_count,
267 cc.attached_at AS "attached_at: Timestamp"
268 FROM class_course cc
269 LEFT JOIN class_blueprint b ON b.id = cc.source
270 WHERE cc.id = $1"#,
271 id.uuid(),
272 )
273 .fetch_optional(db)
274 .await?;
275 Ok(row)
276}
277
278/// The class this instance belongs to, or `None` when the id names no row —
279/// the seam every instance-scoped route reads the section (and, through it, the
280/// year) off.
281pub async fn class_of(db: &Database, id: &ClassCourseId) -> Result<Option<ClassGroupId>, AppError> {
282 let row = sqlx::query!(
283 r#"SELECT class AS "class: ClassGroupId" FROM class_course WHERE id = $1"#,
284 id.uuid(),
285 )
286 .fetch_optional(db)
287 .await?;
288 Ok(row.map(|row| row.class))
289}
290
291/// Set the instance's own policy overrides — the PATCH behind
292/// `PATCH /instances/{id}`. Each `Some(_)` *sets* the column (a PATCH never
293/// clears; clearing is [`clear_overrides`]'s job); `None` keeps what the
294/// column holds.
295///
296/// No counter moves and no compare-and-set is needed: every field is an
297/// independent scalar, so two PATCHes touching different ones cannot revert
298/// each other. `Err(NotFound)` when the instance is gone — the same answer
299/// the caller's own read gives one instant earlier.
300pub async fn update(
301 db: &Database,
302 id: &ClassCourseId,
303 title: Option<CourseTitle>,
304 description: Option<CourseDescription>,
305 staff: Option<DersSaati>,
306 counts: Option<bool>,
307) -> Result<ClassCourse, AppError> {
308 // `i64`, cast down by the statement itself: the column is a nullable
309 // `SMALLINT` and the newtype wraps an `i64`, so naming both types
310 // explicitly is what keeps the driver's type check honest in either
311 // direction. The text columns set-only via `COALESCE` for the same
312 // never-clears rule.
313 let hours = staff.map(|hours| hours.as_i64());
314 let title = title.map(|title| title.as_str().to_string());
315 let description = description.map(|d| d.as_str().to_string());
316 let row = sqlx::query_as!(
317 ClassCourse,
318 r#"WITH updated AS (
319 UPDATE class_course
320 SET title = COALESCE($2, title),
321 description = COALESCE($3, description),
322 ders_saati = COALESCE($4::bigint, ders_saati::bigint)::smallint,
323 counts_toward_karne = COALESCE($5, counts_toward_karne)
324 WHERE id = $1
325 RETURNING *)
326 SELECT u.id AS "id: ClassCourseId", u.class AS "class: ClassGroupId",
327 u.course AS "course: CourseId", u.offering AS "offering: CourseOfferingId",
328 u.attached_by AS "attached_by: UserId",
329 b.grade_level AS "source?: ClassBlueprintId",
330 u.title AS "title?: CourseTitle",
331 u.description AS "description?: CourseDescription",
332 u.ders_saati::bigint AS "ders_saati?: DersSaati",
333 u.counts_toward_karne,
334 u.subjects_inherited, u.exam_weights_inherited, u.weekly_plan_inherited,
335 u.enrollment_count,
336 u.attached_at AS "attached_at: Timestamp"
337 FROM updated u
338 LEFT JOIN class_blueprint b ON b.id = u.source"#,
339 id.uuid(),
340 title,
341 description,
342 hours,
343 counts,
344 )
345 .fetch_optional(db)
346 .await?
347 .ok_or(AppError::NotFound)?;
348 Ok(row)
349}
350
351/// Clear the named overrides back to **inherit**: the scalars go `NULL` (the
352/// offering's default, then the constants, apply again) and a set flag goes
353/// back to `TRUE` (the offering's set is authoritative again — deleting the
354/// section's own set rows rides the child-table lanes' reset). The empty
355/// request is refused by the service before it gets here; a gone instance is
356/// the usual 404.
357///
358/// The whole reset is one statement: the named clears are judged on the row
359/// as it is *at the write*, so a PATCH landing between the caller's read and
360/// this write cannot be silently reverted field-by-field.
361pub async fn clear_overrides(
362 db: &Database,
363 id: &ClassCourseId,
364 fields: &[OverrideField],
365) -> Result<ClassCourse, AppError> {
366 let title = fields.contains(&OverrideField::Title);
367 let description = fields.contains(&OverrideField::Description);
368 let staff = fields.contains(&OverrideField::DersSaati);
369 let counts = fields.contains(&OverrideField::CountsTowardKarne);
370 let subjects = fields.contains(&OverrideField::Subjects);
371 let exam_weights = fields.contains(&OverrideField::ExamWeights);
372 let weekly_plan = fields.contains(&OverrideField::WeeklyPlan);
373 let row = sqlx::query_as!(
374 ClassCourse,
375 r#"WITH updated AS (
376 UPDATE class_course SET
377 title = CASE WHEN $2 THEN NULL ELSE title END,
378 description = CASE WHEN $3 THEN NULL ELSE description END,
379 ders_saati = CASE WHEN $4 THEN NULL ELSE ders_saati END,
380 counts_toward_karne = CASE WHEN $5 THEN NULL ELSE counts_toward_karne END,
381 subjects_inherited = CASE WHEN $6 THEN TRUE ELSE subjects_inherited END,
382 exam_weights_inherited = CASE WHEN $7 THEN TRUE ELSE exam_weights_inherited END,
383 weekly_plan_inherited = CASE WHEN $8 THEN TRUE ELSE weekly_plan_inherited END
384 WHERE id = $1
385 RETURNING *)
386 SELECT u.id AS "id: ClassCourseId", u.class AS "class: ClassGroupId",
387 u.course AS "course: CourseId", u.offering AS "offering: CourseOfferingId",
388 u.attached_by AS "attached_by: UserId",
389 b.grade_level AS "source?: ClassBlueprintId",
390 u.title AS "title?: CourseTitle",
391 u.description AS "description?: CourseDescription",
392 u.ders_saati::bigint AS "ders_saati?: DersSaati",
393 u.counts_toward_karne,
394 u.subjects_inherited, u.exam_weights_inherited, u.weekly_plan_inherited,
395 u.enrollment_count,
396 u.attached_at AS "attached_at: Timestamp"
397 FROM updated u
398 LEFT JOIN class_blueprint b ON b.id = u.source"#,
399 id.uuid(),
400 title,
401 description,
402 staff,
403 counts,
404 subjects,
405 exam_weights,
406 weekly_plan,
407 )
408 .fetch_optional(db)
409 .await?
410 .ok_or(AppError::NotFound)?;
411 Ok(row)
412}