kanban-persistence-sqlite 0.13.0

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
use kanban_domain::data_store::DataStore;
use kanban_domain::{
    Board, Card, CardPriority, CardRecord, CardStatus, Column, ColumnRecord, SprintLog,
};
use sqlx::Row;
use tempfile::TempDir;
use uuid::Uuid;

use super::super::SqliteStore;
use super::make_rt;

/// A fully-populated card whose `column_id` points at a real column and whose
/// `sprint_id` is `None`, so the round-trip satisfies the cards table's
/// foreign-key constraints (column_id -> columns, sprint_id -> sprints).
fn fully_populated_card(column_id: Uuid) -> Card {
    let sprint_id = Uuid::new_v4();
    let record = CardRecord {
        id: Uuid::new_v4(),
        column_id,
        board_id: Uuid::new_v4(),
        title: "Done card".to_string(),
        description: Some("finished".to_string()),
        priority: CardPriority::High,
        status: CardStatus::Done,
        position: 7,
        due_date: Some("2024-05-05T00:00:00Z".parse().unwrap()),
        points: Some(3),
        labels: Vec::new(),
        card_number: 42,
        sprint_id: None,
        created_at: "2024-01-01T00:00:00Z".parse().unwrap(),
        updated_at: "2024-02-02T00:00:00Z".parse().unwrap(),
        completed_at: Some("2024-03-03T00:00:00Z".parse().unwrap()),
        sprint_logs: vec![
            SprintLog {
                sprint_id,
                sprint_number: 1,
                sprint_name: Some("Sprint 1".to_string()),
                started_at: "2024-01-10T00:00:00Z".parse().unwrap(),
                ended_at: Some("2024-01-20T00:00:00Z".parse().unwrap()),
                status: "Completed".to_string(),
            },
            SprintLog {
                sprint_id,
                sprint_number: 2,
                sprint_name: None,
                started_at: "2024-02-01T00:00:00Z".parse().unwrap(),
                ended_at: None,
                status: "Active".to_string(),
            },
        ],
        prefix: String::new(),
    };
    Card::reconstitute(record).unwrap()
}

fn seed_column(store: &SqliteStore) -> Uuid {
    let board = Board::new("B", None::<String>);
    let board_id = board.id;
    store.upsert_board(board).unwrap();

    let column = Column::reconstitute(ColumnRecord {
        id: Uuid::new_v4(),
        board_id,
        name: "In Progress".to_string(),
        position: 0,
        wip_limit: None,
        default_status: None,
        created_at: "2024-01-01T00:00:00Z".parse().unwrap(),
        updated_at: "2024-01-01T00:00:00Z".parse().unwrap(),
    })
    .unwrap();
    let column_id = column.id;
    store.upsert_column(column).unwrap();
    column_id
}

#[test]
fn test_card_status_is_stored_as_its_serde_wire_name_not_debug_output() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("test.sqlite3");
    let rt = make_rt();
    rt.block_on(async {
        let store = SqliteStore::open(&path).await.unwrap();
        let column_id = seed_column(&store);

        let card = fully_populated_card(column_id);
        let id = card.id;
        store.upsert_card(card).unwrap();

        let raw: String = sqlx::query_scalar("SELECT status FROM cards WHERE id = ?")
            .bind(id.to_string())
            .fetch_one(store.pool())
            .await
            .unwrap();
        assert_eq!(
            raw, "Done",
            "the raw stored text must be the serde wire name, never Debug output"
        );
    });
}

#[test]
fn test_list_cards_by_column_ties_break_by_id_when_position_and_created_at_equal() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("test.sqlite3");
    let rt = make_rt();
    rt.block_on(async {
        let store = SqliteStore::open(&path).await.unwrap();
        let column_id = seed_column(&store);

        let mut a = fully_populated_card(column_id);
        a.title = "A".to_string();
        let mut b = fully_populated_card(column_id);
        b.title = "B".to_string();

        // Insert in one order, then re-derive the same two cards and insert
        // in the opposite order into a fresh store; the result must be
        // identical regardless of insertion order.
        store.upsert_card(a.clone()).unwrap();
        store.upsert_card(b.clone()).unwrap();
        let first_order = store
            .list_cards_by_column(column_id)
            .unwrap()
            .iter()
            .map(|c| c.title.clone())
            .collect::<Vec<_>>();

        let path2 = dir.path().join("test2.sqlite3");
        let store2 = SqliteStore::open(&path2).await.unwrap();
        let column_id2 = seed_column(&store2);
        a.column_id = column_id2;
        b.column_id = column_id2;
        store2.upsert_card(b).unwrap();
        store2.upsert_card(a).unwrap();
        let second_order = store2
            .list_cards_by_column(column_id2)
            .unwrap()
            .iter()
            .map(|c| c.title.clone())
            .collect::<Vec<_>>();

        assert_eq!(first_order, second_order);
    });
}

