kanban-persistence-sqlite 0.13.1

SQLite storage backend for the kanban project management tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use crate::SqliteStore;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use kanban_backend_memory::InMemoryStore;
use kanban_domain::command_batch::CommandBatch;
use kanban_domain::command_store::CommandStore;
use kanban_domain::data_store::DataStore;
use kanban_domain::{
    ArchivedBoard, ArchivedCard, Board, Card, Column, DependencyGraph, GraphMutFn, KanbanError,
    KanbanResult, Sprint,
};
use kanban_persistence::PersistenceMetadata;
use uuid::Uuid;

pub struct SqliteBackend {
    db: SqliteStore,
    /// In-session command log. The on-disk `command_log` table exists
    /// in the schema but is not yet wired through this backend.
    mem: InMemoryStore,
    /// Most-recent metadata observed from the underlying DB. Populated on
    /// `open()` and refreshed inside `flush()` after the writer-stamp UPDATE.
    /// Mirrors `JsonDataStore::last_metadata` so `persistence_metadata()` —
    /// called once per TUI render via the F12 diagnostics panel — is a
    /// RwLock read instead of a SELECT round-trip.
    last_metadata: std::sync::RwLock<Option<PersistenceMetadata>>,
}

impl SqliteBackend {
    pub async fn open(locator: &str) -> KanbanResult<Self> {
        let db = SqliteStore::open(locator).await?;
        let initial = db.read_metadata_sync()?;
        Ok(Self {
            db,
            mem: InMemoryStore::new(),
            last_metadata: std::sync::RwLock::new(initial),
        })
    }

    /// Closes the underlying pool. Callers that may delete the database file
    /// afterwards must await this first: Windows refuses to unlink a file with
    /// live handles.
    pub async fn close(&self) {
        self.db.close().await;
    }
}

// ─── DataStore ───────────────────────────────────────────────────────────────

impl DataStore for SqliteBackend {
    fn get_prefix(&self, name: &str) -> KanbanResult<Option<kanban_domain::Prefix>> {
        self.db.get_prefix(name)
    }
    fn list_prefixes(&self) -> KanbanResult<Vec<kanban_domain::Prefix>> {
        self.db.list_prefixes()
    }
    fn upsert_prefix(&self, prefix: kanban_domain::Prefix) -> KanbanResult<()> {
        self.db.upsert_prefix(prefix)
    }

    fn get_label(&self, name: &str) -> KanbanResult<Option<kanban_domain::Label>> {
        self.db.get_label(name)
    }
    fn list_labels(&self) -> KanbanResult<Vec<kanban_domain::Label>> {
        self.db.list_labels()
    }
    fn upsert_label(&self, label: kanban_domain::Label) -> KanbanResult<()> {
        self.db.upsert_label(label)
    }
    fn delete_label(&self, name: &str) -> KanbanResult<()> {
        self.db.delete_label(name)
    }

    fn get_board(&self, id: Uuid) -> KanbanResult<Option<Board>> {
        self.db.get_board(id)
    }
    fn list_boards(&self) -> KanbanResult<Vec<Board>> {
        self.db.list_boards()
    }
    fn upsert_board(&self, board: Board) -> KanbanResult<()> {
        self.db.upsert_board(board)
    }
    fn delete_board(&self, id: Uuid) -> KanbanResult<()> {
        self.db.delete_board(id)
    }

    fn get_column(&self, id: Uuid) -> KanbanResult<Option<Column>> {
        self.db.get_column(id)
    }
    fn list_columns_by_board(&self, board_id: Uuid) -> KanbanResult<Vec<Column>> {
        self.db.list_columns_by_board(board_id)
    }
    fn list_all_columns(&self) -> KanbanResult<Vec<Column>> {
        self.db.list_all_columns()
    }
    fn upsert_column(&self, column: Column) -> KanbanResult<()> {
        self.db.upsert_column(column)
    }
    fn delete_column(&self, id: Uuid) -> KanbanResult<()> {
        self.db.delete_column(id)
    }
    fn delete_columns_by_board(&self, board_id: Uuid) -> KanbanResult<()> {
        self.db.delete_columns_by_board(board_id)
    }

