canon-archive 0.2.2

A CLI tool for organizing large media libraries into a canonical archive
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//! Root repository — infrastructure layer for fetching roots.
//!
//! This module provides fetch functions that return `Root` structs from the
//! database. It is intentionally simple — no domain logic here, just data access.
//!
//! ## Design Principles
//!
//! 1. **Simple SQL**: Queries do data access only, no business logic in WHERE clauses
//! 2. **Returns domain types**: Functions return `Root` structs, not raw rows
//! 3. **No filtering**: Fetch all roots; domain predicates handle filtering
//!
//! ## Usage
//!
//! ```ignore
//! use canon::root_repo;
//!
//! // Fetch all roots
//! let roots = root_repo::fetch_all(conn)?;
//!
//! // Filter with domain predicates
//! let active_sources: Vec<_> = roots.iter()
//!     .filter(|r| r.is_active())
//!     .filter(|r| r.is_source())
//!     .collect();
//! ```

use std::collections::HashMap;

use anyhow::Result;

use super::db::Connection;
use crate::domain::root::Root;

/// The columns we SELECT for Root construction.
const ROOT_COLUMNS: &str = "id, path, role, comment, last_scanned_at, suspended";

/// Construct a Root from a row. Column order must match ROOT_COLUMNS.
fn root_from_row(row: &rusqlite::Row) -> rusqlite::Result<Root> {
    Ok(Root {
        id: row.get(0)?,
        path: row.get(1)?,
        role: row.get(2)?,
        comment: row.get(3)?,
        last_scanned_at: row.get(4)?,
        suspended: row.get(5)?,
    })
}

/// Fetch all roots.
///
/// Returns roots ordered by ID. No filtering is applied — callers should use
/// domain predicates like `is_active()`, `is_source()`, etc. to filter.
pub fn fetch_all(conn: &Connection) -> Result<Vec<Root>> {
    let sql = format!("SELECT {ROOT_COLUMNS} FROM roots ORDER BY id");
    let mut stmt = conn.prepare(&sql)?;
    let rows = stmt.query_map([], root_from_row)?;

    let mut roots = Vec::new();
    for row in rows {
        roots.push(row?);
    }

    Ok(roots)
}

/// Fetch roots by their IDs, returning a HashMap for O(1) lookup.
///
/// This is useful when you have a list of root IDs and need to fetch
/// the full Root data for each.
///
/// If an ID doesn't exist, it won't appear in the result map.
// Part of the domain model API but not currently used. Kept for API completeness.
#[allow(dead_code)]
pub fn batch_fetch_by_ids(conn: &Connection, root_ids: &[i64]) -> Result<HashMap<i64, Root>> {
    if root_ids.is_empty() {
        return Ok(HashMap::new());
    }

    let placeholders: Vec<&str> = root_ids.iter().map(|_| "?").collect();
    let sql = format!(
        "SELECT {} FROM roots WHERE id IN ({})",
        ROOT_COLUMNS,
        placeholders.join(",")
    );

    let params: Vec<rusqlite::types::Value> = root_ids
        .iter()
        .map(|&id| rusqlite::types::Value::from(id))
        .collect();

    let mut stmt = conn.prepare(&sql)?;
    let rows = stmt.query_map(rusqlite::params_from_iter(params), root_from_row)?;

    let mut roots = HashMap::with_capacity(root_ids.len());
    for row in rows {
        let root = row?;
        roots.insert(root.id, root);
    }

    Ok(roots)
}

/// Create a new root in the database.
///
/// # Arguments
/// * `conn` - Database connection
/// * `path` - Canonical path of the root directory
/// * `role` - Role of the root ("source" or "archive")
/// * `comment` - Optional comment/description
///
/// # Returns
/// The newly created Root with all fields populated.
pub fn create(conn: &Connection, path: &str, role: &str, comment: Option<&str>) -> Result<Root> {
    conn.execute(
        "INSERT INTO roots (path, role, comment) VALUES (?, ?, ?)",
        rusqlite::params![path, role, comment],
    )?;
    let id = conn.last_insert_rowid();

    // Fetch the complete Root to ensure consistency with database state.
    // This follows the insert_destination() pattern from source.rs.
    let sql = format!("SELECT {ROOT_COLUMNS} FROM roots WHERE id = ?");
    let root = conn.query_row(&sql, [id], root_from_row)?;
    Ok(root)
}