#[test]
fn test_sqlite_card_round_trip_preserves_all_fields() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("test.sqlite3");
    let rt = make_rt();
    rt.block_on(async {
        let store = SqliteStore::open(&path).await.unwrap();
        let column_id = seed_column(&store);

        let card = fully_populated_card(column_id);
        let id = card.id;
        store.upsert_card(card.clone()).unwrap();

        let loaded = store.get_card(id).unwrap().expect("card should load");
        assert_eq!(loaded, card);
    });
}

#[test]
fn test_sqlite_card_round_trip_restores_sprint_logs_from_separate_table() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("test.sqlite3");
    let rt = make_rt();
    rt.block_on(async {
        let store = SqliteStore::open(&path).await.unwrap();
        let column_id = seed_column(&store);

        let card = fully_populated_card(column_id);
        let id = card.id;
        store.upsert_card(card.clone()).unwrap();

        let loaded = store.get_card(id).unwrap().expect("card should load");
        // The two logs are reassembled from the separate sprint_logs table,
        // ordered, and funnelled through reconstitute verbatim.
        assert_eq!(loaded.sprint_logs.len(), 2);
        assert_eq!(loaded.sprint_logs, card.sprint_logs);
        assert_eq!(loaded.sprint_logs[0].sprint_number, 1);
        assert_eq!(loaded.sprint_logs[0].ended_at, card.sprint_logs[0].ended_at);
        assert_eq!(loaded.sprint_logs[1].sprint_name, None);
        assert_eq!(loaded.sprint_logs[1].ended_at, None);
    });
}

#[test]
fn test_sqlite_card_reconstitute_rejects_malformed_row() {
    // A raw card row with an unparseable status enum surfaces a KanbanError
    // through reconstitute's read path, not a panic.
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("test.sqlite3");
    let rt = make_rt();
    rt.block_on(async {
        let store = SqliteStore::open(&path).await.unwrap();
        let column_id = seed_column(&store);
        let id = Uuid::new_v4();

        sqlx::query(
            "INSERT INTO cards (id, column_id, board_id, title, description, priority, status,
                position, due_date, points, card_number, sprint_id, created_at, updated_at,
                completed_at)
             VALUES (?, ?, ?, 'Bad', NULL, 'Medium', 'NotAStatus', 0, NULL, NULL, 1, NULL,
                '2024-01-01T00:00:00Z', '2024-01-01T00:00:00Z', NULL)",
        )
        .bind(id.to_string())
        .bind(column_id.to_string())
        .bind(Uuid::new_v4().to_string())
        .execute(store.pool())
        .await
        .unwrap();

        let result = store.get_card(id);
        assert!(result.is_err());
    });
}

#[test]
fn test_get_card_by_board_and_number_returns_matching_card() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("test.sqlite3");
    let rt = make_rt();
    rt.block_on(async {
        let store = SqliteStore::open(&path).await.unwrap();
        let column_id = seed_column(&store);

        let mut a = fully_populated_card(column_id);
        a.card_number = 1;
        let mut b = fully_populated_card(column_id);
        b.board_id = a.board_id;
        b.card_number = 2;
        let mut other_board = fully_populated_card(column_id);
        other_board.card_number = 1;

        store.upsert_card(a.clone()).unwrap();
        store.upsert_card(b.clone()).unwrap();
        store.upsert_card(other_board.clone()).unwrap();

        let found = store
            .get_card_by_board_and_number(a.board_id, 1)
            .unwrap()
            .unwrap();
        assert_eq!(found.id, a.id);

        let found = store
            .get_card_by_board_and_number(a.board_id, 2)
            .unwrap()
            .unwrap();
        assert_eq!(found.id, b.id);

        assert!(store
            .get_card_by_board_and_number(a.board_id, 999)
            .unwrap()
            .is_none());
    });
}

