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    Snapshot, 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    // Board
18
19    fn get_board(&self, id: Uuid) -> KanbanResult<Option<Board>> {
20        run(async {
21            let id_str = id.to_string();
22            // Reference-marker model: `get_board` is UNFILTERED — it returns the
23            // head whether the board is live OR archived (an `archived_board`
24            // marker hides it only from the LIVE `list_boards`). Callers
25            // discriminate archived-ness via `get_archived_board`.
26            let row = sqlx::query(
27                "SELECT id, name, description, sprint_prefix, card_prefix, task_sort_field,
28                        task_sort_order, sprint_duration_days, sprint_name_used_count,
29                        next_sprint_number, active_sprint_id, task_list_view,
30                        COALESCE(card_counter, 1) as card_counter,
31                        completion_column_id, position, created_at, updated_at
32                 FROM boards
33                 WHERE id = ?",
34            )
35            .bind(&id_str)
36            .fetch_optional(&self.pool)
37            .await
38            .map_err(db_err)?;
39
40            match row {
41                Some(row) => {
42                    let (names, counters) = self.fetch_board_aux(&id_str).await?;
43                    Ok(Some(row_to_board(&row, names, counters)?))
44                }
45                None => Ok(None),
46            }
47        })
48    }
49
50    fn list_boards(&self) -> KanbanResult<Vec<Board>> {
51        run(self.list_boards_async())
52    }
53
54    fn upsert_board(&self, board: Board) -> KanbanResult<()> {
55        run(self.write_board_async(&board))
56    }
57
58    fn delete_board(&self, id: Uuid) -> KanbanResult<()> {
59        run(async {
60            sqlx::query(
61                "DELETE FROM boards
62                 WHERE id = ?
63                   AND NOT EXISTS (SELECT 1 FROM board_archival ba WHERE ba.board_id = boards.id)",
64            )
65            .bind(id.to_string())
66            .execute(&self.pool)
67            .await
68            .map_err(db_err)?;
69            Ok(())
70        })
71    }
72
73    // Column
74
75    fn get_column(&self, id: Uuid) -> KanbanResult<Option<Column>> {
76        run(async {
77            let row = sqlx::query(
78                "SELECT id, board_id, name, position, wip_limit, created_at, updated_at
79                 FROM columns WHERE id = ?",
80            )
81            .bind(id.to_string())
82            .fetch_optional(&self.pool)
83            .await
84            .map_err(db_err)?;
85            row.as_ref().map(row_to_column).transpose()
86        })
87    }
88
89    fn list_columns_by_board(&self, board_id: Uuid) -> KanbanResult<Vec<Column>> {
90        run(async {
91            let rows = sqlx::query(
92                "SELECT id, board_id, name, position, wip_limit, created_at, updated_at
93                 FROM columns WHERE board_id = ?
94                 ORDER BY position ASC, created_at ASC, id ASC",
95            )
96            .bind(board_id.to_string())
97            .fetch_all(&self.pool)
98            .await
99            .map_err(db_err)?;
100            rows.iter().map(row_to_column).collect()
101        })
102    }
103
104    fn list_all_columns(&self) -> KanbanResult<Vec<Column>> {
105        run(self.list_all_columns_async())
106    }
107
108    fn upsert_column(&self, column: Column) -> KanbanResult<()> {
109        run(self.write_column_async(&column))
110    }
111
112    fn delete_column(&self, id: Uuid) -> KanbanResult<()> {
113        run(async {
114            sqlx::query("DELETE FROM columns WHERE id = ?")
115                .bind(id.to_string())
116                .execute(&self.pool)
117                .await
118                .map_err(db_err)?;
119            Ok(())
120        })
121    }
122
123    fn delete_columns_by_board(&self, board_id: Uuid) -> KanbanResult<()> {
124        run(async {
125            sqlx::query("DELETE FROM columns WHERE board_id = ?")
126                .bind(board_id.to_string())
127                .execute(&self.pool)
128                .await
129                .map_err(db_err)?;
130            Ok(())
131        })
132    }
133
134    // Card
135
136    fn get_card(&self, id: Uuid) -> KanbanResult<Option<Card>> {
137        run(async {
138            let id_str = id.to_string();
139            // F1 (KAN-870): get_card is UNFILTERED — an archived card stays in
140            // `cards` behind a marker and is reachable by id (it is an ordinary,
141            // editable card). The archived/live distinction is a LIST-level filter.
142            let row = sqlx::query(
143                "SELECT id, column_id, board_id, title, description, priority, status, position,
144                        due_date, points, card_number, sprint_id, created_at, updated_at,
145                        completed_at
146                 FROM cards
147                 WHERE id = ?",
148            )
149            .bind(&id_str)
150            .fetch_optional(&self.pool)
151            .await
152            .map_err(db_err)?;
153
154            match row {
155                Some(row) => {
156                    let logs = self.fetch_sprint_logs_for_card(&id_str).await?;
157                    Ok(Some(row_to_card(&row, logs)?))
158                }
159                None => Ok(None),
160            }
161        })
162    }
163
164    fn list_all_cards(&self) -> KanbanResult<Vec<Card>> {
165        run(self.fetch_cards_with_filter("", &[]))
166    }
167
168    fn list_cards_by_column(&self, column_id: Uuid) -> KanbanResult<Vec<Card>> {
169        run(self.fetch_cards_with_filter("AND column_id = ?", &[column_id.to_string()]))
170    }
171
172    fn list_cards_by_columns(&self, column_ids: &[Uuid]) -> KanbanResult<Vec<Card>> {
173        if column_ids.is_empty() {
174            return Ok(Vec::new());
175        }
176        let placeholders = column_ids.iter().map(|_| "?").collect::<Vec<_>>().join(",");
177        let where_clause = format!("AND column_id IN ({placeholders})");
178        let binds: Vec<String> = column_ids.iter().map(|id| id.to_string()).collect();
179        run(self.fetch_cards_with_filter(&where_clause, &binds))
180    }
181
182    fn list_cards_by_sprint(&self, sprint_id: Uuid) -> KanbanResult<Vec<Card>> {
183        run(self.fetch_cards_with_filter("AND sprint_id = ?", &[sprint_id.to_string()]))
184    }
185
186    /// 3-state archived-aware column read. Overrides the loud-floor default so
187    /// SQLite honours `ArchivedOnly`/`Include`; `LiveOnly` stays byte-identical
188    /// to `list_cards_by_column` (same `NOT EXISTS` base clause).
189    fn list_cards_by_column_filtered(
190        &self,
191        column_id: Uuid,
192        archived: kanban_domain::ArchivedFilter,
193    ) -> KanbanResult<Vec<Card>> {
194        run(self.fetch_cards_in_column_filtered(&column_id.to_string(), archived))
195    }
196
197    fn count_cards_in_column(&self, column_id: Uuid) -> KanbanResult<usize> {
198        run(async {
199            let row = sqlx::query(
200                "SELECT COUNT(*) as cnt FROM cards
201                 WHERE column_id = ? AND NOT EXISTS (SELECT 1 FROM archived_cards a WHERE a.card_id = cards.id)",
202            )
203            .bind(column_id.to_string())
204            .fetch_one(&self.pool)
205            .await
206            .map_err(db_err)?;
207            Ok(row.try_get::<i32, _>("cnt").map_err(db_err)? as usize)
208        })
209    }
210
211    /// 3-state archived-aware column count. Mirrors
212    /// `list_cards_by_column_filtered`: `LiveOnly` matches `count_cards_in_column`
213    /// exactly, `ArchivedOnly`/`Include` are served via the archived base clause.
214    fn count_cards_in_column_filtered(
215        &self,
216        column_id: Uuid,
217        archived: kanban_domain::ArchivedFilter,
218    ) -> KanbanResult<usize> {
219        run(self.count_cards_in_column_filtered_impl(&column_id.to_string(), archived))
220    }
221
222    fn count_cards_in_column_excluding(
223        &self,
224        column_id: Uuid,
225        exclude: &[Uuid],
226    ) -> KanbanResult<usize> {
227        run(async {
228            if exclude.is_empty() {
229                return self.count_cards_in_column(column_id);
230            }
231            let placeholders = exclude.iter().map(|_| "?").collect::<Vec<_>>().join(",");
232            let sql = format!(
233                "SELECT COUNT(*) as cnt FROM cards
234                 WHERE column_id = ?
235                   AND NOT EXISTS (SELECT 1 FROM archived_cards a WHERE a.card_id = cards.id)
236                   AND id NOT IN ({placeholders})"
237            );
238            let mut query = sqlx::query(&sql).bind(column_id.to_string());
239            for id in exclude {
240                query = query.bind(id.to_string());
241            }
242            let row = query.fetch_one(&self.pool).await.map_err(db_err)?;
243            Ok(row.try_get::<i32, _>("cnt").map_err(db_err)? as usize)
244        })
245    }
246
247    fn upsert_card(&self, card: Card) -> KanbanResult<()> {
248        run(self.write_card_async(&card))
249    }
250
251    fn delete_card(&self, id: Uuid) -> KanbanResult<()> {
252        run(async {
253            sqlx::query(
254                "DELETE FROM cards
255                 WHERE id = ? AND NOT EXISTS (SELECT 1 FROM archived_cards a WHERE a.card_id = cards.id)",
256            )
257            .bind(id.to_string())
258            .execute(&self.pool)
259            .await
260            .map_err(db_err)?;
261            Ok(())
262        })
263    }
264
265    fn delete_cards_by_columns(&self, column_ids: &[Uuid]) -> KanbanResult<()> {
266        run(async {
267            if column_ids.is_empty() {
268                return Ok(());
269            }
270            let placeholders = column_ids.iter().map(|_| "?").collect::<Vec<_>>().join(",");
271            let sql = format!(
272                "DELETE FROM cards
273                 WHERE column_id IN ({placeholders})
274                   AND NOT EXISTS (SELECT 1 FROM archived_cards a WHERE a.card_id = cards.id)"
275            );
276            let mut query = sqlx::query(&sql);
277            for id in column_ids {
278                query = query.bind(id.to_string());
279            }
280            query.execute(&self.pool).await.map_err(db_err)?;
281            Ok(())
282        })
283    }
284
285    fn clear_sprint_from_cards(
286        &self,
287        sprint_id: Uuid,
288        timestamp: DateTime<Utc>,
289    ) -> KanbanResult<()> {
290        run(async {
291            let now = fmt_dt(&timestamp);
292            sqlx::query(
293                "UPDATE cards SET sprint_id = NULL, updated_at = ?
294                 WHERE sprint_id = ?
295                   AND NOT EXISTS (SELECT 1 FROM archived_cards a WHERE a.card_id = cards.id)",
296            )
297            .bind(&now)
298            .bind(sprint_id.to_string())
299            .execute(&self.pool)
300            .await
301            .map_err(db_err)?;
302            Ok(())
303        })
304    }
305
306    // Archived card
307
308    fn get_archived_card(&self, card_id: Uuid) -> KanbanResult<Option<ArchivedCard>> {
309        run(async {
310            let id_str = card_id.to_string();
311            // Reference-marker model: a marker needs only card id, board scope, and
312            // archive time. No card JOIN required.
313            let row = sqlx::query(
314                "SELECT card_id AS id, board_id, archived_at
315                 FROM archived_cards
316                 WHERE card_id = ?",
317            )
318            .bind(&id_str)
319            .fetch_optional(&self.pool)
320            .await
321            .map_err(db_err)?;
322
323            match row {
324                Some(row) => Ok(Some(row_to_archived_card(&row)?)),
325                None => Ok(None),
326            }
327        })
328    }
329
330    fn list_archived_cards(&self) -> KanbanResult<Vec<ArchivedCard>> {
331        run(self.list_archived_cards_async())
332    }
333
334    fn insert_archived_card(&self, ac: ArchivedCard) -> KanbanResult<()> {
335        run(self.write_archived_card_async(&ac))
336    }
337
338    fn delete_archived_card(&self, card_id: Uuid) -> KanbanResult<()> {
339        run(async {
340            let mut tx = self.pool.begin().await.map_err(db_err)?;
341            sqlx::query("DELETE FROM archived_cards WHERE card_id = ?")
342                .bind(card_id.to_string())
343                .execute(&mut *tx)
344                .await
345                .map_err(db_err)?;
346            sqlx::query("DELETE FROM cards WHERE id = ?")
347                .bind(card_id.to_string())
348                .execute(&mut *tx)
349                .await
350                .map_err(db_err)?;
351            tx.commit().await.map_err(db_err)
352        })
353    }
354
355    // Archived board (C5): board row stays in `boards`; a `board_archival` marker
356    // row marks it out of the live set. Reconstitute Archived<Board> by join.
357
358    fn get_archived_board(&self, board_id: Uuid) -> KanbanResult<Option<ArchivedBoard>> {
359        run(async {
360            let id_str = board_id.to_string();
361            // Reference-marker model: the marker carries only the board id + archive
362            // time. The board row stays live in `boards`.
363            let row =
364                sqlx::query("SELECT board_id, archived_at FROM board_archival WHERE board_id = ?")
365                    .bind(&id_str)
366                    .fetch_optional(&self.pool)
367                    .await
368                    .map_err(db_err)?;
369            match row {
370                Some(row) => {
371                    let at: String = row.try_get("archived_at").map_err(db_err)?;
372                    Ok(Some(Archived::at(board_id, p_dt(&at)?)))
373                }
374                None => Ok(None),
375            }
376        })
377    }
378
379    fn list_archived_boards(&self) -> KanbanResult<Vec<ArchivedBoard>> {
380        run(self.list_archived_boards_async())
381    }
382
383    fn insert_archived_board(&self, ab: ArchivedBoard) -> KanbanResult<()> {
384        run(async {
385            // Reference-marker model: the board row must already be live in
386            // `boards` (archive keeps the head in place). Only record the marker.
387            sqlx::query(
388                "INSERT INTO board_archival (board_id, archived_at) VALUES (?, ?)
389                 ON CONFLICT(board_id) DO UPDATE SET archived_at = excluded.archived_at",
390            )
391            .bind(ab.entity_id.to_string())
392            .bind(fmt_dt(&ab.metadata.archived_at))
393            .execute(&self.pool)
394            .await
395            .map_err(db_err)?;
396            Ok(())
397        })
398    }
399
400    fn delete_archived_board(&self, board_id: Uuid) -> KanbanResult<()> {
401        run(async {
402            let id_str = board_id.to_string();
403            let mut tx = self.pool.begin().await.map_err(db_err)?;
404            // Only remove the board row if it is actually archived — parity with
405            // the in-memory store, whose delete_archived_board touches only the
406            // archived collection and no-ops on a live board. Guarded delete runs
407            // FIRST (the marker still exists to satisfy the EXISTS check); the
408            // board_archival FK (ON DELETE CASCADE) drops the marker with the row,
409            // and the explicit marker delete below is belt-and-suspenders.
410            sqlx::query(
411                "DELETE FROM boards
412                 WHERE id = ?
413                   AND EXISTS (SELECT 1 FROM board_archival ba WHERE ba.board_id = boards.id)",
414            )
415            .bind(&id_str)
416            .execute(&mut *tx)
417            .await
418            .map_err(db_err)?;
419            sqlx::query("DELETE FROM board_archival WHERE board_id = ?")
420                .bind(&id_str)
421                .execute(&mut *tx)
422                .await
423                .map_err(db_err)?;
424            tx.commit().await.map_err(db_err)
425        })
426    }
427
428    /// RESTORE path: drop only the archived MARKER, leaving the shared board row
429    /// and its subtree intact. `delete_archived_board` above deletes the row
430    /// (cascading the subtree) which is right for permanent delete but would
431    /// destroy the subtree on restore (KAN-863). No-op on a live board.
432    fn unarchive_board(&self, board_id: Uuid) -> KanbanResult<()> {
433        run(async {
434            sqlx::query("DELETE FROM board_archival WHERE board_id = ?")
435                .bind(board_id.to_string())
436                .execute(&self.pool)
437                .await
438                .map_err(db_err)?;
439            Ok(())
440        })
441    }
442
443    /// Board-scoped archived cards. Overrides the trait default (which filters
444    /// the full list) with a direct `WHERE board_id = ?` on the extension table,
445    /// so board scoping is a single indexed query.
446    fn list_archived_cards_by_board(&self, board_id: Uuid) -> KanbanResult<Vec<ArchivedCard>> {
447        run(async {
448            // Reference-marker model: markers only, scoped by the first-class
449            // `board_id`. Single indexed query, no card JOIN.
450            let rows = sqlx::query(
451                "SELECT card_id AS id, board_id, archived_at
452                 FROM archived_cards
453                 WHERE board_id = ?
454                 ORDER BY archived_at",
455            )
456            .bind(board_id.to_string())
457            .fetch_all(&self.pool)
458            .await
459            .map_err(db_err)?;
460
461            rows.iter().map(row_to_archived_card).collect()
462        })
463    }
464
465    fn clear_sprint_from_archived_cards(
466        &self,
467        sprint_id: Uuid,
468        timestamp: DateTime<Utc>,
469    ) -> KanbanResult<()> {
470        run(async {
471            let now = fmt_dt(&timestamp);
472            sqlx::query(
473                "UPDATE cards SET sprint_id = NULL, updated_at = ?
474                 WHERE sprint_id = ?
475                   AND EXISTS (SELECT 1 FROM archived_cards a WHERE a.card_id = cards.id)",
476            )
477            .bind(&now)
478            .bind(sprint_id.to_string())
479            .execute(&self.pool)
480            .await
481            .map_err(db_err)?;
482            Ok(())
483        })
484    }
485
486    // Sprint
487
488    fn get_sprint(&self, id: Uuid) -> KanbanResult<Option<Sprint>> {
489        run(async {
490            let row = sqlx::query(
491                "SELECT id, board_id, sprint_number, name_index, prefix, card_prefix,
492                        status, start_date, end_date, created_at, updated_at
493                 FROM sprints WHERE id = ?",
494            )
495            .bind(id.to_string())
496            .fetch_optional(&self.pool)
497            .await
498            .map_err(db_err)?;
499            row.as_ref().map(row_to_sprint).transpose()
500        })
501    }
502
503    fn list_sprints_by_board(&self, board_id: Uuid) -> KanbanResult<Vec<Sprint>> {
504        run(async {
505            let rows = sqlx::query(
506                "SELECT id, board_id, sprint_number, name_index, prefix, card_prefix,
507                        status, start_date, end_date, created_at, updated_at
508                 FROM sprints WHERE board_id = ? ORDER BY sprint_number",
509            )
510            .bind(board_id.to_string())
511            .fetch_all(&self.pool)
512            .await
513            .map_err(db_err)?;
514            rows.iter().map(row_to_sprint).collect()
515        })
516    }
517
518    fn list_all_sprints(&self) -> KanbanResult<Vec<Sprint>> {
519        run(self.list_all_sprints_async())
520    }
521
522    fn upsert_sprint(&self, sprint: Sprint) -> KanbanResult<()> {
523        run(self.write_sprint_async(&sprint))
524    }
525
526    fn delete_sprint(&self, id: Uuid) -> KanbanResult<()> {
527        run(async {
528            sqlx::query("DELETE FROM sprints WHERE id = ?")
529                .bind(id.to_string())
530                .execute(&self.pool)
531                .await
532                .map_err(db_err)?;
533            Ok(())
534        })
535    }
536
537    fn delete_sprints_by_board(&self, board_id: Uuid) -> KanbanResult<()> {
538        run(async {
539            sqlx::query("DELETE FROM sprints WHERE board_id = ?")
540                .bind(board_id.to_string())
541                .execute(&self.pool)
542                .await
543                .map_err(db_err)?;
544            Ok(())
545        })
546    }
547
548    // Graph
549
550    fn get_graph(&self) -> KanbanResult<DependencyGraph> {
551        run(self.get_graph_async())
552    }
553
554    fn set_graph(&self, graph: DependencyGraph) -> KanbanResult<()> {
555        run(self.write_graph_async(&graph))
556    }
557
558    fn modify_graph(&self, f: kanban_domain::GraphMutFn) -> KanbanResult<()> {
559        run(self.modify_graph_async(f))
560    }
561
562    // Snapshot
563
564    fn snapshot(&self) -> KanbanResult<Snapshot> {
565        run(self.snapshot_async())
566    }
567
568    fn apply_snapshot(&self, snapshot: Snapshot) -> KanbanResult<()> {
569        run(self.apply_snapshot_async(snapshot))
570    }
571}