/// Update the last_scanned_at timestamp for a root.
///
/// Called after a full root scan completes (not for subdirectory scans).
pub fn update_last_scanned_at(conn: &Connection, root_id: i64, timestamp: i64) -> Result<()> {
    conn.execute(
        "UPDATE roots SET last_scanned_at = ? WHERE id = ?",
        rusqlite::params![timestamp, root_id],
    )?;
    Ok(())
}

/// Fetch file counts (present sources) for a set of root IDs.
///
/// Returns a HashMap from root_id to count of present sources.
/// Roots with no present sources will not appear in the result.
pub fn fetch_file_counts(conn: &Connection, root_ids: &[i64]) -> Result<HashMap<i64, i64>> {
    if root_ids.is_empty() {
        return Ok(HashMap::new());
    }

    let placeholders: Vec<&str> = root_ids.iter().map(|_| "?").collect();
    let sql = format!(
        "SELECT root_id, COUNT(*) FROM sources WHERE present = 1 AND root_id IN ({}) GROUP BY root_id",
        placeholders.join(",")
    );

    let params: Vec<rusqlite::types::Value> = root_ids
        .iter()
        .map(|&id| rusqlite::types::Value::from(id))
        .collect();

    let mut stmt = conn.prepare(&sql)?;
    let rows = stmt.query_map(rusqlite::params_from_iter(params), |row| {
        Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?))
    })?;

    let mut counts = HashMap::new();
    for row in rows {
        let (root_id, count) = row?;
        counts.insert(root_id, count);
    }

    Ok(counts)
}

/// Set the suspended state of a root.
pub fn set_suspended(conn: &Connection, root_id: i64, suspended: bool) -> Result<()> {
    conn.execute(
        "UPDATE roots SET suspended = ? WHERE id = ?",
        rusqlite::params![suspended as i64, root_id],
    )?;
    Ok(())
}

/// Set or clear the comment on a root.
pub fn set_comment(conn: &Connection, root_id: i64, comment: Option<&str>) -> Result<()> {
    conn.execute(
        "UPDATE roots SET comment = ? WHERE id = ?",
        rusqlite::params![comment, root_id],
    )?;
    Ok(())
}

/// Remove a root and all its sources and facts.
///
/// Deletes in order: facts for sources → sources → root.
/// Returns the number of sources deleted.
pub fn remove(conn: &Connection, root_id: i64) -> Result<i64> {
    // Delete facts for sources in this root
    conn.execute(
        "DELETE FROM facts WHERE entity_type = 'source' AND entity_id IN (
            SELECT id FROM sources WHERE root_id = ?
        )",
        [root_id],
    )?;

    // Delete sources
    let deleted_sources = conn.execute("DELETE FROM sources WHERE root_id = ?", [root_id])?;

    // Delete the root
    conn.execute("DELETE FROM roots WHERE id = ?", [root_id])?;

    Ok(deleted_sources as i64)
}