    fn get_card(&self, id: Uuid) -> KanbanResult<Option<Card>> {
        self.db.get_card(id)
    }
    fn list_all_cards(&self) -> KanbanResult<Vec<Card>> {
        self.db.list_all_cards()
    }
    fn list_cards_by_column(&self, column_id: Uuid) -> KanbanResult<Vec<Card>> {
        self.db.list_cards_by_column(column_id)
    }
    fn list_cards_by_columns(&self, column_ids: &[Uuid]) -> KanbanResult<Vec<Card>> {
        self.db.list_cards_by_columns(column_ids)
    }
    fn list_cards_by_sprint(&self, sprint_id: Uuid) -> KanbanResult<Vec<Card>> {
        self.db.list_cards_by_sprint(sprint_id)
    }
    fn list_cards_by_number(&self, card_number: u32) -> KanbanResult<Vec<kanban_domain::Card>> {
        self.db.list_cards_by_number(card_number)
    }
    fn list_cards_by_prefix_and_number(
        &self,
        prefix: &str,
        card_number: u32,
    ) -> KanbanResult<Vec<kanban_domain::Card>> {
        self.db.list_cards_by_prefix_and_number(prefix, card_number)
    }
    fn get_card_by_board_and_number(
        &self,
        board_id: Uuid,
        card_number: u32,
    ) -> KanbanResult<Option<Card>> {
        self.db.get_card_by_board_and_number(board_id, card_number)
    }
    fn get_card_by_sprint_and_number(
        &self,
        sprint_id: Uuid,
        card_number: u32,
    ) -> KanbanResult<Option<Card>> {
        self.db
            .get_card_by_sprint_and_number(sprint_id, card_number)
    }
    fn count_cards_in_column(&self, column_id: Uuid) -> KanbanResult<usize> {
        self.db.count_cards_in_column(column_id)
    }
    fn count_cards_in_column_excluding(
        &self,
        column_id: Uuid,
        exclude: &[Uuid],
    ) -> KanbanResult<usize> {
        self.db.count_cards_in_column_excluding(column_id, exclude)
    }
    fn list_cards_by_column_filtered(
        &self,
        column_id: Uuid,
        archived: kanban_domain::ArchivedFilter,
    ) -> KanbanResult<Vec<Card>> {
        self.db.list_cards_by_column_filtered(column_id, archived)
    }
    fn count_cards_in_column_filtered(
        &self,
        column_id: Uuid,
        archived: kanban_domain::ArchivedFilter,
    ) -> KanbanResult<usize> {
        self.db.count_cards_in_column_filtered(column_id, archived)
    }
    fn upsert_card(&self, card: Card) -> KanbanResult<()> {
        self.db.upsert_card(card)
    }
    fn delete_card(&self, id: Uuid) -> KanbanResult<()> {
        self.db.delete_card(id)
    }
    fn delete_cards_by_columns(&self, column_ids: &[Uuid]) -> KanbanResult<()> {
        self.db.delete_cards_by_columns(column_ids)
    }
    fn clear_sprint_from_cards(
        &self,
        sprint_id: Uuid,
        timestamp: DateTime<Utc>,
    ) -> KanbanResult<()> {
        self.db.clear_sprint_from_cards(sprint_id, timestamp)
    }

