cora-code 0.9.0

CLI-first AI code review — BYOK, diff/scan/branch, pre-commit hooks
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
//! SQLite schema management for the symbol index.

use rusqlite::Connection;

/// Current schema version.
#[allow(dead_code)]
const SCHEMA_VERSION: i32 = 5;

/// Run database migrations (creates tables if not exist).
pub fn run_migrations(conn: &Connection) -> anyhow::Result<()> {
    // Schema version tracking
    conn.execute_batch(
        "CREATE TABLE IF NOT EXISTS schema_version (
            version INTEGER PRIMARY KEY,
            applied_at TEXT DEFAULT (datetime('now'))
        );",
    )?;

    let current: i32 = conn
        .query_row("SELECT MAX(version) FROM schema_version", [], |row| {
            row.get(0)
        })
        .unwrap_or(0);

    if current < 1 {
        migrate_v1(conn)?;
    }
    if current < 2 {
        migrate_v2(conn)?;
    }
    if current < 3 {
        migrate_v3(conn)?;
    }
    if current < 4 {
        migrate_v4(conn)?;
    }
    if current < 5 {
        migrate_v5(conn)?;
    }

    Ok(())
}

/// Migration v1: Initial schema — symbols, files, FTS5 index.
fn migrate_v1(conn: &Connection) -> anyhow::Result<()> {
    conn.execute_batch(
        "
        -- Symbol definitions extracted from source files
        CREATE TABLE IF NOT EXISTS symbols (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            name        TEXT NOT NULL,
            kind        TEXT NOT NULL,
            file        TEXT NOT NULL,
            line        INTEGER NOT NULL,
            signature   TEXT NOT NULL DEFAULT '',
            language    TEXT NOT NULL DEFAULT 'unknown',
            created_at  TEXT DEFAULT (datetime('now'))
        );

        -- Index for file-based queries
        CREATE INDEX IF NOT EXISTS idx_symbols_file ON symbols(file);

        -- Index for name-based lookups
        CREATE INDEX IF NOT EXISTS idx_symbols_name ON symbols(name);

        -- Index for kind-based filtering
        CREATE INDEX IF NOT EXISTS idx_symbols_kind ON symbols(kind);

        -- File tracking for incremental indexing
        CREATE TABLE IF NOT EXISTS files (
            path          TEXT PRIMARY KEY,
            fingerprint   TEXT NOT NULL,
            last_indexed  TEXT NOT NULL,
            language      TEXT NOT NULL DEFAULT 'unknown',
            symbol_count  INTEGER NOT NULL DEFAULT 0
        );

        -- FTS5 virtual table for full-text search on symbol names
        CREATE VIRTUAL TABLE IF NOT EXISTS symbols_fts USING fts5(
            name,
            signature,
            content='symbols',
            content_rowid='id',
            tokenize='unicode61 remove_diacritics 1'
        );

        -- Call graph edges: caller → callee relationships
        CREATE TABLE IF NOT EXISTS call_graph (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            caller      TEXT NOT NULL,
            callee      TEXT NOT NULL,
            file        TEXT NOT NULL,
            line        INTEGER NOT NULL
        );

        CREATE INDEX IF NOT EXISTS idx_cg_caller ON call_graph(caller);
        CREATE INDEX IF NOT EXISTS idx_cg_callee ON call_graph(callee);
        CREATE INDEX IF NOT EXISTS idx_cg_file ON call_graph(file);

        -- Triggers to keep FTS5 in sync with symbols table
        CREATE TRIGGER IF NOT EXISTS symbols_fts_insert
        AFTER INSERT ON symbols
        BEGIN
            INSERT INTO symbols_fts(rowid, name, signature)
            VALUES (new.id, new.name, new.signature);
        END;

        CREATE TRIGGER IF NOT EXISTS symbols_fts_delete
        AFTER DELETE ON symbols
        BEGIN
            INSERT INTO symbols_fts(symbols_fts, rowid, name, signature)
            VALUES ('delete', old.id, old.name, old.signature);
        END;

        CREATE TRIGGER IF NOT EXISTS symbols_fts_update
        AFTER UPDATE ON symbols
        BEGIN
            INSERT INTO symbols_fts(symbols_fts, rowid, name, signature)
            VALUES ('delete', old.id, old.name, old.signature);
            INSERT INTO symbols_fts(rowid, name, signature)
            VALUES (new.id, new.name, new.signature);
        END;
        ",
    )?;

    conn.execute("INSERT INTO schema_version (version) VALUES (1)", [])?;

    Ok(())
}