/// Insert a root for testing purposes.
///
/// This function is only available in test builds. It provides a simple way
/// to set up test data without duplicating INSERT SQL across test modules.
#[cfg(test)]
pub fn insert_test_root(conn: &Connection, path: &str, role: &str, suspended: bool) -> i64 {
    conn.execute(
        "INSERT INTO roots (path, role, suspended) VALUES (?, ?, ?)",
        rusqlite::params![path, role, suspended as i64],
    )
    .unwrap();
    conn.last_insert_rowid()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::repo::open_in_memory_for_test;
    use rusqlite::Connection as RusqliteConnection;

    /// Create an in-memory database with the full schema.
    fn setup_test_db() -> RusqliteConnection {
        open_in_memory_for_test()
    }

    /// Insert a test root and return its ID.
    fn insert_root(
        conn: &RusqliteConnection,
        path: &str,
        role: &str,
        comment: Option<&str>,
        last_scanned_at: Option<i64>,
        suspended: bool,
    ) -> i64 {
        conn.execute(
            "INSERT INTO roots (path, role, comment, last_scanned_at, suspended) VALUES (?, ?, ?, ?, ?)",
            rusqlite::params![path, role, comment, last_scanned_at, suspended as i64],
        )
        .unwrap();
        conn.last_insert_rowid()
    }

    // =========================================================================
    // fetch_all tests
    // =========================================================================

    #[test]
    fn fetch_all_empty() {
        let conn = setup_test_db();
        let roots = fetch_all(&conn).unwrap();
        assert!(roots.is_empty());
    }

    #[test]
    fn fetch_all_returns_all() {
        let conn = setup_test_db();

        insert_root(&conn, "/photos", "source", None, None, false);
        insert_root(
            &conn,
            "/archive",
            "archive",
            Some("backup"),
            Some(1704067200),
            false,
        );

        let roots = fetch_all(&conn).unwrap();
        assert_eq!(roots.len(), 2);

        // Verify order (by ID)
        assert_eq!(roots[0].path, "/photos");
        assert_eq!(roots[1].path, "/archive");

        // Verify all fields populated
        let archive = &roots[1];
        assert_eq!(archive.role, "archive");
        assert_eq!(archive.comment, Some("backup".to_string()));
        assert_eq!(archive.last_scanned_at, Some(1704067200));
        assert!(!archive.suspended);
    }

    #[test]
    fn fetch_all_includes_suspended() {
        let conn = setup_test_db();

        insert_root(&conn, "/active", "source", None, None, false);
        insert_root(&conn, "/suspended", "source", None, None, true);

        let roots = fetch_all(&conn).unwrap();
        assert_eq!(roots.len(), 2);

        // Both are returned; filtering is caller's job
        let suspended = roots.iter().find(|r| r.path == "/suspended").unwrap();
        assert!(suspended.is_suspended());
    }

    #[test]
    fn fetch_all_with_domain_predicates() {
        let conn = setup_test_db();

        insert_root(&conn, "/photos", "source", None, None, false);
        insert_root(&conn, "/archive", "archive", None, None, false);
        insert_root(&conn, "/suspended", "source", None, None, true);

        let roots = fetch_all(&conn).unwrap();

        // Use domain predicates to filter
        let active_sources: Vec<_> = roots
            .iter()
            .filter(|r| r.is_active())
            .filter(|r| r.is_source())
            .collect();

        assert_eq!(active_sources.len(), 1);
        assert_eq!(active_sources[0].path, "/photos");
    }

    // =========================================================================
    // batch_fetch_by_ids tests
    // =========================================================================

    #[test]
    fn batch_fetch_by_ids_empty() {
        let conn = setup_test_db();
        let roots = batch_fetch_by_ids(&conn, &[]).unwrap();
        assert!(roots.is_empty());
    }

    #[test]
    fn batch_fetch_by_ids_found() {
        let conn = setup_test_db();

        let id1 = insert_root(&conn, "/photos", "source", None, None, false);
        let id2 = insert_root(&conn, "/archive", "archive", None, None, false);

        let roots = batch_fetch_by_ids(&conn, &[id1, id2]).unwrap();
        assert_eq!(roots.len(), 2);

        // Verify O(1) lookup works
        assert_eq!(roots.get(&id1).unwrap().path, "/photos");
        assert_eq!(roots.get(&id2).unwrap().path, "/archive");
    }

    #[test]
    fn batch_fetch_by_ids_partial() {
        let conn = setup_test_db();

        let id1 = insert_root(&conn, "/photos", "source", None, None, false);

        // Query for mix of existing and non-existing IDs
        let roots = batch_fetch_by_ids(&conn, &[id1, 999, 1000]).unwrap();
        assert_eq!(roots.len(), 1);
        assert!(roots.contains_key(&id1));
        assert!(!roots.contains_key(&999));
    }

    #[test]
    fn batch_fetch_by_ids_no_matching() {
        let conn = setup_test_db();

        insert_root(&conn, "/photos", "source", None, None, false);

        let roots = batch_fetch_by_ids(&conn, &[999, 1000]).unwrap();
        assert!(roots.is_empty());
    }

    // =========================================================================
    // create tests
    // =========================================================================

    #[test]
    fn create_returns_complete_root() {
        let conn = setup_test_db();

        let root = create(&conn, "/photos", "source", None).unwrap();

        // Verify returned Root has all fields populated correctly
        assert!(root.id > 0);
        assert_eq!(root.path, "/photos");
        assert_eq!(root.role, "source");
        assert_eq!(root.comment, None);
        assert_eq!(root.last_scanned_at, None);
        assert!(!root.suspended);

        // Verify it matches what's in the database
        let roots = fetch_all(&conn).unwrap();
        assert_eq!(roots.len(), 1);
        assert_eq!(roots[0].id, root.id);
    }

    #[test]
    fn create_with_comment() {
        let conn = setup_test_db();

        let root = create(&conn, "/archive", "archive", Some("My archive")).unwrap();

        // Verify returned Root includes comment
        assert_eq!(root.path, "/archive");
        assert_eq!(root.role, "archive");
        assert_eq!(root.comment, Some("My archive".to_string()));

        // Verify it matches what's in the database
        let roots = fetch_all(&conn).unwrap();
        assert_eq!(roots.len(), 1);
        assert_eq!(roots[0].id, root.id);
        assert_eq!(roots[0].comment, Some("My archive".to_string()));
    }

    #[test]
    fn create_multiple_roots() {
        let conn = setup_test_db();

        let root1 = create(&conn, "/photos", "source", None).unwrap();
        let root2 = create(&conn, "/archive", "archive", None).unwrap();

        // Verify different IDs
        assert_ne!(root1.id, root2.id);

        // Verify returned objects have correct data
        assert_eq!(root1.path, "/photos");
        assert_eq!(root2.path, "/archive");

        let roots = fetch_all(&conn).unwrap();
        assert_eq!(roots.len(), 2);
    }

    // =========================================================================
    // update_last_scanned_at tests
    // =========================================================================

    #[test]
    fn update_last_scanned_at_sets_timestamp() {
        let conn = setup_test_db();
        let id = insert_root(&conn, "/photos", "source", None, None, false);

        // Initially None
        let roots = fetch_all(&conn).unwrap();
        assert!(roots[0].last_scanned_at.is_none());

        // Update timestamp
        update_last_scanned_at(&conn, id, 1700000001).unwrap();

        // Verify updated
        let roots = fetch_all(&conn).unwrap();
        assert_eq!(roots[0].last_scanned_at, Some(1700000001));
    }

    #[test]
    fn update_last_scanned_at_overwrites() {
        let conn = setup_test_db();
        let id = insert_root(&conn, "/photos", "source", None, Some(1700000000), false);

        update_last_scanned_at(&conn, id, 1700000001).unwrap();

        let roots = fetch_all(&conn).unwrap();
        assert_eq!(roots[0].last_scanned_at, Some(1700000001));
    }

    #[test]
    fn update_last_scanned_at_nonexistent_root() {
        let conn = setup_test_db();

        // Should not error when root doesn't exist
        let result = update_last_scanned_at(&conn, 99999, 1700000001);
        assert!(result.is_ok());
    }

    // =========================================================================
    // fetch_file_counts tests
    // =========================================================================

    /// Insert a test source and return its ID.
    fn insert_source(
        conn: &RusqliteConnection,
        root_id: i64,
        rel_path: &str,
        present: bool,
    ) -> i64 {
        conn.execute(
            "INSERT INTO sources (root_id, rel_path, present, device, inode, size, mtime, partial_hash, scanned_at, last_seen_at)
             VALUES (?, ?, ?, 1, 1, 100, 1700000000, 'testhash', 0, 0)",
            rusqlite::params![root_id, rel_path, present as i64],
        )
        .unwrap();
        conn.last_insert_rowid()
    }

    #[test]
    fn fetch_file_counts_empty_ids() {
        let conn = setup_test_db();
        let counts = fetch_file_counts(&conn, &[]).unwrap();
        assert!(counts.is_empty());
    }

    #[test]
    fn fetch_file_counts_root_with_sources() {
        let conn = setup_test_db();
        let root_id = insert_root(&conn, "/photos", "source", None, None, false);

        insert_source(&conn, root_id, "a.jpg", true);
        insert_source(&conn, root_id, "b.jpg", true);
        insert_source(&conn, root_id, "c.jpg", true);

        let counts = fetch_file_counts(&conn, &[root_id]).unwrap();
        assert_eq!(counts.get(&root_id), Some(&3));
    }

    #[test]
    fn fetch_file_counts_root_no_sources() {
        let conn = setup_test_db();
        let root_id = insert_root(&conn, "/photos", "source", None, None, false);

        let counts = fetch_file_counts(&conn, &[root_id]).unwrap();
        // Root with no sources is not in the result
        assert!(counts.get(&root_id).is_none());
    }

    #[test]
    fn fetch_file_counts_multiple_roots() {
        let conn = setup_test_db();
        let root1 = insert_root(&conn, "/photos", "source", None, None, false);
        let root2 = insert_root(&conn, "/archive", "archive", None, None, false);

        insert_source(&conn, root1, "a.jpg", true);
        insert_source(&conn, root1, "b.jpg", true);
        insert_source(&conn, root2, "c.jpg", true);

        let counts = fetch_file_counts(&conn, &[root1, root2]).unwrap();
        assert_eq!(counts.get(&root1), Some(&2));
        assert_eq!(counts.get(&root2), Some(&1));
    }

    #[test]
    fn fetch_file_counts_only_present() {
        let conn = setup_test_db();
        let root_id = insert_root(&conn, "/photos", "source", None, None, false);

        insert_source(&conn, root_id, "a.jpg", true);
        insert_source(&conn, root_id, "b.jpg", true);
        insert_source(&conn, root_id, "missing.jpg", false); // Not present

        let counts = fetch_file_counts(&conn, &[root_id]).unwrap();
        assert_eq!(counts.get(&root_id), Some(&2)); // Only counts present=1
    }

    // =========================================================================
    // set_suspended tests
    // =========================================================================

    #[test]
    fn set_suspended_activates() {
        let conn = setup_test_db();
        let root_id = insert_root(&conn, "/photos", "source", None, None, false);

        set_suspended(&conn, root_id, true).unwrap();

        let roots = fetch_all(&conn).unwrap();
        assert!(roots[0].is_suspended());
    }

    #[test]
    fn set_suspended_deactivates() {
        let conn = setup_test_db();
        let root_id = insert_root(&conn, "/photos", "source", None, None, true);

        set_suspended(&conn, root_id, false).unwrap();

        let roots = fetch_all(&conn).unwrap();
        assert!(!roots[0].is_suspended());
    }

    #[test]
    fn set_suspended_idempotent() {
        let conn = setup_test_db();
        let root_id = insert_root(&conn, "/photos", "source", None, None, true);

        // Setting same value should not error
        set_suspended(&conn, root_id, true).unwrap();

        let roots = fetch_all(&conn).unwrap();
        assert!(roots[0].is_suspended());
    }

    // =========================================================================
    // set_comment tests
    // =========================================================================

    #[test]
    fn set_comment_adds() {
        let conn = setup_test_db();
        let root_id = insert_root(&conn, "/photos", "source", None, None, false);

        set_comment(&conn, root_id, Some("My photos")).unwrap();

        let roots = fetch_all(&conn).unwrap();
        assert_eq!(roots[0].comment, Some("My photos".to_string()));
    }

    #[test]
    fn set_comment_updates() {
        let conn = setup_test_db();
        let root_id = insert_root(&conn, "/photos", "source", Some("Old comment"), None, false);

        set_comment(&conn, root_id, Some("New comment")).unwrap();

        let roots = fetch_all(&conn).unwrap();
        assert_eq!(roots[0].comment, Some("New comment".to_string()));
    }

    #[test]
    fn set_comment_clears() {
        let conn = setup_test_db();
        let root_id = insert_root(&conn, "/photos", "source", Some("Comment"), None, false);

        set_comment(&conn, root_id, None).unwrap();

        let roots = fetch_all(&conn).unwrap();
        assert_eq!(roots[0].comment, None);
    }

    // =========================================================================
    // remove tests
    // =========================================================================

    #[test]
    fn remove_empty_root() {
        let conn = setup_test_db();
        let root_id = insert_root(&conn, "/photos", "source", None, None, false);

        let deleted = remove(&conn, root_id).unwrap();

        assert_eq!(deleted, 0);
        let roots = fetch_all(&conn).unwrap();
        assert!(roots.is_empty());
    }

    #[test]
    fn remove_with_sources() {
        let conn = setup_test_db();
        let root_id = insert_root(&conn, "/photos", "source", None, None, false);

        insert_source(&conn, root_id, "a.jpg", true);
        insert_source(&conn, root_id, "b.jpg", true);
        insert_source(&conn, root_id, "c.jpg", true);

        let deleted = remove(&conn, root_id).unwrap();

        assert_eq!(deleted, 3);
        let roots = fetch_all(&conn).unwrap();
        assert!(roots.is_empty());
    }

    #[test]
    fn remove_deletes_facts() {
        let conn = setup_test_db();
        let root_id = insert_root(&conn, "/photos", "source", None, None, false);
        let source_id = insert_source(&conn, root_id, "a.jpg", true);

        // Insert a fact for this source
        conn.execute(
            "INSERT INTO facts (entity_type, entity_id, key, value_text, observed_at, observed_basis_rev)
             VALUES ('source', ?, 'test.key', 'test value', 0, 1)",
            [source_id],
        )
        .unwrap();

        // Verify fact exists
        let fact_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM facts", [], |row| row.get(0))
            .unwrap();
        assert_eq!(fact_count, 1);

        remove(&conn, root_id).unwrap();

        // Verify fact was deleted
        let fact_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM facts", [], |row| row.get(0))
            .unwrap();
        assert_eq!(fact_count, 0);
    }

    #[test]
    fn remove_deletes_root() {
        let conn = setup_test_db();
        let root_id = insert_root(&conn, "/photos", "source", None, None, false);

        remove(&conn, root_id).unwrap();

        let roots = fetch_all(&conn).unwrap();
        assert!(roots.is_empty());
    }
}