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_teacher.rs139 lines, 4.9 KiBHistoryRawDownload
1//! The `class_course_teacher` junction: who teaches one instance.
2//!
3//! D6 moved teacher assignment off the catalog course and onto the instance —
4//! two sections teaching the same course may legitimately have different
5//! teachers — so this is the table every instance-membership gate reads
6//! ([`crate::service::class_course::ensure_instance_teacher`]) and the one the
7//! demotion sweep strips ([`crate::db::user::set_role_cascade`]).
8//!
9//! The shape is the `course_teacher` junction's, keyed on the instance:
10//! assignment is an idempotent `INSERT` whose `(class_course, teacher)` key
11//! answers a duplicate with `DO NOTHING`, so two requests naming the same
12//! teacher at once land one row.
13
14use crate::database::{Database, foreign_key_violation};
15use crate::domain::class_course::{ClassCourse, ClassCourseId};
16use crate::domain::user::UserId;
17use crate::error::AppError;
18
19use std::collections::HashMap;
20
21/// Assign `teacher` to teach this instance. `false` when they already did
22/// (assignment is idempotent, so a repeat is a no-op rather than an error);
23/// `Err(NotFound)` when the instance is gone — the same answer the caller's
24/// own read gives one instant earlier.
25pub async fn assign(
26 db: &Database,
27 instance: &ClassCourseId,
28 teacher: &UserId,
29) -> Result<bool, AppError> {
30 let written = match sqlx::query!(
31 r#"INSERT INTO class_course_teacher (class_course, teacher)
32 SELECT $1, $2 WHERE EXISTS (SELECT 1 FROM class_course WHERE id = $1)
33 ON CONFLICT DO NOTHING"#,
34 instance.uuid(),
35 teacher.uuid(),
36 )
37 .execute(db)
38 .await
39 {
40 Ok(result) => result.rows_affected(),
41 // The teacher row (or the instance) vanished mid-write: a foreign key
42 // answers, and a gone target is the `NotFound` the read below gives.
43 Err(e) if foreign_key_violation(&e) => return Err(AppError::NotFound),
44 Err(e) => return Err(e.into()),
45 };
46 if written == 0
47 && crate::db::class_course::class_of(db, instance)
48 .await?
49 .is_none()
50 {
51 // Zero rows and no instance: the conditional select matched nothing,
52 // rather than the pair already holding its row.
53 return Err(AppError::NotFound);
54 }
55 Ok(written > 0)
56}
57
58/// Drop `teacher` from this instance. `false` when they were not assigned to
59/// it, so the web layer can answer 404 instead of pretending it removed
60/// someone.
61pub async fn unassign(
62 db: &Database,
63 instance: &ClassCourseId,
64 teacher: &UserId,
65) -> Result<bool, AppError> {
66 let deleted = sqlx::query!(
67 r#"DELETE FROM class_course_teacher WHERE class_course = $1 AND teacher = $2"#,
68 instance.uuid(),
69 teacher.uuid(),
70 )
71 .execute(db)
72 .await?;
73 Ok(deleted.rows_affected() > 0)
74}
75
76/// Strip `user` from every instance they were assigned to — the sweep for a
77/// user demoted below `teacher`, who may no longer run anything.
78pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {
79 sqlx::query!(
80 r#"DELETE FROM class_course_teacher WHERE teacher = $1"#,
81 user.uuid(),
82 )
83 .execute(db)
84 .await?;
85 Ok(())
86}
87
88/// The teachers of one instance, by uuid — the read behind a single
89/// `/instances/{id}` response.
90pub async fn list_for_instance(
91 db: &Database,
92 instance: &ClassCourseId,
93) -> Result<Vec<UserId>, AppError> {
94 let rows = sqlx::query!(
95 r#"SELECT teacher AS "teacher: UserId" FROM class_course_teacher
96 WHERE class_course = $1 ORDER BY teacher"#,
97 instance.uuid(),
98 )
99 .fetch_all(db)
100 .await?;
101 Ok(rows.into_iter().map(|row| row.teacher).collect())
102}
103
104/// Assemble `(instance, teachers)` pairs out of a batch of instance reads:
105/// one `class_course_teacher` query for the whole batch, so a page of `n`
106/// instances costs one extra statement rather than `n`. An instance nobody is
107/// assigned to reads an empty list, the shape
108/// [`crate::db::course`]'s old `into_courses` gave a course.
109pub async fn into_instances(
110 db: &Database,
111 rows: Vec<ClassCourse>,
112) -> Result<Vec<(ClassCourse, Vec<UserId>)>, AppError> {
113 if rows.is_empty() {
114 return Ok(Vec::new());
115 }
116 let ids: Vec<uuid::Uuid> = rows.iter().map(|row| row.get_id().uuid()).collect();
117 let links = sqlx::query!(
118 r#"SELECT class_course AS "class_course: ClassCourseId", teacher AS "teacher: UserId"
119 FROM class_course_teacher WHERE class_course = ANY($1)
120 ORDER BY class_course, teacher"#,
121 &ids,
122 )
123 .fetch_all(db)
124 .await?;
125 let mut by_instance: HashMap<uuid::Uuid, Vec<UserId>> = HashMap::new();
126 for link in links {
127 by_instance
128 .entry(link.class_course.uuid())
129 .or_default()
130 .push(link.teacher);
131 }
132 Ok(rows
133 .into_iter()
134 .map(|row| {
135 let teachers = by_instance.remove(&row.get_id().uuid()).unwrap_or_default();
136 (row, teachers)
137 })
138 .collect())
139}