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

holiday.rs160 lines, 5.7 KiBHistoryRawDownload
1//! The `holiday` table: the row mint, the read, the field-scoped PATCH whose
2//! `WHERE` re-checks the merged range, the delete, and the two listings — a
3//! paged calendar view and the materializer's overlap read. The type lives in
4//! [`crate::domain::holiday`].
5
6use crate::constant::HOLIDAY_TABLE;
7use crate::database::Database;
8use crate::db::field_update::FieldUpdate;
9use crate::db::page::{Param, PagedList};
10use crate::domain::holiday::{Holiday, HolidayId, HolidayKind, HolidayName};
11use crate::domain::timestamp::{Timestamp, range_error};
12use crate::domain::user::UserId;
13use crate::error::AppError;
14
15/// A PATCH of one holiday row: only the fields the request carried are
16/// written, `None` = omitted = keep.
17#[derive(Debug, Clone, Default)]
18pub struct HolidayPatch {
19 pub name: Option<HolidayName>,
20 pub starts_at: Option<Timestamp>,
21 pub ends_at: Option<Timestamp>,
22 pub kind: Option<HolidayKind>,
23}
24
25pub async fn create(
26 db: &Database,
27 name: &HolidayName,
28 starts_at: Timestamp,
29 ends_at: Timestamp,
30 kind: &HolidayKind,
31 creator: &UserId,
32) -> Result<Holiday, AppError> {
33 let holiday = Holiday {
34 id: HolidayId::generate(),
35 name: name.clone(),
36 starts_at,
37 ends_at,
38 kind: kind.clone(),
39 creator: *creator,
40 created_at: Timestamp::now(),
41 };
42 let created = sqlx::query_as!(
43 Holiday,
44 r#"INSERT INTO holiday (id, name, starts_at, ends_at, kind, creator, created_at)
45 VALUES ($1, $2, $3, $4, $5, $6, $7)
46 RETURNING id AS "id: HolidayId", name AS "name: HolidayName",
47 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
48 kind AS "kind: HolidayKind", creator AS "creator: UserId",
49 created_at AS "created_at: Timestamp""#,
50 holiday.id.uuid(),
51 holiday.name.as_str(),
52 holiday.starts_at.as_millis(),
53 holiday.ends_at.as_millis(),
54 holiday.kind.as_str(),
55 holiday.creator.uuid(),
56 holiday.created_at.as_millis(),
57 )
58 .fetch_one(db)
59 .await?;
60 Ok(created)
61}
62
63/// The holiday `id` names, or `Err(NotFound)` when absent.
64pub async fn read(db: &Database, id: &HolidayId) -> Result<Holiday, AppError> {
65 sqlx::query_as!(
66 Holiday,
67 r#"SELECT id AS "id: HolidayId", name AS "name: HolidayName",
68 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
69 kind AS "kind: HolidayKind", creator AS "creator: UserId",
70 created_at AS "created_at: Timestamp"
71 FROM holiday WHERE id = $1"#,
72 id.uuid(),
73 )
74 .fetch_optional(db)
75 .await?
76 .ok_or(AppError::NotFound)
77}
78
79/// Write only the fields the PATCH carried, and re-check the merged
80/// `starts_at <= ends_at` in the `UPDATE`'s own `WHERE` — two PATCHes each
81/// moving one end of the range cannot commit an inverted holiday between
82/// them.
83pub async fn update(
84 db: &Database,
85 id: &HolidayId,
86 patch: HolidayPatch,
87) -> Result<Holiday, AppError> {
88 FieldUpdate::new(HOLIDAY_TABLE, id.uuid())
89 .set("name", patch.name.map(|name| name.as_str().to_owned()))
90 .set("starts_at", patch.starts_at.map(|at| at.as_millis()))
91 .set("ends_at", patch.ends_at.map(|at| at.as_millis()))
92 .set("kind", patch.kind.map(|kind| kind.as_str().to_owned()))
93 .ordered("starts_at", "ends_at", range_error())
94 .run::<Holiday>(db)
95 .await
96}
97
98/// Delete the holiday. A holiday is referenced by nothing — the materializer
99/// only *reads* it — so nothing can refuse the delete but its own absence.
100pub async fn delete(db: &Database, id: &HolidayId) -> Result<Holiday, AppError> {
101 let deleted = sqlx::query_as!(
102 Holiday,
103 r#"DELETE FROM holiday WHERE id = $1
104 RETURNING id AS "id: HolidayId", name AS "name: HolidayName",
105 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
106 kind AS "kind: HolidayKind", creator AS "creator: UserId",
107 created_at AS "created_at: Timestamp""#,
108 id.uuid(),
109 )
110 .fetch_optional(db)
111 .await?;
112 deleted.ok_or(AppError::NotFound)
113}
114
115/// Holidays, newest start first, paged. `from`/`to` are inclusive bounds with
116/// overlap semantics — a holiday is listed when it *reaches into* the range,
117/// not only when it lies inside it.
118pub async fn list(
119 db: &Database,
120 from: Option<Timestamp>,
121 to: Option<Timestamp>,
122 limit: Option<i64>,
123 offset: i64,
124) -> Result<(Vec<Holiday>, i64), AppError> {
125 PagedList::new(
126 format!(
127 "{HOLIDAY_TABLE} WHERE ($1::bigint IS NULL OR ends_at >= $1) \
128 AND ($2::bigint IS NULL OR starts_at <= $2)"
129 ),
130 "ORDER BY starts_at DESC, id DESC",
131 )
132 .bind(Param::OptI64(from.map(|at| at.as_millis())))
133 .bind(Param::OptI64(to.map(|at| at.as_millis())))
134 .run::<Holiday>(limit, offset, db)
135 .await
136}
137
138/// Every holiday reaching into `[from, to]`, unpaged, earliest first — the
139/// materializer's read. Same overlap semantics as [`list`].
140pub async fn list_between(
141 db: &Database,
142 from: Timestamp,
143 to: Timestamp,
144) -> Result<Vec<Holiday>, AppError> {
145 let rows = sqlx::query_as!(
146 Holiday,
147 r#"SELECT id AS "id: HolidayId", name AS "name: HolidayName",
148 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
149 kind AS "kind: HolidayKind", creator AS "creator: UserId",
150 created_at AS "created_at: Timestamp"
151 FROM holiday
152 WHERE ends_at >= $1 AND starts_at <= $2
153 ORDER BY starts_at"#,
154 from.as_millis(),
155 to.as_millis(),
156 )
157 .fetch_all(db)
158 .await?;
159 Ok(rows)
160}