    fn get_archived_card(&self, card_id: Uuid) -> KanbanResult<Option<ArchivedCard>> {
        self.db.get_archived_card(card_id)
    }
    fn list_archived_cards(&self) -> KanbanResult<Vec<ArchivedCard>> {
        self.db.list_archived_cards()
    }
    fn insert_archived_card(&self, ac: ArchivedCard) -> KanbanResult<()> {
        self.db.insert_archived_card(ac)
    }
    fn delete_archived_card(&self, card_id: Uuid) -> KanbanResult<()> {
        self.db.delete_archived_card(card_id)
    }
    fn get_archived_board(&self, board_id: Uuid) -> KanbanResult<Option<ArchivedBoard>> {
        self.db.get_archived_board(board_id)
    }
    fn list_archived_boards(&self) -> KanbanResult<Vec<ArchivedBoard>> {
        self.db.list_archived_boards()
    }
    fn insert_archived_board(&self, ab: ArchivedBoard) -> KanbanResult<()> {
        self.db.insert_archived_board(ab)
    }
    fn delete_archived_board(&self, board_id: Uuid) -> KanbanResult<()> {
        self.db.delete_archived_board(board_id)
    }
    fn unarchive_board(&self, board_id: Uuid) -> KanbanResult<()> {
        self.db.unarchive_board(board_id)
    }
    fn list_archived_cards_by_board(&self, board_id: Uuid) -> KanbanResult<Vec<ArchivedCard>> {
        self.db.list_archived_cards_by_board(board_id)
    }
    fn clear_sprint_from_archived_cards(
        &self,
        sprint_id: Uuid,
        timestamp: DateTime<Utc>,
    ) -> KanbanResult<()> {
        self.db
            .clear_sprint_from_archived_cards(sprint_id, timestamp)
    }

    fn get_sprint(&self, id: Uuid) -> KanbanResult<Option<Sprint>> {
        self.db.get_sprint(id)
    }
    fn list_sprints_by_board(&self, board_id: Uuid) -> KanbanResult<Vec<Sprint>> {
        self.db.list_sprints_by_board(board_id)
    }
    fn list_all_sprints(&self) -> KanbanResult<Vec<Sprint>> {
        self.db.list_all_sprints()
    }
    fn upsert_sprint(&self, sprint: Sprint) -> KanbanResult<()> {
        self.db.upsert_sprint(sprint)
    }
    fn delete_sprint(&self, id: Uuid) -> KanbanResult<()> {
        self.db.delete_sprint(id)
    }
    fn delete_sprints_by_board(&self, board_id: Uuid) -> KanbanResult<()> {
        self.db.delete_sprints_by_board(board_id)
    }

    fn get_graph(&self) -> KanbanResult<DependencyGraph> {
        self.db.get_graph()
    }
    fn set_graph(&self, graph: DependencyGraph) -> KanbanResult<()> {
        self.db.set_graph(graph)
    }
    fn modify_graph(&self, f: GraphMutFn) -> KanbanResult<()> {
        self.db.modify_graph(f)
    }
}

// ─── CommandStore ─────────────────────────────────────────────────────────────

// Routes to the in-memory mirror; the on-disk command_log table stays
// unwritten until a separate piece of work wires it up.
impl CommandStore for SqliteBackend {
    fn append_batch(&self, batch: &CommandBatch) -> KanbanResult<u64> {
        self.mem.append_batch(batch)
    }
    fn batch_count(&self) -> KanbanResult<u64> {
        self.mem.batch_count()
    }
    fn load_batches(&self, from: u64, to: u64) -> KanbanResult<Vec<CommandBatch>> {
        self.mem.load_batches(from, to)
    }
    /// Delegate to the mirror's atomic count+load rather than the
    /// non-atomic trait default, so a concurrent append cannot land
    /// between the count and the load.
    fn load_all_batches(&self) -> KanbanResult<(Vec<CommandBatch>, u64)> {
        self.mem.load_all_batches()
    }
}

// ─── KanbanBackend ────────────────────────────────────────────────────────────

#[async_trait]
impl kanban_backend::KanbanBackend for SqliteBackend {
    fn as_data_store(&self) -> &dyn DataStore {
        self
    }