/// Migration v2: Multi-project support.
///
/// Adds `projects` table and `project_id` column to `symbols`, `files`,
/// and `call_graph`. The global DB at `~/.codecora/cora-code/cora.db`
/// stores data for all indexed projects, keyed by absolute path.
fn migrate_v2(conn: &Connection) -> anyhow::Result<()> {
    conn.execute_batch(
        "
        -- Projects table: one row per indexed codebase
        CREATE TABLE IF NOT EXISTS projects (
            id            INTEGER PRIMARY KEY AUTOINCREMENT,
            root_path     TEXT NOT NULL UNIQUE,
            name          TEXT NOT NULL DEFAULT '',
            last_indexed  TEXT NOT NULL DEFAULT (datetime('now')),
            created_at    TEXT NOT NULL DEFAULT (datetime('now'))
        );

        -- Add project_id to symbols (nullable for migration compat)
        ALTER TABLE symbols ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE CASCADE;
        CREATE INDEX IF NOT EXISTS idx_symbols_project ON symbols(project_id);

        -- Add project_id to files (nullable for migration compat)
        ALTER TABLE files ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE CASCADE;
        CREATE INDEX IF NOT EXISTS idx_files_project ON files(project_id);

        -- Add project_id to call_graph (nullable for migration compat)
        ALTER TABLE call_graph ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE CASCADE;
        CREATE INDEX IF NOT EXISTS idx_cg_project ON call_graph(project_id);
        ",
    )?;

    conn.execute("INSERT INTO schema_version (version) VALUES (2)", [])?;

    Ok(())
}

/// Migration v3: Knowledge graph edges.
///
/// Adds `edges` table — a richer version of `call_graph` that supports
/// multiple edge types (CALLS, IMPORTS, IMPLEMENTS, INHERITS, CHILD_OF).
/// Existing `call_graph` rows are migrated into `edges` with kind='CALLS'.
fn migrate_v3(conn: &Connection) -> anyhow::Result<()> {
    conn.execute_batch(
        "
        -- Knowledge graph edges: source → target with typed relationship
        CREATE TABLE IF NOT EXISTS edges (
            id          INTEGER PRIMARY KEY AUTOINCREMENT,
            source      TEXT NOT NULL,
            kind        TEXT NOT NULL,
            target      TEXT NOT NULL,
            file        TEXT NOT NULL,
            line        INTEGER NOT NULL,
            project_id  INTEGER REFERENCES projects(id) ON DELETE CASCADE
        );

        CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source);
        CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target);
        CREATE INDEX IF NOT EXISTS idx_edges_kind ON edges(kind);
        CREATE INDEX IF NOT EXISTS idx_edges_project ON edges(project_id);
        CREATE INDEX IF NOT EXISTS idx_edges_file ON edges(file);

        -- Migrate existing call_graph data into edges
        INSERT OR IGNORE INTO edges (source, kind, target, file, line, project_id)
            SELECT caller, 'CALLS', callee, file, line, project_id FROM call_graph;
        ",
    )?;

    conn.execute("INSERT INTO schema_version (version) VALUES (3)", [])?;

    Ok(())
}

/// Migration v4: Embedding metadata on projects table.
fn migrate_v4(conn: &Connection) -> anyhow::Result<()> {
    conn.execute_batch(
        "
        ALTER TABLE projects ADD COLUMN embedding_tier TEXT NOT NULL DEFAULT 'static';
        ALTER TABLE projects ADD COLUMN embedding_dims INTEGER NOT NULL DEFAULT 256;
        ALTER TABLE projects ADD COLUMN last_embedded_at TEXT;
        ",
    )?;

    conn.execute("INSERT INTO schema_version (version) VALUES (4)", [])?;

    Ok(())
}

