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

course_offering.rs429 lines, 17.1 KiBHistoryRawDownload
1//! The `course_offering` table: the grade-level course template and the reads
2//! and writes behind `/offerings`. The row shape lives in
3//! [`crate::domain::course_offering`]; the workflows (the class-delivered
4//! gate, the duplicate refusal) in [`crate::service::course_offering`].
5//!
6//! One row per (course, grade_level) — the `UNIQUE` key the attach pump's
7//! auto-create races on: [`ensure_tx`] inserts `ON CONFLICT DO NOTHING` and
8//! reads the winner's id back, so two attaches landing together share one
9//! template whatever the interleaving was.
10//!
11//! Every content column is nullable by design — `NULL` means *inherit* (from
12//! the catalog course, or from the constants), never "missing". The update is
13//! field-scoped in the `set_or_clear` shape the other PATCH handlers speak:
14//! an absent field keeps its column, an explicit `null` clears back to
15//! inherit, a value sets the override.
16
17use sqlx::postgres::PgConnection;
18
19use crate::database::{Database, unique_violation};
20use crate::db::page::PagedList;
21use crate::domain::class_course::DersSaati;
22use crate::domain::course::{CourseDescription, CourseId, CourseTitle};
23use crate::domain::course_offering::{CourseOffering, CourseOfferingId};
24use crate::domain::grade::GradeLevel;
25use crate::domain::timestamp::Timestamp;
26use crate::domain::user::UserId;
27use crate::error::AppError;
28
29/// One offering as the *runtime* row decode sees it. Identical to
30/// [`CourseOffering`] except `default_ders_saati` stays the raw `SMALLINT`
31/// (`Option<i16>`): the runtime [`sqlx::FromRow`] path cannot name the
32/// `::bigint` cast the static `query_as!` projections use, and
33/// [`DersSaati`]'s transparent `i64` would refuse a `SMALLINT` at decode.
34/// [`OfferingRow::into_course_offering`] does the two-step conversions the
35/// column `CHECK`s already guarantee.
36#[derive(Debug, sqlx::FromRow)]
37struct OfferingRow {
38 id: CourseOfferingId,
39 course: CourseId,
40 grade_level: GradeLevel,
41 title: Option<CourseTitle>,
42 description: Option<CourseDescription>,
43 default_ders_saati: Option<i16>,
44 default_counts_toward_karne: Option<bool>,
45 created_by: UserId,
46 created_at: Timestamp,
47 updated_at: Timestamp,
48}
49
50impl OfferingRow {
51 fn into_course_offering(self) -> CourseOffering {
52 CourseOffering {
53 id: self.id,
54 course: self.course,
55 grade_level: self.grade_level,
56 title: self.title,
57 description: self.description,
58 default_ders_saati: self.default_ders_saati.map(|hours| {
59 DersSaati::try_new(i64::from(hours))
60 .expect("the column CHECK keeps the weekly hours between 1 and 40")
61 }),
62 default_counts_toward_karne: self.default_counts_toward_karne,
63 created_by: self.created_by,
64 created_at: self.created_at,
65 updated_at: self.updated_at,
66 }
67 }
68}
69
70/// One offering by id, or `None` when the id names no row.
71pub async fn read(db: &Database, id: &CourseOfferingId) -> Result<Option<CourseOffering>, AppError> {
72 let row = sqlx::query_as!(
73 CourseOffering,
74 r#"SELECT id AS "id: CourseOfferingId",
75 course AS "course: CourseId",
76 grade_level AS "grade_level: GradeLevel",
77 title AS "title?: CourseTitle",
78 description AS "description?: CourseDescription",
79 default_ders_saati::bigint AS "default_ders_saati?: DersSaati",
80 default_counts_toward_karne,
81 created_by AS "created_by: UserId",
82 created_at AS "created_at: Timestamp",
83 updated_at AS "updated_at: Timestamp"
84 FROM course_offering WHERE id = $1"#,
85 id.uuid(),
86 )
87 .fetch_optional(db)
88 .await?;
89 Ok(row)
90}
91
92/// Load every offering behind `ids` (one query) — the batch half of the
93/// resolved-content reads (`service::instance_resolve::resolved_content`),
94/// which map a page of instances onto their templates without an N+1.
95pub async fn list_by_ids(
96 db: &Database,
97 ids: &[CourseOfferingId],
98) -> Result<Vec<CourseOffering>, AppError> {
99 if ids.is_empty() {
100 return Ok(Vec::new());
101 }
102 let keys: Vec<uuid::Uuid> = ids.iter().map(CourseOfferingId::uuid).collect();
103 let rows = sqlx::query_as!(
104 CourseOffering,
105 r#"SELECT id AS "id: CourseOfferingId",
106 course AS "course: CourseId",
107 grade_level AS "grade_level: GradeLevel",
108 title AS "title?: CourseTitle",
109 description AS "description?: CourseDescription",
110 default_ders_saati::bigint AS "default_ders_saati?: DersSaati",
111 default_counts_toward_karne,
112 created_by AS "created_by: UserId",
113 created_at AS "created_at: Timestamp",
114 updated_at AS "updated_at: Timestamp"
115 FROM course_offering WHERE id = ANY($1)"#,
116 &keys,
117 )
118 .fetch_all(db)
119 .await?;
120 Ok(rows)
121}
122
123/// The offering a (course, grade_level) pair resolves to, or `None` when no
124/// template exists there yet — the read behind "what does this grade teach
125/// from" outside a pump transaction.
126pub async fn find(
127 db: &Database,
128 course: &CourseId,
129 grade: GradeLevel,
130) -> Result<Option<CourseOffering>, AppError> {
131 let row = sqlx::query_as!(
132 CourseOffering,
133 r#"SELECT id AS "id: CourseOfferingId",
134 course AS "course: CourseId",
135 grade_level AS "grade_level: GradeLevel",
136 title AS "title?: CourseTitle",
137 description AS "description?: CourseDescription",
138 default_ders_saati::bigint AS "default_ders_saati?: DersSaati",
139 default_counts_toward_karne,
140 created_by AS "created_by: UserId",
141 created_at AS "created_at: Timestamp",
142 updated_at AS "updated_at: Timestamp"
143 FROM course_offering WHERE course = $1 AND grade_level = $2"#,
144 course.uuid(),
145 grade.get(),
146 )
147 .fetch_optional(db)
148 .await?;
149 Ok(row)
150}
151
152/// The offerings, grade ladder first, paged via `limit`/`offset`; both
153/// filters are optional and combine. The page and its count share the same
154/// predicate ([`PagedList`]).
155pub async fn list(
156 db: &Database,
157 course: Option<&CourseId>,
158 grade: Option<GradeLevel>,
159 limit: Option<i64>,
160 offset: i64,
161) -> Result<(Vec<CourseOffering>, i64), AppError> {
162 let from_where = match (course, grade) {
163 (Some(_), Some(_)) => "course_offering WHERE course = $1 AND grade_level = $2",
164 (Some(_), None) => "course_offering WHERE course = $1",
165 (None, Some(_)) => "course_offering WHERE grade_level = $1",
166 (None, None) => "course_offering",
167 };
168 let mut page = PagedList::new(from_where, "ORDER BY grade_level, course");
169 if let Some(course) = course {
170 page = page.bind(course.uuid());
171 }
172 if let Some(grade) = grade {
173 page = page.bind(i64::from(grade.get()));
174 }
175 let (rows, total) = page.run::<OfferingRow>(limit, offset, db).await?;
176 Ok((
177 rows.into_iter()
178 .map(OfferingRow::into_course_offering)
179 .collect(),
180 total,
181 ))
182}
183
184/// Mint the template. The duplicate (course, grade_level) answer is a **409
185/// `offering_exists`**, not a store error: a manager creating the same
186/// template twice wants to be told it exists, and the attach pump's
187/// auto-create would have silently shared the row instead.
188#[allow(clippy::too_many_arguments)] // the offering row, spelled field by field
189pub async fn create(
190 db: &Database,
191 course: &CourseId,
192 grade: GradeLevel,
193 title: Option<CourseTitle>,
194 description: Option<CourseDescription>,
195 default_ders_saati: Option<DersSaati>,
196 default_counts_toward_karne: Option<bool>,
197 by: &UserId,
198) -> Result<CourseOffering, AppError> {
199 let now = Timestamp::now();
200 let title = title.map(|title| title.as_str().to_string());
201 let description = description.map(|d| d.as_str().to_string());
202 // An `i64` bound into a `SMALLINT` column: the assignment cast is the
203 // statement's own, and the newtype has already range-checked the value.
204 let hours = default_ders_saati.map(DersSaati::as_i64);
205 let row = sqlx::query_as!(
206 CourseOffering,
207 r#"INSERT INTO course_offering
208 (id, course, grade_level, title, description,
209 default_ders_saati, default_counts_toward_karne,
210 created_by, created_at, updated_at)
211 VALUES ($1, $2, $3, $4, $5, $6::bigint, $7, $8, $9, $9)
212 RETURNING id AS "id: CourseOfferingId",
213 course AS "course: CourseId",
214 grade_level AS "grade_level: GradeLevel",
215 title AS "title?: CourseTitle",
216 description AS "description?: CourseDescription",
217 default_ders_saati::bigint AS "default_ders_saati?: DersSaati",
218 default_counts_toward_karne,
219 created_by AS "created_by: UserId",
220 created_at AS "created_at: Timestamp",
221 updated_at AS "updated_at: Timestamp""#,
222 CourseOfferingId::generate().uuid(),
223 course.uuid(),
224 grade.get(),
225 title,
226 description,
227 hours,
228 default_counts_toward_karne,
229 by.uuid(),
230 now.as_millis(),
231 )
232 .fetch_one(db)
233 .await
234 .map_err(|e| {
235 // The table carries exactly one `UNIQUE` constraint — the (course,
236 // grade_level) template key — so *any* unique violation here is the
237 // duplicate template, whatever Postgres named it.
238 if unique_violation(&e).is_some() {
239 AppError::ConflictCoded {
240 code: "offering_exists",
241 message: "this course already has an offering for this grade".into(),
242 }
243 } else {
244 e.into()
245 }
246 })?;
247 Ok(row)
248}
249
250/// Field-scoped PATCH in the `set_or_clear` shape: an absent field keeps its
251/// column, `Some(None)` clears back to inherit (`NULL`), `Some(Some(v))` sets
252/// the override. `updated_at` moves with every write that changes anything.
253/// An empty request writes nothing and reads the row back. `Err(NotFound)`
254/// when the offering is gone.
255pub async fn update(
256 db: &Database,
257 id: &CourseOfferingId,
258 title: Option<Option<CourseTitle>>,
259 description: Option<Option<CourseDescription>>,
260 default_ders_saati: Option<Option<DersSaati>>,
261 default_counts_toward_karne: Option<Option<bool>>,
262) -> Result<CourseOffering, AppError> {
263 if title.is_none()
264 && description.is_none()
265 && default_ders_saati.is_none()
266 && default_counts_toward_karne.is_none()
267 {
268 return read(db, id).await?.ok_or(AppError::NotFound);
269 }
270 // Present-flag + nullable-value pairs: the flag decides *whether* the
271 // column moves, the value decides to what (a typed `NULL` is the inherit
272 // state). The weekly hours ride the `::bigint` round-trip cast like every
273 // other `DersSaati` read, and the column `CHECK` re-checks the range at
274 // the store.
275 let title_present = title.is_some();
276 let title = title.flatten().map(|t| t.as_str().to_string());
277 let description_present = description.is_some();
278 let description = description.flatten().map(|d| d.as_str().to_string());
279 let hours_present = default_ders_saati.is_some();
280 let hours = default_ders_saati.flatten().map(DersSaati::as_i64);
281 let counts_present = default_counts_toward_karne.is_some();
282 let counts = default_counts_toward_karne.flatten();
283 let now = Timestamp::now();
284 let row = sqlx::query_as!(
285 CourseOffering,
286 r#"WITH updated AS (
287 UPDATE course_offering SET
288 title = CASE WHEN $2 THEN $3::text ELSE title END,
289 description = CASE WHEN $4 THEN $5::text ELSE description END,
290 default_ders_saati = CASE WHEN $6 THEN
291 COALESCE($7::bigint, default_ders_saati::bigint)::smallint
292 ELSE default_ders_saati END,
293 default_counts_toward_karne = CASE WHEN $8 THEN $9
294 ELSE default_counts_toward_karne END,
295 updated_at = $10
296 WHERE id = $1
297 RETURNING id, course, grade_level, title, description,
298 default_ders_saati, default_counts_toward_karne,
299 created_by, created_at, updated_at)
300 SELECT u.id AS "id: CourseOfferingId",
301 u.course AS "course: CourseId",
302 u.grade_level AS "grade_level: GradeLevel",
303 u.title AS "title?: CourseTitle",
304 u.description AS "description?: CourseDescription",
305 u.default_ders_saati::bigint AS "default_ders_saati?: DersSaati",
306 u.default_counts_toward_karne,
307 u.created_by AS "created_by: UserId",
308 u.created_at AS "created_at: Timestamp",
309 u.updated_at AS "updated_at: Timestamp"
310 FROM updated u"#,
311 id.uuid(),
312 title_present,
313 title,
314 description_present,
315 description,
316 hours_present,
317 hours,
318 counts_present,
319 counts,
320 now.as_millis(),
321 )
322 .fetch_optional(db)
323 .await?
324 .ok_or(AppError::NotFound)?;
325 Ok(row)
326}
327
328/// The offering's two defaults, straight off its row — `(default_ders_saati,
329/// default_counts_toward_karne)`, `None`s *included* (a `NULL` default is the
330/// inherit state, and the caller layers its own fallbacks on top). `None` when
331/// the id names no offering: the `RESTRICT` foreign key on `class_course`
332/// keeps every instance's offering alive, so a missing row is the honest 404
333/// the service turns into one, not a case to paper over.
334pub async fn defaults(
335 db: &Database,
336 id: &CourseOfferingId,
337) -> Result<Option<(Option<DersSaati>, Option<bool>)>, AppError> {
338 let row = sqlx::query!(
339 r#"SELECT default_ders_saati::bigint AS "default_ders_saati?: DersSaati",
340 default_counts_toward_karne
341 FROM course_offering WHERE id = $1"#,
342 id.uuid(),
343 )
344 .fetch_optional(db)
345 .await?;
346 Ok(row.map(|row| (row.default_ders_saati, row.default_counts_toward_karne)))
347}
348
349/// Delete the template — refused while any instance still teaches from it.
350/// The refusal is a **409 `offering_in_use`** (the foreign key's `RESTRICT`
351/// is the store's mirror of the same rule); a gone id is the usual 404. One
352/// conditional statement is the whole invariant, so a check-then-delete race
353/// cannot exist: the `NOT EXISTS` is judged on the row as it is *at the
354/// delete*.
355pub async fn delete(db: &Database, id: &CourseOfferingId) -> Result<(), AppError> {
356 let deleted = sqlx::query!(
357 r#"DELETE FROM course_offering
358 WHERE id = $1
359 AND NOT EXISTS (SELECT 1 FROM class_course cc WHERE cc.offering = $1)"#,
360 id.uuid(),
361 )
362 .execute(db)
363 .await?
364 .rows_affected();
365 if deleted > 0 {
366 return Ok(());
367 }
368 // Zero rows: in use, or already gone. The read tells the two apart.
369 let standing = sqlx::query_scalar!(
370 r#"SELECT 1 AS "one" FROM course_offering WHERE id = $1"#,
371 id.uuid()
372 )
373 .fetch_optional(db)
374 .await?
375 .is_some();
376 if standing {
377 Err(AppError::ConflictCoded {
378 code: "offering_in_use",
379 message:
380 "instances still teach this offering — detach the course from those classes first"
381 .into(),
382 })
383 } else {
384 Err(AppError::NotFound)
385 }
386}
387
388/// Resolve — or mint empty — the template a (course, grade_level) pair
389/// teaches from, inside the caller's transaction. The attach pump's helper:
390/// every instance insert needs its offering link, and an untouched grade
391/// mints an *empty* template (every content column `NULL`) so it inherits the
392/// catalog course until a manager fills it in. `created_by` is the actor
393/// whose attach asked.
394///
395/// The `ON CONFLICT DO NOTHING` + read-back pair is the race-closer: two
396/// attaches landing on the same (course, grade_level) together both insert,
397/// one wins, and the loser's read-back returns the winner's row — one
398/// template per pair, whatever the order was. The table's only `UNIQUE`
399/// constraint is that pair, so the bare `DO NOTHING` cannot swallow a
400/// different conflict.
401pub(crate) async fn ensure_tx(
402 tx: &mut PgConnection,
403 course: &CourseId,
404 grade: GradeLevel,
405 by: &UserId,
406) -> Result<CourseOfferingId, AppError> {
407 let now = Timestamp::now();
408 sqlx::query!(
409 r#"INSERT INTO course_offering (id, course, grade_level, created_by, created_at, updated_at)
410 VALUES ($1, $2, $3, $4, $5, $5)
411 ON CONFLICT DO NOTHING"#,
412 CourseOfferingId::generate().uuid(),
413 course.uuid(),
414 grade.get(),
415 by.uuid(),
416 now.as_millis(),
417 )
418 .execute(&mut *tx)
419 .await?;
420 let id = sqlx::query_scalar!(
421 r#"SELECT id AS "id: CourseOfferingId" FROM course_offering
422 WHERE course = $1 AND grade_level = $2"#,
423 course.uuid(),
424 grade.get(),
425 )
426 .fetch_one(&mut *tx)
427 .await?;
428 Ok(id)
429}