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_audience.rs157 lines, 5.9 KiBHistoryRawDownload
1//! The `exam_audience` junction: which instances one exam is announced to.
2//!
3//! Every exam is *owned* by exactly one instance — the `class_course` column
4//! on its own row — and [`crate::db::exam::insert_in`] writes that owner's
5//! audience row in the same transaction as the exam. The rows beyond it are
6//! the **shared exam**'s (D2): one exam announced to another section's instance,
7//! sat and graded once, standing in every addressed instance's marks and
8//! report card. Every exam read goes through this table
9//! ([`crate::db::exam::list_for_class_course`] and the marks reports' joins),
10//! so the audience set is the single answer to "which instances does this
11//! exam belong to" and the owner column is only the join's tie-break.
12//!
13//! The owner's row is never removed from here: [`crate::service::exam`]
14//! refuses that pair on both routes, and deleting the exam is what ends its
15//! audience — [`crate::db::exam::delete`] and the instance sweep each clear
16//! the rows in their own transaction. The audience a detach may *not* leave
17//! behind is the one pointing at the detaching instance: an exam owned by
18//! another instance would block the `class_course` delete with a `23503`, so
19//! [`crate::db::course::sweep_instance_subtree`] clears both directions.
20
21use crate::database::{Database, foreign_key_violation};
22use crate::domain::class_course::ClassCourseId;
23use crate::domain::class_group::ClassGroupId;
24use crate::domain::course::CourseId;
25use crate::domain::exam::ExamId;
26use crate::domain::user::UserId;
27use crate::error::AppError;
28
29/// One audience row, resolved to what a client needs to name it: the
30/// instance, the section it belongs to and the catalog course it teaches.
31#[derive(Debug, sqlx::FromRow)]
32pub struct Audience {
33 class_course: ClassCourseId,
34 class: ClassGroupId,
35 course: CourseId,
36}
37
38impl Audience {
39 /// The instance the exam is announced to.
40 pub fn get_instance(&self) -> &ClassCourseId {
41 &self.class_course
42 }
43
44 /// The section that instance belongs to.
45 pub fn get_class(&self) -> &ClassGroupId {
46 &self.class
47 }
48
49 /// The catalog course that instance teaches — the exam's own, by the
50 /// announcement's rule.
51 pub fn get_course(&self) -> &CourseId {
52 &self.course
53 }
54}
55
56/// Announce `exam` to `class_course`. An audience the exam already carries is
57/// success, not a refusal: the announcement is idempotent, exactly like a
58/// teacher assignment ([`crate::db::class_course_teacher::assign`]), and the
59/// route answers the resulting set either way.
60///
61/// Both foreign keys answer a gone parent with `NotFound`: an exam swept by a
62/// concurrent detach and an instance that never existed are the same answer
63/// to the caller, and neither may read as a `500`.
64pub async fn add(
65 db: &Database,
66 exam: &ExamId,
67 class_course: &ClassCourseId,
68) -> Result<(), AppError> {
69 match sqlx::query!(
70 r#"INSERT INTO exam_audience (exam, class_course) VALUES ($1, $2)
71 ON CONFLICT ON CONSTRAINT exam_audience_pk DO NOTHING"#,
72 exam.uuid(),
73 class_course.uuid(),
74 )
75 .execute(db)
76 .await
77 {
78 Ok(_) => Ok(()),
79 Err(e) if foreign_key_violation(&e) => Err(AppError::NotFound),
80 Err(e) => Err(e.into()),
81 }
82}
83
84/// Drop an audience row. `false` when the pair held none, so the web layer
85/// can answer 404 instead of pretending it removed one — the shape
86/// [`crate::db::class_course_teacher::unassign`] has.
87pub async fn remove(
88 db: &Database,
89 exam: &ExamId,
90 class_course: &ClassCourseId,
91) -> Result<bool, AppError> {
92 let deleted = sqlx::query!(
93 r#"DELETE FROM exam_audience WHERE exam = $1 AND class_course = $2"#,
94 exam.uuid(),
95 class_course.uuid(),
96 )
97 .execute(db)
98 .await?;
99 Ok(deleted.rows_affected() > 0)
100}
101
102/// Every instance `exam` is announced to, in the order they were announced —
103/// uuidv7 is creation order — the read behind `GET /exams/{id}/audience`.
104pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<Audience>, AppError> {
105 let rows = sqlx::query_as!(
106 Audience,
107 r#"SELECT a.class_course AS "class_course: ClassCourseId",
108 c.class AS "class: ClassGroupId",
109 c.course AS "course: CourseId"
110 FROM exam_audience a
111 JOIN class_course c ON c.id = a.class_course
112 WHERE a.exam = $1
113 ORDER BY a.class_course"#,
114 exam.uuid(),
115 )
116 .fetch_all(db)
117 .await?;
118 Ok(rows)
119}
120
121/// The exams addressed to one instance — the reverse read, for a caller that
122/// starts from the instance rather than the exam (`exam_audience`'s
123/// `class_course` index is the side it walks).
124pub async fn list_for_instance(
125 db: &Database,
126 class_course: &ClassCourseId,
127) -> Result<Vec<ExamId>, AppError> {
128 let rows = sqlx::query!(
129 r#"SELECT exam AS "exam: ExamId" FROM exam_audience
130 WHERE class_course = $1 ORDER BY exam"#,
131 class_course.uuid(),
132 )
133 .fetch_all(db)
134 .await?;
135 Ok(rows.into_iter().map(|row| row.exam).collect())
136}
137
138/// Whether `user` is enrolled in any instance `exam` is addressed to — the
139/// owner included, its audience row always standing.
140///
141/// The enrollment predicate the sitting and grading gates ask once one exam
142/// can be announced to several instances (D2): for an exam nobody was
143/// announced to this is the owner-only check those gates used to run, row for
144/// row, and for a shared exam it admits the addressed sections' students —
145/// who sit and are graded at their own instance exactly like the owner's.
146pub async fn enrolled(db: &Database, exam: &ExamId, user: &UserId) -> Result<bool, AppError> {
147 Ok(sqlx::query_scalar!(
148 r#"SELECT EXISTS(
149 SELECT 1 FROM exam_audience a
150 JOIN enrollment e ON e.class_course = a.class_course
151 WHERE a.exam = $1 AND e.app_user = $2) AS "enrolled!""#,
152 exam.uuid(),
153 user.uuid(),
154 )
155 .fetch_one(db)
156 .await?)
157}