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

menu_dish.rs251 lines, 10.3 KiBHistoryRawDownload
1//! The `menu_dish` table: the dishes on a menu — the guarded insert (the
2//! dish cap, enforced by the menu row's own lock), the field PATCH riding
3//! the menu's revision bump, the reads and listings, and the delete. The
4//! kitchen workflows live in [`crate::service::menu`].
5
6use crate::database::{Database, tx_with_retry};
7use crate::domain::menu::MenuId;
8use crate::domain::menu_dish::{
9 DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId,
10};
11use crate::domain::timestamp::Timestamp;
12use crate::error::AppError;
13
14/// Add a dish. The dish cap is one guarded decision, not a count a caller
15/// took a moment earlier: the menu row is locked `FOR NO KEY UPDATE` in
16/// this write's own transaction and the `INSERT` runs with a
17/// `count(*) < $cap` guard — a writer that queued on the lock behind a
18/// concurrent one re-counts after it and is refused (`409`) instead of
19/// overfilling. The revision bump rides the same transaction, and the
20/// lock's `SELECT` is what makes the menu's **existence** part of the
21/// write: it matches nothing once the menu row is deleted, so `NotFound`
22/// means the dish was not written.
23pub async fn create(
24 db: &Database,
25 menu: &MenuId,
26 name: DishName,
27 description: Option<DishDescription>,
28 price_minor: DishPrice,
29 tags: DishTags,
30 cap: i64,
31) -> Result<MenuDish, AppError> {
32 let menu_key = menu.key().to_string();
33 let id = MenuDishId::generate();
34 let created_at = Timestamp::now();
35 tx_with_retry(db, false, async move |tx| {
36 // The lock first: every later statement in this transaction then
37 // sees the committed state of whoever queued ahead of it.
38 let locked = sqlx::query!(
39 "SELECT 1 AS locked FROM menu WHERE id = $1 FOR NO KEY UPDATE",
40 menu_key,
41 )
42 .fetch_optional(&mut *tx)
43 .await?;
44 if locked.is_none() {
45 return Err(AppError::NotFound);
46 }
47 sqlx::query!(
48 "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1",
49 menu_key,
50 )
51 .execute(&mut *tx)
52 .await?;
53 let placed = sqlx::query!(
54 "INSERT INTO menu_dish (id, menu, name, description, price_minor, created_at)
55 SELECT $1, $2, $3, $4, $5, $6
56 WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $7",
57 id.uuid(),
58 menu_key,
59 name.as_str(),
60 description.as_ref().map(|d| d.as_str()),
61 price_minor.as_minor(),
62 created_at.as_millis(),
63 cap,
64 )
65 .execute(&mut *tx)
66 .await?;
67 if placed.rows_affected() == 0 {
68 // The menu exists (locked above), so an empty result is the cap.
69 return Err(AppError::Conflict(
70 "the menu already carries the maximum number of dishes",
71 ));
72 }
73 // The tags are child rows: one per tag, `ord` carrying the order
74 // the caller gave the list in (already deduplicated by DishTags).
75 sqlx::query!(
76 "INSERT INTO menu_dish_tag (dish, tag, ord)
77 SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)",
78 id.uuid(),
79 tags.as_slice(),
80 )
81 .execute(&mut *tx)
82 .await?;
83 let row = sqlx::query_as!(
84 MenuDish,
85 "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",
86 COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",
87 created_at AS \"created_at: Timestamp\"
88 FROM menu_dish WHERE id = $1",
89 id.uuid(),
90 )
91 .fetch_one(&mut *tx)
92 .await?;
93 Ok(row)
94 })
95 .await
96}
97
98pub async fn read(db: &Database, id: &MenuDishId) -> Result<Option<MenuDish>, AppError> {
99 let row = sqlx::query_as!(
100 MenuDish,
101 "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",
102 COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",
103 created_at AS \"created_at: Timestamp\"
104 FROM menu_dish WHERE id = $1",
105 id.uuid(),
106 )
107 .fetch_optional(db)
108 .await?;
109 Ok(row)
110}
111
112/// Every dish on one menu, in the order they were added.
113pub async fn list_for_menu(db: &Database, menu: &MenuId) -> Result<Vec<MenuDish>, AppError> {
114 list_for_menus(db, std::slice::from_ref(menu)).await
115}
116
117/// Dishes for a whole page of menus in one round trip — the alternative is
118/// a query per menu, which is the N+1 the pagination slice exists to avoid.
119pub async fn list_for_menus(db: &Database, menus: &[MenuId]) -> Result<Vec<MenuDish>, AppError> {
120 if menus.is_empty() {
121 return Ok(Vec::new());
122 }
123 let keys: Vec<String> = menus.iter().map(|m| m.key().to_string()).collect();
124 let rows = sqlx::query_as!(
125 MenuDish,
126 "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",
127 COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",
128 created_at AS \"created_at: Timestamp\"
129 FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC",
130 &keys,
131 )
132 .fetch_all(db)
133 .await?;
134 Ok(rows)
135}
136
137/// Write only the fields the PATCH carried. `description` is nullable, so
138/// it takes the three-way shape: absent = keep, `Some(None)` = clear.
139/// Each field is spelled with a "was it on the request?" flag and its
140/// nullable value, so an omitted field is never written and a concurrent
141/// PATCH of another one is not reverted.
142///
143/// The revision bump lands in the same transaction — "every dish write
144/// bumps" is the rule a caller can rely on without knowing which fields
145/// were on the wire. A PATCH that carried nothing still bumps and reads
146/// the row back.
147pub async fn update(
148 db: &Database,
149 dish: MenuDish,
150 name: Option<DishName>,
151 description: Option<Option<DishDescription>>,
152 price_minor: Option<DishPrice>,
153 tags: Option<DishTags>,
154) -> Result<MenuDish, AppError> {
155 let dish_key = dish.id.uuid();
156 let menu_key = dish.menu.key().to_string();
157 tx_with_retry(db, false, async move |tx| {
158 let bumped = sqlx::query!(
159 "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1
160 RETURNING 1 AS bumped",
161 menu_key,
162 )
163 .fetch_optional(&mut *tx)
164 .await?;
165 if bumped.is_none() {
166 return Err(AppError::NotFound);
167 }
168 let updated = sqlx::query!(
169 "UPDATE menu_dish SET
170 name = COALESCE($2, name),
171 description = CASE WHEN $3 THEN $4 ELSE description END,
172 price_minor = COALESCE($5, price_minor)
173 WHERE id = $1",
174 dish_key,
175 name.as_ref().map(|n| n.as_str()),
176 description.is_some(),
177 description.as_ref().and_then(|d| d.as_ref()).map(|d| d.as_str()),
178 price_minor.map(DishPrice::as_minor),
179 )
180 .execute(&mut *tx)
181 .await?;
182 if updated.rows_affected() == 0 {
183 return Err(AppError::NotFound);
184 }
185 // The tags are child rows now: an absent field keeps the stored
186 // ones, a carried field replaces the whole set (an empty list
187 // clears it) — under the same transaction as the bump above.
188 if let Some(tags) = &tags {
189 sqlx::query!("DELETE FROM menu_dish_tag WHERE dish = $1", dish_key)
190 .execute(&mut *tx)
191 .await?;
192 sqlx::query!(
193 "INSERT INTO menu_dish_tag (dish, tag, ord)
194 SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)",
195 dish_key,
196 tags.as_slice(),
197 )
198 .execute(&mut *tx)
199 .await?;
200 }
201 let row = sqlx::query_as!(
202 MenuDish,
203 "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",
204 COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",
205 created_at AS \"created_at: Timestamp\"
206 FROM menu_dish WHERE id = $1",
207 dish_key,
208 )
209 .fetch_one(&mut *tx)
210 .await?;
211 Ok(row)
212 })
213 .await
214}
215
216pub async fn delete(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError> {
217 let dish_key = dish.id.uuid();
218 let menu_key = dish.menu.key().to_string();
219 tx_with_retry(db, false, async move |tx| {
220 let bumped = sqlx::query!(
221 "UPDATE menu SET version = COALESCE(version, 0) + 1 WHERE id = $1
222 RETURNING 1 AS bumped",
223 menu_key,
224 )
225 .fetch_optional(&mut *tx)
226 .await?;
227 if bumped.is_none() {
228 return Err(AppError::NotFound);
229 }
230 let row = sqlx::query_as!(
231 MenuDish,
232 "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",
233 COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",
234 created_at AS \"created_at: Timestamp\"
235 FROM menu_dish WHERE id = $1",
236 dish_key,
237 )
238 .fetch_optional(&mut *tx)
239 .await?;
240 let dish = row.ok_or(AppError::NotFound)?;
241 // The tag rows go first: `menu_dish_tag.dish` is NO ACTION too.
242 sqlx::query!("DELETE FROM menu_dish_tag WHERE dish = $1", dish_key)
243 .execute(&mut *tx)
244 .await?;
245 sqlx::query!("DELETE FROM menu_dish WHERE id = $1", dish_key)
246 .execute(&mut *tx)
247 .await?;
248 Ok(dish)
249 })
250 .await
251}