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

parent_link.rs83 lines, 2.8 KiBHistoryRawDownload
1//! The `parent_link` table: the composite-PK upsert, the existence probe,
2//! the per-parent listing, and the delete. The *decisions* over these rows
3//! — who may be tied, and which reads a live link grants — live in
4//! [`crate::service::parent_link`].
5
6use crate::database::Database;
7use crate::domain::parent_link::ParentLink;
8use crate::domain::user::UserId;
9use crate::error::AppError;
10use sqlx::query_as;
11
12pub async fn link(
13 db: &Database,
14 parent: &UserId,
15 student: &UserId,
16 linked_by: &UserId,
17) -> Result<ParentLink, AppError> {
18 // The pair is the primary key, so the upsert is one atomic statement —
19 // no find-then-insert race to lose, and a re-link restamps `linked_by`.
20 let link = query_as!(
21 ParentLink,
22 "INSERT INTO parent_link (parent, student, linked_by)
23 VALUES ($1, $2, $3)
24 ON CONFLICT (parent, student) DO UPDATE SET linked_by = $3
25 RETURNING parent AS \"parent: UserId\", student AS \"student: UserId\", \
26 linked_by AS \"linked_by: UserId\"",
27 parent.uuid(),
28 student.uuid(),
29 linked_by.uuid()
30 )
31 .fetch_one(db)
32 .await?;
33 Ok(link)
34}
35
36/// True iff a link row exists for the (parent, student) pair — the storage
37/// half of the grant. The live half (the student side still holding the
38/// role) is [`crate::service::parent_link::links_live`].
39pub async fn exists(db: &Database, parent: &UserId, student: &UserId) -> Result<bool, AppError> {
40 let row = sqlx::query!(
41 "SELECT EXISTS(SELECT 1 FROM parent_link WHERE parent = $1 AND student = $2) AS \"present!\"",
42 parent.uuid(),
43 student.uuid()
44 )
45 .fetch_one(db)
46 .await?;
47 Ok(row.present)
48}
49
50/// Every student `parent` observes. The composite key's text form ordered
51/// the old listing, which for one parent means the student ids — the same
52/// order on the natural key.
53pub async fn list_for_parent(db: &Database, parent: &UserId) -> Result<Vec<ParentLink>, AppError> {
54 let links = query_as!(
55 ParentLink,
56 "SELECT parent AS \"parent: UserId\", student AS \"student: UserId\", \
57 linked_by AS \"linked_by: UserId\" \
58 FROM parent_link WHERE parent = $1
59 ORDER BY student DESC",
60 parent.uuid()
61 )
62 .fetch_all(db)
63 .await?;
64 Ok(links)
65}
66
67pub async fn remove(
68 db: &Database,
69 parent: &UserId,
70 student: &UserId,
71) -> Result<Option<ParentLink>, AppError> {
72 let gone = query_as!(
73 ParentLink,
74 "DELETE FROM parent_link WHERE parent = $1 AND student = $2
75 RETURNING parent AS \"parent: UserId\", student AS \"student: UserId\", \
76 linked_by AS \"linked_by: UserId\"",
77 parent.uuid(),
78 student.uuid()
79 )
80 .fetch_optional(db)
81 .await?;
82 Ok(gone)
83}