/// Migration v5: Review history — reviews, findings, finding_events.
///
/// Enables persistent storage of review/scan results in the same `cora.db`.
/// This replaces the legacy JSON snapshot files in `.cora/history/`.
fn migrate_v5(conn: &Connection) -> anyhow::Result<()> {
    conn.execute_batch(
        "
        -- One row per review/scan run
        CREATE TABLE IF NOT EXISTS reviews (
            id              INTEGER PRIMARY KEY AUTOINCREMENT,
            project_id      INTEGER REFERENCES projects(id) ON DELETE CASCADE,
            command         TEXT NOT NULL DEFAULT 'review',
            commit_hash     TEXT,
            branch          TEXT,
            summary         TEXT NOT NULL DEFAULT '',
            score           INTEGER NOT NULL DEFAULT 0,
            gate_status     TEXT NOT NULL DEFAULT 'disabled',
            files_scanned   INTEGER NOT NULL DEFAULT 0,
            lines_scanned   INTEGER NOT NULL DEFAULT 0,
            should_block    INTEGER NOT NULL DEFAULT 0,
            input_tokens    INTEGER NOT NULL DEFAULT 0,
            output_tokens   INTEGER NOT NULL DEFAULT 0,
            cost_usd        REAL NOT NULL DEFAULT 0.0,
            created_at      TEXT NOT NULL DEFAULT (datetime('now'))
        );

        CREATE INDEX IF NOT EXISTS idx_reviews_project ON reviews(project_id);
        CREATE INDEX IF NOT EXISTS idx_reviews_created ON reviews(created_at);
        CREATE INDEX IF NOT EXISTS idx_reviews_command ON reviews(command);

        -- Individual findings (issues) from each review/scan
        CREATE TABLE IF NOT EXISTS findings (
            id              INTEGER PRIMARY KEY AUTOINCREMENT,
            review_id       INTEGER NOT NULL REFERENCES reviews(id) ON DELETE CASCADE,
            file_path       TEXT NOT NULL,
            line_number     INTEGER,
            severity        TEXT NOT NULL DEFAULT 'info',
            issue_type      TEXT,
            title           TEXT NOT NULL DEFAULT '',
            body            TEXT NOT NULL DEFAULT '',
            suggested_fix   TEXT,
            status          TEXT NOT NULL DEFAULT 'open',
            fingerprint     TEXT,
            created_at      TEXT NOT NULL DEFAULT (datetime('now'))
        );

        CREATE INDEX IF NOT EXISTS idx_findings_review ON findings(review_id);
        CREATE INDEX IF NOT EXISTS idx_findings_status ON findings(status);
        CREATE INDEX IF NOT EXISTS idx_findings_severity ON findings(severity);
        CREATE INDEX IF NOT EXISTS idx_findings_file ON findings(file_path);
        CREATE INDEX IF NOT EXISTS idx_findings_fingerprint ON findings(fingerprint);

        -- Audit trail for finding status changes
        CREATE TABLE IF NOT EXISTS finding_events (
            id              INTEGER PRIMARY KEY AUTOINCREMENT,
            finding_id      INTEGER NOT NULL REFERENCES findings(id) ON DELETE CASCADE,
            event_type      TEXT NOT NULL,  -- 'opened', 'auto_resolved', 'dismissed', 'reopened'
            note            TEXT,
            created_at      TEXT NOT NULL DEFAULT (datetime('now'))
        );

        CREATE INDEX IF NOT EXISTS idx_fevents_finding ON finding_events(finding_id);
        CREATE INDEX IF NOT EXISTS idx_fevents_type ON finding_events(event_type);
        ",
    )?;

    conn.execute("INSERT INTO schema_version (version) VALUES (5)", [])?;

    Ok(())
}

