Skip to main content

kanban_persistence_sqlite/sqlite_store/
data_store.rs

1use chrono::{DateTime, Utc};
2use kanban_domain::data_store::DataStore;
3use kanban_domain::{
4    Archived, ArchivedBoard, ArchivedCard, Board, Card, Column, DependencyGraph, KanbanResult,
5    Sprint,
6};
7use sqlx::Row;
8use uuid::Uuid;
9
10use super::conversions::{
11    row_to_archived_card, row_to_board, row_to_card, row_to_column, row_to_sprint,
12};
13use super::helpers::{db_err, fmt_dt, p_dt, run};
14use super::SqliteStore;
15
16impl DataStore for SqliteStore {
17    // Prefix
18
19    fn get_prefix(&self, name: &str) -> KanbanResult<Option<kanban_domain::Prefix>> {
20        // `prefixes.name` is `COLLATE NOCASE`, so `=` already matches
21        // case-insensitively at the schema level. Normalising the probe as
22        // well keeps this agreeing with the in-memory store, whose comparison
23        // is the only one on the JSON path.
24        let wanted = kanban_domain::Prefix::normalize(name);
25        run(self.db_conn(|conn| {
26            Box::pin(async move {
27                let row: Option<(String, i64, i64)> = sqlx::query_as(
28                    "SELECT name, card_counter, sprint_counter FROM prefixes WHERE name = ?",
29                )
30                .bind(wanted)
31                .fetch_optional(&mut *conn)
32                .await
33                .map_err(db_err)?;
34                Ok(row.map(
35                    |(name, card_counter, sprint_counter)| kanban_domain::Prefix {
36                        name,
37                        card_counter: card_counter as u32,
38                        sprint_counter: sprint_counter as u32,
39                    },
40                ))
41            })
42        }))
43    }
44
45    fn list_prefixes(&self) -> KanbanResult<Vec<kanban_domain::Prefix>> {
46        run(self.db_conn(|conn| {
47            Box::pin(async move {
48                let rows: Vec<(String, i64, i64)> = sqlx::query_as(
49                    "SELECT name, card_counter, sprint_counter FROM prefixes ORDER BY name ASC",
50                )
51                .fetch_all(&mut *conn)
52                .await
53                .map_err(db_err)?;
54                Ok(rows
55                    .into_iter()
56                    .map(
57                        |(name, card_counter, sprint_counter)| kanban_domain::Prefix {
58                            name,
59                            card_counter: card_counter as u32,
60                            sprint_counter: sprint_counter as u32,
61                        },
62                    )
63                    .collect())
64            })
65        }))
66    }
67
68    fn upsert_prefix(&self, prefix: kanban_domain::Prefix) -> KanbanResult<()> {
69        let name = kanban_domain::Prefix::normalize(&prefix.name);
70        let card_counter = prefix.card_counter as i64;
71        let sprint_counter = prefix.sprint_counter as i64;
72        run(self.db_conn(move |conn| {
73            Box::pin(async move {
74                sqlx::query(
75                    "INSERT INTO prefixes (name, card_counter, sprint_counter)
76                     VALUES (?, ?, ?)
77                     ON CONFLICT(name) DO UPDATE SET
78                         card_counter = excluded.card_counter,
79                         sprint_counter = excluded.sprint_counter",
80                )
81                .bind(name)
82                .bind(card_counter)
83                .bind(sprint_counter)
84                .execute(&mut *conn)
85                .await
86                .map_err(db_err)?;
87                Ok(())
88            })
89        }))
90    }
91
92    // Board
93
94    fn get_board(&self, id: Uuid) -> KanbanResult<Option<Board>> {
95        run(self.db_conn(|conn| {
96            Box::pin(async move {
97                let id_str = id.to_string();
98                // Reference-marker model: `get_board` is UNFILTERED — it returns the
99                // head whether the board is live OR archived (an `archived_board`
100                // marker hides it only from the LIVE `list_boards`). Callers
101                // discriminate archived-ness via `get_archived_board`.
102                let row = sqlx::query(
103                    "SELECT id, name, description, sprint_prefix, card_prefix, task_sort_field,
104                            task_sort_order, sprint_duration_days, sprint_name_used_count,
105                            next_sprint_number, active_sprint_id, task_list_view,
106                            position, created_at, updated_at
107                     FROM boards
108                     WHERE id = ?",
109                )
110                .bind(&id_str)
111                .fetch_optional(&mut *conn)
112                .await
113                .map_err(db_err)?;
114
115                match row {
116                    Some(row) => {
117                        let names = SqliteStore::fetch_board_aux_with_conn(conn, &id_str).await?;
118                        Ok(Some(row_to_board(&row, names)?))
119                    }
120                    None => Ok(None),
121                }
122            })
123        }))
124    }
125
126    fn list_boards(&self) -> KanbanResult<Vec<Board>> {
127        run(self.list_boards_async())
128    }
129
130    fn upsert_board(&self, board: Board) -> KanbanResult<()> {
131        run(self.write_board_async(&board))
132    }
133
134    fn delete_board(&self, id: Uuid) -> KanbanResult<()> {
135        run(self.db_conn(|conn| {
136            Box::pin(async move {
137                sqlx::query(
138                    "DELETE FROM boards
139                     WHERE id = ?
140                       AND NOT EXISTS (SELECT 1 FROM board_archival ba WHERE ba.board_id = boards.id)",
141                )
142                .bind(id.to_string())
143                .execute(&mut *conn)
144                .await
145                .map_err(db_err)?;
146                Ok(())
147            })
148        }))
149    }
150
151    // Column
152
153    fn get_column(&self, id: Uuid) -> KanbanResult<Option<Column>> {
154        run(self.db_conn(|conn| {
155            Box::pin(async move {
156                let row = sqlx::query(
157                    "SELECT id, board_id, name, position, wip_limit, default_status, created_at, updated_at
158                     FROM columns WHERE id = ?",
159                )
160                .bind(id.to_string())
161                .fetch_optional(&mut *conn)
162                .await
163                .map_err(db_err)?;
164                row.as_ref().map(row_to_column).transpose()
165            })
166        }))
167    }
168
169    fn list_columns_by_board(&self, board_id: Uuid) -> KanbanResult<Vec<Column>> {
170        run(self.db_conn(|conn| {
171            Box::pin(async move {
172                let rows = sqlx::query(
173                    "SELECT id, board_id, name, position, wip_limit, default_status, created_at, updated_at
174                     FROM columns WHERE board_id = ?
175                     ORDER BY position ASC, created_at ASC, id ASC",
176                )
177                .bind(board_id.to_string())
178                .fetch_all(&mut *conn)
179                .await
180                .map_err(db_err)?;
181                rows.iter().map(row_to_column).collect()
182            })
183        }))
184    }
185
186    fn list_all_columns(&self) -> KanbanResult<Vec<Column>> {
187        run(self.list_all_columns_async())
188    }
189
190    fn upsert_column(&self, column: Column) -> KanbanResult<()> {
191        run(self.write_column_async(&column))
192    }
193
194    fn delete_column(&self, id: Uuid) -> KanbanResult<()> {
195        run(self.db_conn(|conn| {
196            Box::pin(async move {
197                sqlx::query("DELETE FROM columns WHERE id = ?")
198                    .bind(id.to_string())
199                    .execute(&mut *conn)
200                    .await
201                    .map_err(db_err)?;
202                Ok(())
203            })
204        }))
205    }
206
207    fn delete_columns_by_board(&self, board_id: Uuid) -> KanbanResult<()> {
208        run(self.db_conn(|conn| {
209            Box::pin(async move {
210                sqlx::query("DELETE FROM columns WHERE board_id = ?")
211                    .bind(board_id.to_string())
212                    .execute(&mut *conn)
213                    .await
214                    .map_err(db_err)?;
215                Ok(())
216            })
217        }))
218    }
219
220    // Card
221
222    fn get_card(&self, id: Uuid) -> KanbanResult<Option<Card>> {
223        run(self.db_conn(|conn| {
224            Box::pin(async move {
225                let id_str = id.to_string();
226                // F1 (KAN-870): get_card is UNFILTERED — an archived card stays in
227                // `cards` behind a marker and is reachable by id (it is an ordinary,
228                // editable card). The archived/live distinction is a LIST-level filter.
229                let row = sqlx::query(
230                    "SELECT id, column_id, board_id, title, description, priority, status, position,
231                            due_date, points, card_number, prefix, sprint_id, created_at,
232                            updated_at, completed_at
233                     FROM cards
234                     WHERE id = ?",
235                )
236                .bind(&id_str)
237                .fetch_optional(&mut *conn)
238                .await
239                .map_err(db_err)?;
240
241                match row {
242                    Some(row) => {
243                        let logs = SqliteStore::fetch_sprint_logs_for_card_with_conn(conn, &id_str)
244                            .await?;
245                        Ok(Some(row_to_card(&row, logs)?))
246                    }
247                    None => Ok(None),
248                }
249            })
250        }))
251    }
252
253    fn list_all_cards(&self) -> KanbanResult<Vec<Card>> {
254        run(self.fetch_cards_with_filter("", vec![]))
255    }
256
257    fn list_cards_by_column(&self, column_id: Uuid) -> KanbanResult<Vec<Card>> {
258        run(self.fetch_cards_with_filter("AND column_id = ?", vec![column_id.to_string()]))
259    }
260
261    fn list_cards_by_columns(&self, column_ids: &[Uuid]) -> KanbanResult<Vec<Card>> {
262        if column_ids.is_empty() {
263            return Ok(Vec::new());
264        }
265        let placeholders = column_ids.iter().map(|_| "?").collect::<Vec<_>>().join(",");
266        let where_clause = format!("AND column_id IN ({placeholders})");
267        let binds: Vec<String> = column_ids.iter().map(|id| id.to_string()).collect();
268        run(self.fetch_cards_with_filter(where_clause, binds))
269    }
270
271    fn list_cards_by_sprint(&self, sprint_id: Uuid) -> KanbanResult<Vec<Card>> {
272        run(self.fetch_cards_with_filter("AND sprint_id = ?", vec![sprint_id.to_string()]))
273    }
274
275    fn list_cards_by_prefix_and_number(
276        &self,
277        prefix: &str,
278        card_number: u32,
279    ) -> KanbanResult<Vec<Card>> {
280        // Indexed by idx_cards_prefix_nocase_number. The COLLATE must match the
281        // index's, or SQLite scans instead.
282        run(self.fetch_cards_with_filter(
283            "AND prefix = ? COLLATE NOCASE AND card_number = ?",
284            vec![
285                kanban_domain::Prefix::normalize(prefix),
286                card_number.to_string(),
287            ],
288        ))
289    }
290
291    fn list_cards_by_number(&self, card_number: u32) -> KanbanResult<Vec<Card>> {
292        // Indexed by idx_cards_number.
293        run(self.fetch_cards_with_filter("AND card_number = ?", vec![card_number.to_string()]))
294    }
295
296    fn get_card_by_board_and_number(
297        &self,
298        board_id: Uuid,
299        card_number: u32,
300    ) -> KanbanResult<Option<Card>> {
301        let cards = run(self.fetch_cards_with_filter(
302            "AND board_id = ? AND card_number = ?",
303            vec![board_id.to_string(), card_number.to_string()],
304        ))?;
305        Ok(cards.into_iter().next())
306    }
307
308    fn get_card_by_sprint_and_number(
309        &self,
310        sprint_id: Uuid,
311        card_number: u32,
312    ) -> KanbanResult<Option<Card>> {
313        let cards = run(self.fetch_cards_with_filter(
314            "AND sprint_id = ? AND card_number = ?",
315            vec![sprint_id.to_string(), card_number.to_string()],
316        ))?;
317        Ok(cards.into_iter().next())
318    }
319
320    /// 3-state archived-aware column read. Overrides the loud-floor default so
321    /// SQLite honours `ArchivedOnly`/`Include`; `LiveOnly` stays byte-identical
322    /// to `list_cards_by_column` (same `NOT EXISTS` base clause).
323    fn list_cards_by_column_filtered(
324        &self,
325        column_id: Uuid,
326        archived: kanban_domain::ArchivedFilter,
327    ) -> KanbanResult<Vec<Card>> {
328        run(self.fetch_cards_in_column_filtered(&column_id.to_string(), archived))
329    }
330
331    fn count_cards_in_column(&self, column_id: Uuid) -> KanbanResult<usize> {
332        run(self.db_conn(|conn| {
333            Box::pin(async move {
334                let column_id = column_id.to_string();
335                SqliteStore::count_cards_in_column_with_conn(conn, &column_id).await
336            })
337        }))
338    }
339
340    /// 3-state archived-aware column count. Mirrors
341    /// `list_cards_by_column_filtered`: `LiveOnly` matches `count_cards_in_column`
342    /// exactly, `ArchivedOnly`/`Include` are served via the archived base clause.
343    fn count_cards_in_column_filtered(
344        &self,
345        column_id: Uuid,
346        archived: kanban_domain::ArchivedFilter,
347    ) -> KanbanResult<usize> {
348        run(self.count_cards_in_column_filtered_impl(&column_id.to_string(), archived))
349    }
350
351    fn count_cards_in_column_excluding(
352        &self,
353        column_id: Uuid,
354        exclude: &[Uuid],
355    ) -> KanbanResult<usize> {
356        let exclude: Vec<Uuid> = exclude.to_vec();
357        run(self.db_conn(move |conn| {
358            Box::pin(async move {
359                let column_id_str = column_id.to_string();
360                if exclude.is_empty() {
361                    // Associated fn on the already-held conn — calling
362                    // `self.count_cards_in_column` here would capture `self`
363                    // and violate db_conn's CAPTURE RULE.
364                    return SqliteStore::count_cards_in_column_with_conn(conn, &column_id_str)
365                        .await;
366                }
367                let placeholders = exclude.iter().map(|_| "?").collect::<Vec<_>>().join(",");
368                let sql = format!(
369                    "SELECT COUNT(*) as cnt FROM cards
370                     WHERE column_id = ?
371                       AND NOT EXISTS (SELECT 1 FROM archived_cards a WHERE a.card_id = cards.id)
372                       AND id NOT IN ({placeholders})"
373                );
374                let mut query = sqlx::query(&sql).bind(&column_id_str);
375                for id in &exclude {
376                    query = query.bind(id.to_string());
377                }
378                let row = query.fetch_one(&mut *conn).await.map_err(db_err)?;
379                Ok(row.try_get::<i32, _>("cnt").map_err(db_err)? as usize)
380            })
381        }))
382    }
383
384    fn upsert_card(&self, card: Card) -> KanbanResult<()> {
385        run(self.write_card_async(&card))
386    }
387
388    fn delete_card(&self, id: Uuid) -> KanbanResult<()> {
389        run(self.db_conn(|conn| {
390            Box::pin(async move {
391                sqlx::query(
392                    "DELETE FROM cards
393                     WHERE id = ? AND NOT EXISTS (SELECT 1 FROM archived_cards a WHERE a.card_id = cards.id)",
394                )
395                .bind(id.to_string())
396                .execute(&mut *conn)
397                .await
398                .map_err(db_err)?;
399                Ok(())
400            })
401        }))
402    }
403
404    fn delete_cards_by_columns(&self, column_ids: &[Uuid]) -> KanbanResult<()> {
405        let column_ids: Vec<Uuid> = column_ids.to_vec();
406        run(self.db_conn(move |conn| {
407            Box::pin(async move {
408                if column_ids.is_empty() {
409                    return Ok(());
410                }
411                let placeholders = column_ids.iter().map(|_| "?").collect::<Vec<_>>().join(",");
412                let sql = format!(
413                    "DELETE FROM cards
414                     WHERE column_id IN ({placeholders})
415                       AND NOT EXISTS (SELECT 1 FROM archived_cards a WHERE a.card_id = cards.id)"
416                );
417                let mut query = sqlx::query(&sql);
418                for id in &column_ids {
419                    query = query.bind(id.to_string());
420                }
421                query.execute(&mut *conn).await.map_err(db_err)?;
422                Ok(())
423            })
424        }))
425    }
426
427    fn clear_sprint_from_cards(
428        &self,
429        sprint_id: Uuid,
430        timestamp: DateTime<Utc>,
431    ) -> KanbanResult<()> {
432        run(self.db_conn(move |conn| {
433            Box::pin(async move {
434                let now = fmt_dt(&timestamp);
435                sqlx::query(
436                    "UPDATE cards SET sprint_id = NULL, updated_at = ?
437                     WHERE sprint_id = ?
438                       AND NOT EXISTS (SELECT 1 FROM archived_cards a WHERE a.card_id = cards.id)",
439                )
440                .bind(&now)
441                .bind(sprint_id.to_string())
442                .execute(&mut *conn)
443                .await
444                .map_err(db_err)?;
445                Ok(())
446            })
447        }))
448    }
449
450    // Archived card
451
452    fn get_archived_card(&self, card_id: Uuid) -> KanbanResult<Option<ArchivedCard>> {
453        run(self.db_conn(|conn| {
454            Box::pin(async move {
455                let id_str = card_id.to_string();
456                // Reference-marker model: a marker needs only card id, board scope, and
457                // archive time. No card JOIN required.
458                let row = sqlx::query(
459                    "SELECT card_id AS id, board_id, archived_at
460                     FROM archived_cards
461                     WHERE card_id = ?",
462                )
463                .bind(&id_str)
464                .fetch_optional(&mut *conn)
465                .await
466                .map_err(db_err)?;
467
468                match row {
469                    Some(row) => Ok(Some(row_to_archived_card(&row)?)),
470                    None => Ok(None),
471                }
472            })
473        }))
474    }
475
476    fn list_archived_cards(&self) -> KanbanResult<Vec<ArchivedCard>> {
477        run(self.list_archived_cards_async())
478    }
479
480    fn insert_archived_card(&self, ac: ArchivedCard) -> KanbanResult<()> {
481        run(self.write_archived_card_async(&ac))
482    }
483
484    fn delete_archived_card(&self, card_id: Uuid) -> KanbanResult<()> {
485        run(self.db_conn(|conn| {
486            Box::pin(async move {
487                sqlx::query("DELETE FROM archived_cards WHERE card_id = ?")
488                    .bind(card_id.to_string())
489                    .execute(&mut *conn)
490                    .await
491                    .map_err(db_err)?;
492                sqlx::query("DELETE FROM cards WHERE id = ?")
493                    .bind(card_id.to_string())
494                    .execute(&mut *conn)
495                    .await
496                    .map_err(db_err)?;
497                Ok(())
498            })
499        }))
500    }
501
502    // Archived board (C5): board row stays in `boards`; a `board_archival` marker
503    // row marks it out of the live set. Reconstitute Archived<Board> by join.
504
505    fn get_archived_board(&self, board_id: Uuid) -> KanbanResult<Option<ArchivedBoard>> {
506        run(self.db_conn(move |conn| {
507            Box::pin(async move {
508                let id_str = board_id.to_string();
509                // Reference-marker model: the marker carries only the board id + archive
510                // time. The board row stays live in `boards`.
511                let row = sqlx::query(
512                    "SELECT board_id, archived_at FROM board_archival WHERE board_id = ?",
513                )
514                .bind(&id_str)
515                .fetch_optional(&mut *conn)
516                .await
517                .map_err(db_err)?;
518                match row {
519                    Some(row) => {
520                        let at: String = row.try_get("archived_at").map_err(db_err)?;
521                        Ok(Some(Archived::at(board_id, p_dt(&at)?)))
522                    }
523                    None => Ok(None),
524                }
525            })
526        }))
527    }
528
529    fn list_archived_boards(&self) -> KanbanResult<Vec<ArchivedBoard>> {
530        run(self.db_conn(|conn| {
531            Box::pin(async move { SqliteStore::list_archived_boards_with_conn(conn).await })
532        }))
533    }
534
535    fn insert_archived_board(&self, ab: ArchivedBoard) -> KanbanResult<()> {
536        run(self.db_conn(move |conn| {
537            Box::pin(async move {
538                // Reference-marker model: the board row must already be live in
539                // `boards` (archive keeps the head in place). Only record the marker.
540                sqlx::query(
541                    "INSERT INTO board_archival (board_id, archived_at) VALUES (?, ?)
542                     ON CONFLICT(board_id) DO UPDATE SET archived_at = excluded.archived_at",
543                )
544                .bind(ab.entity_id.to_string())
545                .bind(fmt_dt(&ab.metadata.archived_at))
546                .execute(&mut *conn)
547                .await
548                .map_err(db_err)?;
549                Ok(())
550            })
551        }))
552    }
553
554    fn delete_archived_board(&self, board_id: Uuid) -> KanbanResult<()> {
555        run(self.db_conn(move |conn| {
556            Box::pin(async move {
557                let id_str = board_id.to_string();
558                // Only remove the board row if it is actually archived — parity with
559                // the in-memory store, whose delete_archived_board touches only the
560                // archived collection and no-ops on a live board. Guarded delete runs
561                // FIRST (the marker still exists to satisfy the EXISTS check); the
562                // board_archival FK (ON DELETE CASCADE) drops the marker with the row,
563                // and the explicit marker delete below is belt-and-suspenders.
564                sqlx::query(
565                    "DELETE FROM boards
566                     WHERE id = ?
567                       AND EXISTS (SELECT 1 FROM board_archival ba WHERE ba.board_id = boards.id)",
568                )
569                .bind(&id_str)
570                .execute(&mut *conn)
571                .await
572                .map_err(db_err)?;
573                sqlx::query("DELETE FROM board_archival WHERE board_id = ?")
574                    .bind(&id_str)
575                    .execute(&mut *conn)
576                    .await
577                    .map_err(db_err)?;
578                Ok(())
579            })
580        }))
581    }
582
583    /// RESTORE path: drop only the archived MARKER, leaving the shared board row
584    /// and its subtree intact. `delete_archived_board` above deletes the row
585    /// (cascading the subtree) which is right for permanent delete but would
586    /// destroy the subtree on restore (KAN-863). No-op on a live board.
587    fn unarchive_board(&self, board_id: Uuid) -> KanbanResult<()> {
588        run(self.db_conn(|conn| {
589            Box::pin(async move {
590                sqlx::query("DELETE FROM board_archival WHERE board_id = ?")
591                    .bind(board_id.to_string())
592                    .execute(&mut *conn)
593                    .await
594                    .map_err(db_err)?;
595                Ok(())
596            })
597        }))
598    }
599
600    /// Board-scoped archived cards. Overrides the trait default (which filters
601    /// the full list) with a direct `WHERE board_id = ?` on the extension table,
602    /// so board scoping is a single indexed query.
603    fn list_archived_cards_by_board(&self, board_id: Uuid) -> KanbanResult<Vec<ArchivedCard>> {
604        run(self.db_conn(|conn| {
605            Box::pin(async move {
606                // Reference-marker model: markers only, scoped by the first-class
607                // `board_id`. Single indexed query, no card JOIN.
608                let rows = sqlx::query(
609                    "SELECT card_id AS id, board_id, archived_at
610                     FROM archived_cards
611                     WHERE board_id = ?
612                     ORDER BY archived_at",
613                )
614                .bind(board_id.to_string())
615                .fetch_all(&mut *conn)
616                .await
617                .map_err(db_err)?;
618
619                rows.iter().map(row_to_archived_card).collect()
620            })
621        }))
622    }
623
624    fn clear_sprint_from_archived_cards(
625        &self,
626        sprint_id: Uuid,
627        timestamp: DateTime<Utc>,
628    ) -> KanbanResult<()> {
629        run(self.db_conn(move |conn| {
630            Box::pin(async move {
631                let now = fmt_dt(&timestamp);
632                sqlx::query(
633                    "UPDATE cards SET sprint_id = NULL, updated_at = ?
634                     WHERE sprint_id = ?
635                       AND EXISTS (SELECT 1 FROM archived_cards a WHERE a.card_id = cards.id)",
636                )
637                .bind(&now)
638                .bind(sprint_id.to_string())
639                .execute(&mut *conn)
640                .await
641                .map_err(db_err)?;
642                Ok(())
643            })
644        }))
645    }
646
647    // Sprint
648
649    fn get_sprint(&self, id: Uuid) -> KanbanResult<Option<Sprint>> {
650        run(self.db_conn(|conn| {
651            Box::pin(async move {
652                let row = sqlx::query(
653                    "SELECT id, board_id, sprint_number, name_index, prefix, card_prefix,
654                            status, start_date, end_date, created_at, updated_at
655                     FROM sprints WHERE id = ?",
656                )
657                .bind(id.to_string())
658                .fetch_optional(&mut *conn)
659                .await
660                .map_err(db_err)?;
661                row.as_ref().map(row_to_sprint).transpose()
662            })
663        }))
664    }
665
666    fn list_sprints_by_board(&self, board_id: Uuid) -> KanbanResult<Vec<Sprint>> {
667        run(self.db_conn(|conn| {
668            Box::pin(async move {
669                let rows = sqlx::query(
670                    "SELECT id, board_id, sprint_number, name_index, prefix, card_prefix,
671                            status, start_date, end_date, created_at, updated_at
672                     FROM sprints WHERE board_id = ? ORDER BY sprint_number",
673                )
674                .bind(board_id.to_string())
675                .fetch_all(&mut *conn)
676                .await
677                .map_err(db_err)?;
678                rows.iter().map(row_to_sprint).collect()
679            })
680        }))
681    }
682
683    fn list_all_sprints(&self) -> KanbanResult<Vec<Sprint>> {
684        run(self.list_all_sprints_async())
685    }
686
687    fn upsert_sprint(&self, sprint: Sprint) -> KanbanResult<()> {
688        run(self.write_sprint_async(&sprint))
689    }
690
691    fn delete_sprint(&self, id: Uuid) -> KanbanResult<()> {
692        run(self.db_conn(|conn| {
693            Box::pin(async move {
694                sqlx::query("DELETE FROM sprints WHERE id = ?")
695                    .bind(id.to_string())
696                    .execute(&mut *conn)
697                    .await
698                    .map_err(db_err)?;
699                Ok(())
700            })
701        }))
702    }
703
704    fn delete_sprints_by_board(&self, board_id: Uuid) -> KanbanResult<()> {
705        run(self.db_conn(|conn| {
706            Box::pin(async move {
707                sqlx::query("DELETE FROM sprints WHERE board_id = ?")
708                    .bind(board_id.to_string())
709                    .execute(&mut *conn)
710                    .await
711                    .map_err(db_err)?;
712                Ok(())
713            })
714        }))
715    }
716
717    // Graph
718
719    fn get_graph(&self) -> KanbanResult<DependencyGraph> {
720        run(self.get_graph_async())
721    }
722
723    fn set_graph(&self, graph: DependencyGraph) -> KanbanResult<()> {
724        run(self.write_graph_async(&graph))
725    }
726
727    fn modify_graph(&self, f: kanban_domain::GraphMutFn) -> KanbanResult<()> {
728        run(self.modify_graph_async(f))
729    }
730}