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

offering_subject.rs244 lines, 9.0 KiBHistoryRawDownload
1//! The syllabus selection junctions: `offering_subject` (what the grade-level
2//! template teaches) and `class_course_subject` (what one section teaches for
3//! itself), over the subject rows of [`crate::db::subject`]. The row types are
4//! the subjects themselves — a selection is only membership — so every read
5//! here answers `Vec<Subject>` in the resolved listing order: **by subject
6//! name, then subject id** (deterministic under any insert order).
7//!
8//! The class-side writes are the override machinery: each is **one
9//! data-modifying-CTE statement** that flips `class_course.subjects_inherited`
10//! in the same breath it inserts, deletes or sweeps the section's rows — the
11//! flag can never drift from the table it governs, and this module never
12//! touches `class_course` outside that flag. The reset is the same shape in
13//! reverse: sweep the rows, flip the flag back to TRUE, one statement.
14
15use crate::database::Database;
16use crate::domain::class_course::ClassCourseId;
17use crate::domain::course::CourseId;
18use crate::domain::course_offering::CourseOfferingId;
19use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};
20use crate::error::AppError;
21
22/// Map the junctions' foreign-key refusals to the caller's 404: an offering,
23/// a section or a subject deleted between the service's up-front read and
24/// this write cannot half-land (the same mapping
25/// [`crate::db::subject::create`] uses for its course key).
26fn gone(err: sqlx::Error) -> AppError {
27 if crate::database::foreign_key_violation(&err) {
28 AppError::NotFound
29 } else {
30 err.into()
31 }
32}
33
34/// The offering's selected topics, name-then-id order.
35pub async fn list_for_offering(
36 db: &Database,
37 offering: &CourseOfferingId,
38) -> Result<Vec<Subject>, AppError> {
39 let rows = sqlx::query_as!(
40 Subject,
41 r#"SELECT s.id AS "id: SubjectId",
42 s.course AS "course: CourseId",
43 s.name AS "name: SubjectName",
44 s.description AS "description: SubjectDescription"
45 FROM offering_subject os
46 JOIN subject s ON s.id = os.subject
47 WHERE os.offering = $1
48 ORDER BY s.name ASC, s.id ASC"#,
49 offering.uuid(),
50 )
51 .fetch_all(db)
52 .await?;
53 Ok(rows)
54}
55
56/// The section's own selected topics — authoritative only while
57/// `subjects_inherited` is FALSE, and empty-list-is-a-set then — name-then-id
58/// order.
59pub async fn list_for_class_course(
60 db: &Database,
61 class_course: &ClassCourseId,
62) -> Result<Vec<Subject>, AppError> {
63 let rows = sqlx::query_as!(
64 Subject,
65 r#"SELECT s.id AS "id: SubjectId",
66 s.course AS "course: CourseId",
67 s.name AS "name: SubjectName",
68 s.description AS "description: SubjectDescription"
69 FROM class_course_subject ccs
70 JOIN subject s ON s.id = ccs.subject
71 WHERE ccs.class_course = $1
72 ORDER BY s.name ASC, s.id ASC"#,
73 class_course.uuid(),
74 )
75 .fetch_all(db)
76 .await?;
77 Ok(rows)
78}
79
80/// Add one topic to the offering's selection. Idempotent: re-adding a
81/// selection the offering already holds writes nothing and answers `false`
82/// (`true` = newly added), matching the junction idiom.
83pub async fn add_for_offering(
84 db: &Database,
85 offering: &CourseOfferingId,
86 subject: &SubjectId,
87) -> Result<bool, AppError> {
88 let added = sqlx::query!(
89 r#"INSERT INTO offering_subject (offering, subject)
90 VALUES ($1, $2)
91 ON CONFLICT DO NOTHING"#,
92 offering.uuid(),
93 subject.uuid(),
94 )
95 .execute(db)
96 .await
97 .map_err(gone)?;
98 Ok(added.rows_affected() > 0)
99}
100
101/// Drop one topic from the offering's selection. `false` when it was not
102/// selected — an honest nothing-changed, which the service answers as a 404.
103pub async fn remove_for_offering(
104 db: &Database,
105 offering: &CourseOfferingId,
106 subject: &SubjectId,
107) -> Result<bool, AppError> {
108 let dropped = sqlx::query!(
109 r#"DELETE FROM offering_subject
110 WHERE offering = $1 AND subject = $2"#,
111 offering.uuid(),
112 subject.uuid(),
113 )
114 .execute(db)
115 .await?;
116 Ok(dropped.rows_affected() > 0)
117}
118
119/// Add one topic to the section's own set, flipping `subjects_inherited` to
120/// FALSE **in the same statement** — the insert and the override switch are
121/// one data-modifying-CTE unit, so a reader can never see a class-owned row
122/// under a still-inheriting flag. Idempotent like the offering side: the
123/// second add of one topic writes no row (`added` = false) but the intent —
124/// "this section owns its set" — still stands, so the flip is unconditional
125/// on a live instance. `live` = false means the instance vanished mid-flight;
126/// the service answers that 404.
127pub async fn add_for_class_course(
128 db: &Database,
129 class_course: &ClassCourseId,
130 subject: &SubjectId,
131) -> Result<(bool, bool), AppError> {
132 let row = sqlx::query!(
133 r#"WITH flipped AS (
134 UPDATE class_course
135 SET subjects_inherited = FALSE
136 WHERE id = $1
137 RETURNING id
138 ), inserted AS (
139 INSERT INTO class_course_subject (class_course, subject)
140 SELECT $1, $2
141 WHERE EXISTS (SELECT 1 FROM flipped)
142 ON CONFLICT DO NOTHING
143 RETURNING subject
144 )
145 SELECT EXISTS (SELECT 1 FROM flipped) AS "live!",
146 EXISTS (SELECT 1 FROM inserted) AS "added!""#,
147 class_course.uuid(),
148 subject.uuid(),
149 )
150 .fetch_one(db)
151 .await
152 .map_err(gone)?;
153 Ok((row.live, row.added))
154}
155
156/// Drop one topic from the section's own set, flipping `subjects_inherited`
157/// to FALSE in the same statement — but **only when a row actually went**:
158/// a delete that finds nothing flips nothing, so the service can answer 404
159/// for a missing selection without a stray side effect on the flag. (`live`
160/// = false: the instance is gone mid-flight.)
161pub async fn remove_for_class_course(
162 db: &Database,
163 class_course: &ClassCourseId,
164 subject: &SubjectId,
165) -> Result<(bool, bool), AppError> {
166 let row = sqlx::query!(
167 r#"WITH dropped AS (
168 DELETE FROM class_course_subject
169 WHERE class_course = $1 AND subject = $2
170 RETURNING subject
171 ), flipped AS (
172 UPDATE class_course
173 SET subjects_inherited = FALSE
174 WHERE id = $1 AND EXISTS (SELECT 1 FROM dropped)
175 RETURNING id
176 )
177 SELECT EXISTS (SELECT 1 FROM flipped) AS "live!",
178 EXISTS (SELECT 1 FROM dropped) AS "dropped!""#,
179 class_course.uuid(),
180 subject.uuid(),
181 )
182 .fetch_one(db)
183 .await?;
184 Ok((row.live, row.dropped))
185}
186
187/// The reset door: sweep every class-owned row and flip
188/// `subjects_inherited` back to TRUE — one statement, so the set and its
189/// switch agree at every instant. The flip is unconditional on a live
190/// instance: clearing an already-empty own set is exactly the request that
191/// must restore inheritance. Answers the swept row count; `live` = false
192/// means the instance vanished mid-flight.
193pub async fn reset_for_class_course(
194 db: &Database,
195 class_course: &ClassCourseId,
196) -> Result<(i64, bool), AppError> {
197 let row = sqlx::query!(
198 r#"WITH swept AS (
199 DELETE FROM class_course_subject
200 WHERE class_course = $1
201 RETURNING subject
202 ), restored AS (
203 UPDATE class_course
204 SET subjects_inherited = TRUE
205 WHERE id = $1
206 RETURNING id
207 )
208 SELECT (SELECT count(*) FROM swept) AS "swept!: i64",
209 EXISTS (SELECT 1 FROM restored) AS "live!""#,
210 class_course.uuid(),
211 )
212 .fetch_one(db)
213 .await?;
214 Ok((row.swept, row.live))
215}
216
217/// The resolved-membership probe behind the exam-question/homework tag rewire:
218/// does `subject` sit in what this section *teaches* — its own rows while
219/// `subjects_inherited` is FALSE, else the offering's set? One statement, so
220/// the flag and the rows it reads agree as of one snapshot. `None` = the
221/// instance is gone.
222pub async fn resolves_for_class_course(
223 db: &Database,
224 class_course: &ClassCourseId,
225 subject: &SubjectId,
226) -> Result<Option<bool>, AppError> {
227 let row = sqlx::query!(
228 r#"SELECT CASE WHEN cc.subjects_inherited
229 THEN EXISTS (SELECT 1
230 FROM offering_subject os
231 WHERE os.offering = cc.offering AND os.subject = $2)
232 ELSE EXISTS (SELECT 1
233 FROM class_course_subject ccs
234 WHERE ccs.class_course = cc.id AND ccs.subject = $2)
235 END AS "member!"
236 FROM class_course cc
237 WHERE cc.id = $1"#,
238 class_course.uuid(),
239 subject.uuid(),
240 )
241 .fetch_optional(db)
242 .await?;
243 Ok(row.map(|row| row.member))
244}