/// Get or create a project entry by root path.
///
/// Returns the project ID.
pub fn get_or_create_project(conn: &Connection, root_path: &str) -> anyhow::Result<i64> {
    // Try to find existing project
    let existing: Option<i64> = conn
        .query_row(
            "SELECT id FROM projects WHERE root_path = ?1",
            rusqlite::params![root_path],
            |row| row.get(0),
        )
        .ok();

    if let Some(id) = existing {
        return Ok(id);
    }

    // Extract project name from directory name
    let name = std::path::Path::new(root_path)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("unknown");

    conn.execute(
        "INSERT INTO projects (root_path, name) VALUES (?1, ?2)",
        rusqlite::params![root_path, name],
    )?;

    Ok(conn.last_insert_rowid())
}

/// Remove a project and all its associated data (CASCADE).
///
/// Returns the number of rows deleted.
pub fn delete_project(conn: &Connection, project_id: i64) -> anyhow::Result<usize> {
    let affected = conn.execute(
        "DELETE FROM projects WHERE id = ?1",
        rusqlite::params![project_id],
    )?;
    Ok(affected)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn mem_conn() -> Connection {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch("PRAGMA foreign_keys=ON;").unwrap();
        run_migrations(&conn).unwrap();
        conn
    }

    #[test]
    fn test_migration_creates_tables() {
        let conn = mem_conn();

        // Check symbols table
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM symbols", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);

        // Check files table
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM files", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);

        // Check FTS table exists
        conn.query_row("SELECT COUNT(*) FROM symbols_fts", [], |row| {
            row.get::<_, i64>(0)
        })
        .unwrap();

        // Check projects table
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM projects", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);

        // Check schema version
        let version: i32 = conn
            .query_row("SELECT MAX(version) FROM schema_version", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(version, SCHEMA_VERSION);
    }

    #[test]
    fn test_migration_idempotent() {
        let conn = mem_conn();
        // Running again should not error
        run_migrations(&conn).unwrap();
    }

    #[test]
    fn test_v2_project_columns_exist() {
        let conn = mem_conn();

        // Verify project_id column exists on symbols
        let _: i64 = conn
            .query_row("SELECT project_id FROM symbols LIMIT 0", [], |row| {
                row.get(0)
            })
            .unwrap_or(0);

        // Verify project_id column exists on files
        let _: i64 = conn
            .query_row("SELECT project_id FROM files LIMIT 0", [], |row| row.get(0))
            .unwrap_or(0);

        // Verify project_id column exists on call_graph
        let _: i64 = conn
            .query_row("SELECT project_id FROM call_graph LIMIT 0", [], |row| {
                row.get(0)
            })
            .unwrap_or(0);
    }

    #[test]
    fn test_get_or_create_project() {
        let conn = mem_conn();

        // Create project
        let id1 = get_or_create_project(&conn, "/home/user/myproject").unwrap();
        assert!(id1 > 0);

        // Same path returns same id
        let id2 = get_or_create_project(&conn, "/home/user/myproject").unwrap();
        assert_eq!(id1, id2);

        // Different path returns different id
        let id3 = get_or_create_project(&conn, "/home/user/other").unwrap();
        assert_ne!(id1, id3);

        // Check name extraction
        let name: String = conn
            .query_row(
                "SELECT name FROM projects WHERE id = ?1",
                rusqlite::params![id1],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(name, "myproject");
    }

    #[test]
    fn test_delete_project_cascades() {
        let conn = mem_conn();

        let pid = get_or_create_project(&conn, "/tmp/testproj").unwrap();

        // Insert symbol and file linked to project
        conn.execute(
            "INSERT INTO symbols (name, kind, file, line, project_id) VALUES ('test_fn', 'function', 'main.rs', 1, ?1)",
            rusqlite::params![pid],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO files (path, fingerprint, last_indexed, project_id) VALUES ('main.rs', 'abc', datetime('now'), ?1)",
            rusqlite::params![pid],
        )
        .unwrap();

        // Delete project
        delete_project(&conn, pid).unwrap();

        // Symbols and files should be cascade-deleted
        let sym_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM symbols", [], |row| row.get(0))
            .unwrap();
        assert_eq!(sym_count, 0);

        let file_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM files", [], |row| row.get(0))
            .unwrap();
        assert_eq!(file_count, 0);

        let proj_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM projects", [], |row| row.get(0))
            .unwrap();
        assert_eq!(proj_count, 0);
    }

    #[test]
    fn test_v3_edges_table() {
        let conn = mem_conn();
        let pid = get_or_create_project(&conn, "/test/proj").unwrap();

        // Check edges table exists
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM edges", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);

        // Insert an edge
        conn.execute(
            "INSERT INTO edges (source, kind, target, file, line, project_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
            rusqlite::params!["Cache", "IMPLEMENTS", "Store", "cache.rs", 10, pid],
        )
        .unwrap();

        // Query it back
        let (source, kind, target): (String, String, String) = conn
            .query_row(
                "SELECT source, kind, target FROM edges WHERE kind = 'IMPLEMENTS'",
                [],
                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
            )
            .unwrap();
        assert_eq!(source, "Cache");
        assert_eq!(kind, "IMPLEMENTS");
        assert_eq!(target, "Store");
    }

    #[test]
    fn test_v3_migrate_call_graph() {
        let conn = mem_conn();
        let pid = get_or_create_project(&conn, "/test/proj").unwrap();

        // Insert into old call_graph
        conn.execute(
            "INSERT INTO call_graph (caller, callee, file, line, project_id) VALUES (?1, ?2, ?3, ?4, ?5)",
            rusqlite::params!["main", "helper", "main.rs", 5, pid],
        )
        .unwrap();

        // Migration already ran, so edges should be empty
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM edges WHERE kind = 'CALLS'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count, 0);

        // Manually verify the migration SQL works
        conn.execute(
            "INSERT OR IGNORE INTO edges (source, kind, target, file, line, project_id) SELECT caller, 'CALLS', callee, file, line, project_id FROM call_graph",
            [],
        )
        .unwrap();

        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM edges WHERE kind = 'CALLS'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn test_v5_review_tables_exist() {
        let conn = mem_conn();

        // Check reviews table
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM reviews", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);

        // Check findings table
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM findings", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);

        // Check finding_events table
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM finding_events", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);

        // Verify schema version is 5
        let version: i32 = conn
            .query_row("SELECT MAX(version) FROM schema_version", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(version, SCHEMA_VERSION);
        assert_eq!(version, 5);
    }

    #[test]
    fn test_v5_insert_review_and_findings() {
        let conn = mem_conn();
        let pid = get_or_create_project(&conn, "/test/proj").unwrap();

        // Insert a review
        conn.execute(
            "INSERT INTO reviews (project_id, command, commit_hash, branch, summary, score, files_scanned, lines_scanned)
             VALUES (?1, 'review', 'abc123', 'main', '3 issues found', 75, 5, 200)",
            rusqlite::params![pid],
        )
        .unwrap();
        let review_id: i64 = conn.last_insert_rowid();

        // Insert findings
        conn.execute(
            "INSERT INTO findings (review_id, file_path, line_number, severity, title, body, fingerprint)
             VALUES (?1, 'src/main.rs', 42, 'critical', 'SQL injection', 'Unsanitized input', 'main.rs:42:sql_injection')",
            rusqlite::params![review_id],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO findings (review_id, file_path, line_number, severity, title, body, fingerprint)
             VALUES (?1, 'src/lib.rs', 10, 'minor', 'Unused import', 'Import not used', 'lib.rs:10:unused_import')",
            rusqlite::params![review_id],
        )
        .unwrap();

        // Query back
        let finding_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM findings WHERE review_id = ?1",
                rusqlite::params![review_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(finding_count, 2);

        // Insert an event
        let finding_id: i64 = conn.last_insert_rowid();
        conn.execute(
            "INSERT INTO finding_events (finding_id, event_type, note) VALUES (?1, 'opened', NULL)",
            rusqlite::params![finding_id],
        )
        .unwrap();

        let event_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM finding_events WHERE finding_id = ?1",
                rusqlite::params![finding_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(event_count, 1);
    }
}