#[test]
fn test_get_card_by_sprint_and_number_returns_matching_card() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("test.sqlite3");
    let rt = make_rt();
    rt.block_on(async {
        let store = SqliteStore::open(&path).await.unwrap();
        let board = Board::new("B", None::<String>);
        let board_id = board.id;
        store.upsert_board(board).unwrap();
        let column = Column::reconstitute(ColumnRecord {
            id: Uuid::new_v4(),
            board_id,
            name: "In Progress".to_string(),
            position: 0,
            wip_limit: None,
            default_status: None,
            created_at: "2024-01-01T00:00:00Z".parse().unwrap(),
            updated_at: "2024-01-01T00:00:00Z".parse().unwrap(),
        })
        .unwrap();
        let column_id = column.id;
        store.upsert_column(column).unwrap();
        let sprint = kanban_domain::Sprint::new(board_id, 1, None, Some("SP"));
        let sprint_id = sprint.id;
        store.upsert_sprint(sprint).unwrap();

        let mut a = fully_populated_card(column_id);
        a.sprint_id = Some(sprint_id);
        a.card_number = 1;
        let mut b = fully_populated_card(column_id);
        b.sprint_id = Some(sprint_id);
        b.card_number = 2;
        let unsprinted = fully_populated_card(column_id);

        store.upsert_card(a.clone()).unwrap();
        store.upsert_card(b.clone()).unwrap();
        store.upsert_card(unsprinted.clone()).unwrap();

        let found = store
            .get_card_by_sprint_and_number(sprint_id, 1)
            .unwrap()
            .unwrap();
        assert_eq!(found.id, a.id);

        let found = store
            .get_card_by_sprint_and_number(sprint_id, 2)
            .unwrap()
            .unwrap();
        assert_eq!(found.id, b.id);

        assert!(store
            .get_card_by_sprint_and_number(sprint_id, 999)
            .unwrap()
            .is_none());
    });
}

/// Structural proof that the SQLite override issues a targeted, indexed
/// single-row query rather than silently falling back to the trait's
/// `list_all_cards`-based default (which has no `WHERE` clause at all).
/// `EXPLAIN QUERY PLAN` on the override's exact query must report an indexed
/// `SEARCH`, not an unindexed full-table `SCAN`.
#[test]
// Matches any board-leading index name, not one specific index. The planner
// picks `idx_cards_board_id` or the composite `idx_cards_board_number`
// depending on which exist, and pinning either name makes this test fail the
// moment the other lands. The load-bearing half is the `SCAN cards` exclusion
// below: the trait default has no WHERE clause, so a full scan is the only
// plan it can produce, and its absence is what proves the override ran.
fn test_get_card_by_board_and_number_uses_indexed_search_not_full_scan() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("test.sqlite3");
    let rt = make_rt();
    rt.block_on(async {
        let store = SqliteStore::open(&path).await.unwrap();

        let plan_rows = sqlx::query(
            "EXPLAIN QUERY PLAN
             SELECT id FROM cards
             WHERE NOT EXISTS (SELECT 1 FROM archived_cards a WHERE a.card_id = cards.id)
               AND board_id = ? AND card_number = ?",
        )
        .bind(Uuid::new_v4().to_string())
        .bind(1_i64)
        .fetch_all(store.pool())
        .await
        .unwrap();

        let plan: Vec<String> = plan_rows
            .iter()
            .map(|row| row.try_get::<String, _>("detail").unwrap())
            .collect();
        let plan_text = plan.join(" | ");

        assert!(
            plan_text.contains("SEARCH cards USING INDEX idx_cards_board"),
            "expected an indexed search on a board-leading index, got: {plan_text}"
        );
        assert!(
            !plan_text.contains("SCAN cards"),
            "override must not fall back to a full table scan, got: {plan_text}"
        );
    });
}

/// Write a card carrying `labels=["x","y"]`, read it back, and assert the labels
/// survived the round-trip through SQLite.
#[test]
fn test_sqlite_card_tags_round_trip() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("t.sqlite3");
    let rt = make_rt();
    rt.block_on(async {
        let store = SqliteStore::open(&path).await.unwrap();
        let column_id = seed_column(&store);

        let card = Card::reconstitute(CardRecord {
            id: Uuid::new_v4(),
            column_id,
            board_id: Uuid::new_v4(),
            title: "Tagged".into(),
            description: None,
            priority: kanban_domain::CardPriority::Medium,
            status: kanban_domain::CardStatus::Todo,
            position: 0,
            due_date: None,
            points: None,
            labels: vec!["x".to_string(), "y".to_string()],
            card_number: 1,
            sprint_id: None,
            created_at: "2024-01-01T00:00:00Z".parse().unwrap(),
            updated_at: "2024-01-01T00:00:00Z".parse().unwrap(),
            completed_at: None,
            sprint_logs: vec![],
            prefix: String::new(),
        })
        .unwrap();

        let card_id = card.id;
        store.upsert_card(card).expect("upsert card with labels");

        let loaded = store.get_card(card_id).expect("get card").expect("Some");
        assert_eq!(loaded.labels, vec!["x".to_string(), "y".to_string()]);
    });
}