    async fn flush(&self) -> KanbanResult<()> {
        // Stamp before truncating the WAL: anything in the WAL is about to
        // land in the main DB, so the writer attribution should land
        // alongside it.
        self.db.stamp_writer().await?;
        self.db.checkpoint().await?;
        // Refresh the cached metadata so subsequent persistence_metadata()
        // calls reflect what was just stamped without re-issuing a SELECT.
        // Propagate poison errors rather than swallowing — symmetric with
        // JsonDataStore::do_flush's handling of the same RwLock pattern.
        let fresh = self.db.read_metadata_sync()?;
        let mut guard = self.last_metadata.write().map_err(|_| {
            KanbanError::Internal("sqlite_backend: last_metadata RwLock poisoned".into())
        })?;
        *guard = fresh;
        Ok(())
    }

    fn instance_id(&self) -> Uuid {
        self.db.instance_id()
    }

    fn local_persistence(&self) -> Option<&dyn kanban_backend::LocalPersistence> {
        Some(self)
    }

    /// Real `BEGIN`/`COMMIT`/`ROLLBACK` transaction rather than a
    /// snapshot-and-restore rollback.
    fn with_transaction(&self, f: kanban_backend::TransactionFn<'_>) -> KanbanResult<()> {
        self.db.begin_write_transaction()?;
        match f() {
            Ok(()) => self.db.commit_write_transaction(),
            Err(e) => {
                self.db.rollback_write_transaction();
                Err(e)
            }
        }
    }
}

impl kanban_backend::LocalPersistence for SqliteBackend {
    fn persistence_metadata(&self) -> Option<PersistenceMetadata> {
        self.last_metadata.read().ok().and_then(|g| g.clone())
    }
}

#[cfg(test)]
mod tests {
    use kanban_domain::{Board, DataStore};

    use super::SqliteBackend;
    use kanban_backend::KanbanBackend;

    #[tokio::test(flavor = "multi_thread")]
    async fn test_sqlite_backend_needs_flush_returns_false() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("t.sqlite3");
        let backend = SqliteBackend::open(path.to_str().unwrap()).await.unwrap();
        assert!(!backend.needs_flush());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_sqlite_backend_flush_executes_wal_checkpoint() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("t.sqlite3");
        let backend = SqliteBackend::open(path.to_str().unwrap()).await.unwrap();
        backend
            .upsert_board(Board::new("B", None::<String>))
            .unwrap();
        backend
            .flush()
            .await
            .expect("WAL checkpoint should not error");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_sqlite_backend_exposes_local_persistence() {
        use super::SqliteBackend;
        use kanban_backend::KanbanBackend;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("md.sqlite3");
        let backend = SqliteBackend::open(path.to_str().unwrap()).await.unwrap();
        backend.flush().await.unwrap();
        let meta = backend
            .local_persistence()
            .expect("sqlite backend must expose a LocalPersistence capability")
            .persistence_metadata()
            .expect("flushed sqlite backend must expose metadata");
        assert_eq!(
            meta.writer_version.as_deref(),
            Some(kanban_core::KANBAN_VERSION),
            "flushed sqlite backend must stamp writer_version"
        );
        assert_eq!(
            meta.writer_commit.as_deref(),
            Some(kanban_core::KANBAN_COMMIT),
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_sqlite_backend_reload_is_noop() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("t.sqlite3");
        let backend = SqliteBackend::open(path.to_str().unwrap()).await.unwrap();
        backend
            .upsert_board(Board::new("A", None::<String>))
            .unwrap();
        backend.reload().await.unwrap();
        let boards = backend.list_boards().unwrap();
        assert_eq!(boards.len(), 1);
        assert_eq!(boards[0].name, "A");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_sqlite_backend_instance_id_matches_its_store() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("t.sqlite3");
        let backend = SqliteBackend::open(path.to_str().unwrap()).await.unwrap();
        assert_eq!(
            KanbanBackend::instance_id(&backend),
            backend.db.instance_id()
        );
    }
}