coraline 0.8.0

Coraline: semantic code knowledge graph for faster AI-assisted development.
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
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
#![forbid(unsafe_code)]

use std::path::{Path, PathBuf};

use rusqlite::{Connection, OptionalExtension, params};
use tracing::{debug, warn};

use crate::types::{
    Edge, EdgeKind, FileRecord, Language, Node, NodeKind, SearchResult, UnresolvedReference,
    Visibility,
};

pub const DATABASE_FILENAME: &str = "coraline.db";
pub const SCHEMA_SQL: &str = include_str!("db/schema.sql");

/// PRAGMAs applied on every connection open.
///
/// - `foreign_keys = ON`   — enforce referential integrity
/// - `journal_mode = WAL`  — concurrent readers, faster writes
/// - `synchronous = NORMAL`— durable on OS crash, faster than FULL
/// - `cache_size = -65536` — 64 MB page cache (negative = KiB)
/// - `temp_store = MEMORY` — temp tables in RAM
/// - `mmap_size = 268435456` — 256 MB memory-mapped I/O
const PERF_PRAGMAS: &str = "
    PRAGMA foreign_keys  = ON;
    PRAGMA journal_mode  = WAL;
    PRAGMA synchronous   = NORMAL;
    PRAGMA cache_size    = -65536;
    PRAGMA temp_store    = MEMORY;
    PRAGMA mmap_size     = 268435456;
";

#[derive(Debug, Default)]
pub struct Database;

#[derive(Debug, Clone)]
pub struct UnresolvedRefRow {
    pub id: i64,
    pub reference: UnresolvedReference,
}

fn io_other(err: impl std::error::Error + Send + Sync + 'static) -> std::io::Error {
    std::io::Error::other(err)
}

pub fn database_path(project_root: &Path) -> PathBuf {
    project_root.join(".coraline").join(DATABASE_FILENAME)
}

pub fn initialize_database(project_root: &Path) -> std::io::Result<PathBuf> {
    let db_path = database_path(project_root);
    debug!(path = %db_path.display(), "initializing database");

    if let Some(parent) = db_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    let conn = rusqlite::Connection::open(&db_path).map_err(io_other)?;
    conn.execute_batch(PERF_PRAGMAS).map_err(io_other)?;
    conn.execute_batch(SCHEMA_SQL).map_err(io_other)?;
    Ok(db_path)
}

pub fn open_database(project_root: &Path) -> std::io::Result<Connection> {
    let db_path = database_path(project_root);
    let conn = Connection::open(&db_path).map_err(io_other)?;
    conn.execute_batch(PERF_PRAGMAS).map_err(io_other)?;
    Ok(conn)
}

pub fn clear_database(conn: &Connection) -> std::io::Result<()> {
    conn.execute_batch(
        "DELETE FROM unresolved_refs;
         DELETE FROM vectors;
         DELETE FROM edges;
         DELETE FROM nodes;
         DELETE FROM files;",
    )
    .map_err(io_other)
}

pub fn get_file_record(conn: &Connection, path: &str) -> std::io::Result<Option<FileRecord>> {
    let row = conn
        .query_row(
            "SELECT path, content_hash, language, size, modified_at, indexed_at, node_count, errors FROM files WHERE path = ?",
            params![path],
            |row| {
                let errors: Option<String> = row.get(7)?;
                let language_raw: String = row.get(2)?;
                Ok(FileRecord {
                    path: row.get(0)?,
                    content_hash: row.get(1)?,
                    language: parse_language(&language_raw),
                    size: u64::try_from(row.get::<_, i64>(3)?).unwrap_or(0),
                    modified_at: row.get(4)?,
                    indexed_at: row.get(5)?,
                    node_count: row.get(6)?,
                    errors: errors
                        .and_then(|raw| serde_json::from_str(&raw).ok()),
                })
            },
        )
        .optional()
        .map_err(io_other)?;

    Ok(row)
}

pub fn list_files(conn: &Connection) -> std::io::Result<Vec<FileRecord>> {
    let mut stmt = conn
        .prepare(
            "SELECT path, content_hash, language, size, modified_at, indexed_at, node_count, errors FROM files",
        )
        .map_err(io_other)?;
    let rows = stmt
        .query_map([], |row| {
            let errors: Option<String> = row.get(7)?;
            let language_raw: String = row.get(2)?;
            Ok(FileRecord {
                path: row.get(0)?,
                content_hash: row.get(1)?,
                language: parse_language(&language_raw),
                size: u64::try_from(row.get::<_, i64>(3)?).unwrap_or(0),
                modified_at: row.get(4)?,
                indexed_at: row.get(5)?,
                node_count: row.get(6)?,
                errors: errors.and_then(|raw| serde_json::from_str(&raw).ok()),
            })
        })
        .map_err(io_other)?;

    let mut results = Vec::new();
    for row in rows {
        results.push(row.map_err(io_other)?);
    }
    Ok(results)
}

pub fn upsert_file(conn: &Connection, file: &FileRecord) -> std::io::Result<()> {
    let errors = file
        .errors
        .as_ref()
        .map(|errs| serde_json::to_string(errs).unwrap_or_default());
    conn.execute(
        "INSERT INTO files (path, content_hash, language, size, modified_at, indexed_at, node_count, errors)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)
         ON CONFLICT(path) DO UPDATE SET
            content_hash = excluded.content_hash,
            language = excluded.language,
            size = excluded.size,
            modified_at = excluded.modified_at,
            indexed_at = excluded.indexed_at,
            node_count = excluded.node_count,
            errors = excluded.errors",
        params![
            file.path,
            file.content_hash,
            language_to_string(file.language),
            i64::try_from(file.size).unwrap_or(i64::MAX),
            file.modified_at,
            file.indexed_at,
            file.node_count,
            errors,
        ],
    )
    .map_err(io_other)?;
    Ok(())
}

pub fn insert_nodes(conn: &mut Connection, nodes: &[Node]) -> std::io::Result<()> {
    let tx = conn.transaction().map_err(io_other)?;
    {
        let mut stmt = tx
            .prepare(
                "INSERT INTO nodes (
                    id, kind, name, qualified_name, file_path, language,
                    start_line, end_line, start_column, end_column,
                    docstring, signature, visibility,
                    is_exported, is_async, is_static, is_abstract,
                    decorators, type_parameters, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            )
            .map_err(io_other)?;

        for node in nodes {
            let decorators = node
                .decorators
                .as_ref()
                .map(|vals| serde_json::to_string(vals).unwrap_or_default());
            let type_parameters = node
                .type_parameters
                .as_ref()
                .map(|vals| serde_json::to_string(vals).unwrap_or_default());
            let visibility = node.visibility.map(visibility_to_string);
            stmt.execute(params![
                node.id,
                kind_to_string(node.kind),
                node.name,
                node.qualified_name,
                node.file_path,
                language_to_string(node.language),
                node.start_line,
                node.end_line,
                node.start_column,
                node.end_column,
                node.docstring,
                node.signature,
                visibility,
                i32::from(node.is_exported),
                i32::from(node.is_async),
                i32::from(node.is_static),
                i32::from(node.is_abstract),
                decorators,
                type_parameters,
                node.updated_at,
            ])
            .map_err(io_other)?;
        }
    }
    tx.commit().map_err(io_other)
}

pub fn insert_edges(conn: &mut Connection, edges: &[Edge]) -> std::io::Result<()> {
    let tx = conn.transaction().map_err(io_other)?;
    {
        let mut stmt = tx
            .prepare(
                "INSERT INTO edges (source, target, kind, metadata, line, col)
                 VALUES (?, ?, ?, ?, ?, ?)",
            )
            .map_err(io_other)?;

        for edge in edges {
            let metadata = edge
                .metadata
                .as_ref()
                .map(|vals| serde_json::to_string(vals).unwrap_or_default());
            stmt.execute(params![
                edge.source,
                edge.target,
                edge_kind_to_string(edge.kind),
                metadata,
                edge.line,
                edge.column,
            ])
            .map_err(io_other)?;
        }
    }
    tx.commit().map_err(io_other)
}

pub fn insert_unresolved_refs(
    conn: &mut Connection,
    refs: &[UnresolvedReference],
) -> std::io::Result<()> {
    let tx = conn.transaction().map_err(io_other)?;
    {
        let mut stmt = tx
            .prepare(
                "INSERT INTO unresolved_refs (
                    from_node_id, reference_name, reference_kind, line, col, candidates
                 ) VALUES (?, ?, ?, ?, ?, ?)",
            )
            .map_err(io_other)?;

        for unresolved in refs {
            let candidates = unresolved
                .candidates
                .as_ref()
                .map(|vals| serde_json::to_string(vals).unwrap_or_default());
            stmt.execute(params![
                unresolved.from_node_id,
                unresolved.reference_name,
                edge_kind_to_string(unresolved.reference_kind),
                unresolved.line,
                unresolved.column,
                candidates,
            ])
            .map_err(io_other)?;
        }
    }
    tx.commit().map_err(io_other)
}

/// Store a fully-parsed file's results in a single `SQLite` transaction:
/// nodes, edges, unresolved refs, and the file metadata record.
///
/// This is more efficient than the three separate `insert_nodes` /
/// `insert_edges` / `insert_unresolved_refs` calls because it incurs only
/// one transaction commit instead of three.
#[allow(clippy::too_many_lines)]
pub fn store_file_batch(
    conn: &mut Connection,
    file_record: &FileRecord,
    nodes: &[Node],
    edges: &[Edge],
    unresolved_refs: &[UnresolvedReference],
) -> std::io::Result<()> {
    let tx = conn.transaction().map_err(io_other)?;

    // Nodes
    if !nodes.is_empty() {
        let mut stmt = tx
            .prepare(
                "INSERT INTO nodes (
                    id, kind, name, qualified_name, file_path, language,
                    start_line, end_line, start_column, end_column,
                    docstring, signature, visibility,
                    is_exported, is_async, is_static, is_abstract,
                    decorators, type_parameters, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            )
            .map_err(io_other)?;
        for node in nodes {
            let decorators = node
                .decorators
                .as_ref()
                .map(|v| serde_json::to_string(v).unwrap_or_default());
            let type_parameters = node
                .type_parameters
                .as_ref()
                .map(|v| serde_json::to_string(v).unwrap_or_default());
            let visibility = node.visibility.map(visibility_to_string);
            stmt.execute(params![
                node.id,
                kind_to_string(node.kind),
                node.name,
                node.qualified_name,
                node.file_path,
                language_to_string(node.language),
                node.start_line,
                node.end_line,
                node.start_column,
                node.end_column,
                node.docstring,
                node.signature,
                visibility,
                i32::from(node.is_exported),
                i32::from(node.is_async),
                i32::from(node.is_static),
                i32::from(node.is_abstract),
                decorators,
                type_parameters,
                node.updated_at,
            ])
            .map_err(io_other)?;
        }
    }

    // Edges
    if !edges.is_empty() {
        let mut stmt = tx
            .prepare(
                "INSERT INTO edges (source, target, kind, metadata, line, col)
                 VALUES (?, ?, ?, ?, ?, ?)",
            )
            .map_err(io_other)?;
        for edge in edges {
            let metadata = edge
                .metadata
                .as_ref()
                .map(|v| serde_json::to_string(v).unwrap_or_default());
            stmt.execute(params![
                edge.source,
                edge.target,
                edge_kind_to_string(edge.kind),
                metadata,
                edge.line,
                edge.column,
            ])
            .map_err(io_other)?;
        }
    }

    // Unresolved references
    if !unresolved_refs.is_empty() {
        let mut stmt = tx
            .prepare(
                "INSERT INTO unresolved_refs (
                    from_node_id, reference_name, reference_kind, line, col, candidates
                 ) VALUES (?, ?, ?, ?, ?, ?)",
            )
            .map_err(io_other)?;
        for r in unresolved_refs {
            let candidates = r
                .candidates
                .as_ref()
                .map(|v| serde_json::to_string(v).unwrap_or_default());
            stmt.execute(params![
                r.from_node_id,
                r.reference_name,
                edge_kind_to_string(r.reference_kind),
                r.line,
                r.column,
                candidates,
            ])
            .map_err(io_other)?;
        }
    }

    // File record (upsert)
    let errors = file_record
        .errors
        .as_ref()
        .map(|e| serde_json::to_string(e).unwrap_or_default());
    tx.execute(
        "INSERT INTO files (path, content_hash, language, size, modified_at, indexed_at, node_count, errors)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)
         ON CONFLICT(path) DO UPDATE SET
            content_hash = excluded.content_hash,
            language = excluded.language,
            size = excluded.size,
            modified_at = excluded.modified_at,
            indexed_at = excluded.indexed_at,
            node_count = excluded.node_count,
            errors = excluded.errors",
        params![
            file_record.path,
            file_record.content_hash,
            language_to_string(file_record.language),
            i64::try_from(file_record.size).unwrap_or(i64::MAX),
            file_record.modified_at,
            file_record.indexed_at,
            file_record.node_count,
            errors,
        ],
    )
    .map_err(io_other)?;

    tx.commit().map_err(|err| {
        warn!(file = %file_record.path, error = %err, "store_file_batch commit failed");
        io_other(err)
    })
}

pub fn search_nodes(
    conn: &Connection,
    query: &str,
    kind: Option<NodeKind>,
    limit: usize,
) -> std::io::Result<Vec<SearchResult>> {
    let Some(fts_query) = build_fts_query(query) else {
        return Ok(Vec::new());
    };

    // First try FTS search for better matching
    let mut sql = String::from(
        "SELECT n.id, n.kind, n.name, n.qualified_name, n.file_path, n.language,
                n.start_line, n.end_line, n.start_column, n.end_column,
                n.docstring, n.signature, n.visibility,
                n.is_exported, n.is_async, n.is_static, n.is_abstract,
                n.decorators, n.type_parameters, n.updated_at,
                fts.rank AS score
         FROM nodes n
         INNER JOIN nodes_fts fts ON n.rowid = fts.rowid
         WHERE nodes_fts MATCH ?",
    );

    let mut params_vec: Vec<String> = vec![fts_query];

    if let Some(kind) = kind {
        sql.push_str(" AND n.kind = ?");
        params_vec.push(kind_to_string(kind));
    }

    sql.push_str(" ORDER BY score ASC, length(n.name) ASC LIMIT ?");
    params_vec.push(limit.to_string());

    let mut stmt = conn.prepare(&sql).map_err(io_other)?;
    let rows = stmt
        .query_map(rusqlite::params_from_iter(params_vec), |row| {
            // FTS rank is negative, convert to positive score (higher = better)
            let rank: f64 = row.get(20)?;
            #[allow(clippy::cast_possible_truncation)]
            let score = (-rank) as f32;
            Ok(SearchResult {
                node: row_to_node(row)?,
                score,
                highlights: None,
            })
        })
        .map_err(io_other)?;

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

    Ok(results)
}

fn build_fts_query(query: &str) -> Option<String> {
    let mut terms = query
        .split_whitespace()
        .map(|term| format!("\"{}\"", term.replace('"', "\"\"")));

    let first = terms.next()?;
    let fts_query = terms.fold(first, |mut acc, term| {
        acc.push_str(" OR ");
        acc.push_str(&term);
        acc
    });

    Some(fts_query)
}

pub fn find_nodes_by_name(conn: &Connection, name: &str) -> std::io::Result<Vec<Node>> {
    let mut stmt = conn
        .prepare(
            "SELECT id, kind, name, qualified_name, file_path, language,
                    start_line, end_line, start_column, end_column,
                    docstring, signature, visibility,
                    is_exported, is_async, is_static, is_abstract,
                    decorators, type_parameters, updated_at
             FROM nodes WHERE name = ?",
        )
        .map_err(io_other)?;
    let rows = stmt
        .query_map(params![name], row_to_node)
        .map_err(io_other)?;

    let mut results = Vec::new();
    for row in rows {
        results.push(row.map_err(io_other)?);
    }
    Ok(results)
}

pub fn find_exports_by_module(conn: &Connection, module_path: &str) -> std::io::Result<Vec<Node>> {
    let mut stmt = conn
        .prepare(
            "SELECT id, kind, name, qualified_name, file_path, language,
                    start_line, end_line, start_column, end_column,
                    docstring, signature, visibility,
                    is_exported, is_async, is_static, is_abstract,
                    decorators, type_parameters, updated_at
             FROM nodes WHERE kind = ? AND signature = ?",
        )
        .map_err(io_other)?;
    let rows = stmt
        .query_map(
            params![kind_to_string(NodeKind::Export), module_path],
            row_to_node,
        )
        .map_err(io_other)?;

    let mut results = Vec::new();
    for row in rows {
        results.push(row.map_err(io_other)?);
    }
    Ok(results)
}

pub fn get_node_by_id(conn: &Connection, node_id: &str) -> std::io::Result<Option<Node>> {
    let row = conn
        .query_row(
            "SELECT id, kind, name, qualified_name, file_path, language,
                    start_line, end_line, start_column, end_column,
                    docstring, signature, visibility,
                    is_exported, is_async, is_static, is_abstract,
                    decorators, type_parameters, updated_at
             FROM nodes WHERE id = ?",
            params![node_id],
            row_to_node,
        )
        .optional()
        .map_err(io_other)?;

    Ok(row)
}

pub fn get_edges_by_source(
    conn: &Connection,
    source_id: &str,
    kind: Option<EdgeKind>,
    limit: usize,
) -> std::io::Result<Vec<Edge>> {
    let mut sql = String::from(
        "SELECT source, target, kind, metadata, line, col FROM edges WHERE source = ?",
    );
    let mut params_vec: Vec<String> = vec![source_id.to_string()];

    if let Some(kind) = kind {
        sql.push_str(" AND kind = ?");
        params_vec.push(edge_kind_to_string(kind));
    }

    sql.push_str(" LIMIT ?");
    params_vec.push(limit.to_string());

    let mut stmt = conn.prepare(&sql).map_err(io_other)?;
    let rows = stmt
        .query_map(rusqlite::params_from_iter(params_vec), row_to_edge)
        .map_err(io_other)?;

    let mut results = Vec::new();
    for row in rows {
        results.push(row.map_err(io_other)?);
    }
    Ok(results)
}

pub fn get_edges_by_target(
    conn: &Connection,
    target_id: &str,
    kind: Option<EdgeKind>,
    limit: usize,
) -> std::io::Result<Vec<Edge>> {
    let mut sql = String::from(
        "SELECT source, target, kind, metadata, line, col FROM edges WHERE target = ?",
    );
    let mut params_vec: Vec<String> = vec![target_id.to_string()];

    if let Some(kind) = kind {
        sql.push_str(" AND kind = ?");
        params_vec.push(edge_kind_to_string(kind));
    }

    sql.push_str(" LIMIT ?");
    params_vec.push(limit.to_string());

    let mut stmt = conn.prepare(&sql).map_err(io_other)?;
    let rows = stmt
        .query_map(rusqlite::params_from_iter(params_vec), row_to_edge)
        .map_err(io_other)?;

    let mut results = Vec::new();
    for row in rows {
        results.push(row.map_err(io_other)?);
    }
    Ok(results)
}

pub fn list_unresolved_refs(
    conn: &Connection,
    limit: usize,
) -> std::io::Result<Vec<UnresolvedRefRow>> {
    let mut stmt = conn
        .prepare(
            "SELECT id, from_node_id, reference_name, reference_kind, line, col, candidates
             FROM unresolved_refs LIMIT ?",
        )
        .map_err(io_other)?;
    let limit_i64 = i64::try_from(limit).unwrap_or(i64::MAX);
    let rows = stmt
        .query_map(params![limit_i64], |row| {
            let id: i64 = row.get(0)?;
            let reference_kind_raw: String = row.get(3)?;
            let candidates_raw: Option<String> = row.get(6)?;
            Ok(UnresolvedRefRow {
                id,
                reference: UnresolvedReference {
                    from_node_id: row.get(1)?,
                    reference_name: row.get(2)?,
                    reference_kind: parse_edge_kind(&reference_kind_raw),
                    line: row.get(4)?,
                    column: row.get(5)?,
                    candidates: candidates_raw.and_then(|raw| serde_json::from_str(&raw).ok()),
                },
            })
        })
        .map_err(io_other)?;

    let mut results = Vec::new();
    for row in rows {
        results.push(row.map_err(io_other)?);
    }
    Ok(results)
}

pub fn delete_unresolved_refs(conn: &mut Connection, ids: &[i64]) -> std::io::Result<()> {
    if ids.is_empty() {
        return Ok(());
    }
    let tx = conn.transaction().map_err(io_other)?;
    {
        let mut stmt = tx
            .prepare("DELETE FROM unresolved_refs WHERE id = ?")
            .map_err(io_other)?;
        for id in ids {
            stmt.execute(params![id]).map_err(io_other)?;
        }
    }
    tx.commit().map_err(io_other)
}

pub fn delete_file(conn: &mut Connection, path: &str) -> std::io::Result<()> {
    let tx = conn.transaction().map_err(io_other)?;
    tx.execute("DELETE FROM nodes WHERE file_path = ?", params![path])
        .map_err(io_other)?;
    tx.execute("DELETE FROM files WHERE path = ?", params![path])
        .map_err(io_other)?;
    tx.commit().map_err(io_other)
}

/// Get all nodes belonging to a specific file, optionally filtered by kind.
pub fn get_nodes_by_file(
    conn: &Connection,
    file_path: &str,
    kind: Option<NodeKind>,
) -> std::io::Result<Vec<Node>> {
    let mut sql = String::from(
        "SELECT id, kind, name, qualified_name, file_path, language,
                start_line, end_line, start_column, end_column,
                docstring, signature, visibility,
                is_exported, is_async, is_static, is_abstract,
                decorators, type_parameters, updated_at
         FROM nodes WHERE file_path = ?",
    );
    let mut params_vec: Vec<String> = vec![file_path.to_string()];

    if let Some(k) = kind {
        sql.push_str(" AND kind = ?");
        params_vec.push(kind_to_string(k));
    }

    sql.push_str(" ORDER BY start_line ASC");

    let mut stmt = conn.prepare(&sql).map_err(io_other)?;
    let rows = stmt
        .query_map(rusqlite::params_from_iter(params_vec), row_to_node)
        .map_err(io_other)?;

    let mut results = Vec::new();
    for row in rows {
        results.push(row.map_err(io_other)?);
    }
    Ok(results)
}

/// Return every node in the database ordered by file path then start line.
pub fn get_all_nodes(conn: &Connection) -> std::io::Result<Vec<Node>> {
    let mut stmt = conn
        .prepare(
            "SELECT id, kind, name, qualified_name, file_path, language,
                    start_line, end_line, start_column, end_column,
                    docstring, signature, visibility,
                    is_exported, is_async, is_static, is_abstract,
                    decorators, type_parameters, updated_at
             FROM nodes
             ORDER BY file_path ASC, start_line ASC",
        )
        .map_err(io_other)?;

    let rows = stmt.query_map([], row_to_node).map_err(io_other)?;
    let mut results = Vec::new();
    for row in rows {
        results.push(row.map_err(io_other)?);
    }
    Ok(results)
}

/// Return nodes that have no corresponding row in the `vectors` table.
pub fn get_unembedded_nodes(conn: &Connection) -> std::io::Result<Vec<Node>> {
    let mut stmt = conn
        .prepare(
            "SELECT n.id, n.kind, n.name, n.qualified_name, n.file_path, n.language,
                    n.start_line, n.end_line, n.start_column, n.end_column,
                    n.docstring, n.signature, n.visibility,
                    n.is_exported, n.is_async, n.is_static, n.is_abstract,
                    n.decorators, n.type_parameters, n.updated_at
             FROM nodes n
             LEFT JOIN vectors v ON n.id = v.node_id
             WHERE v.node_id IS NULL
             ORDER BY n.file_path ASC, n.start_line ASC",
        )
        .map_err(io_other)?;

    let rows = stmt.query_map([], row_to_node).map_err(io_other)?;
    let mut results = Vec::new();
    for row in rows {
        results.push(row.map_err(io_other)?);
    }
    Ok(results)
}

/// Database statistics returned by `get_db_stats`.
#[derive(Debug, serde::Serialize)]
pub struct DbStats {
    pub node_count: i64,
    pub edge_count: i64,
    pub file_count: i64,
    pub unresolved_count: i64,
}

/// Return summary statistics for the indexed codebase.
pub fn get_db_stats(conn: &Connection) -> std::io::Result<DbStats> {
    let node_count: i64 = conn
        .query_row("SELECT COUNT(*) FROM nodes", [], |r| r.get(0))
        .map_err(io_other)?;
    let edge_count: i64 = conn
        .query_row("SELECT COUNT(*) FROM edges", [], |r| r.get(0))
        .map_err(io_other)?;
    let file_count: i64 = conn
        .query_row("SELECT COUNT(*) FROM files", [], |r| r.get(0))
        .map_err(io_other)?;
    let unresolved_count: i64 = conn
        .query_row("SELECT COUNT(*) FROM unresolved_refs", [], |r| r.get(0))
        .map_err(io_other)?;

    Ok(DbStats {
        node_count,
        edge_count,
        file_count,
        unresolved_count,
    })
}

fn language_to_string(language: Language) -> String {
    serde_json::to_value(language)
        .ok()
        .and_then(|v| v.as_str().map(std::string::ToString::to_string))
        .unwrap_or_else(|| "unknown".to_string())
}

fn kind_to_string(kind: NodeKind) -> String {
    serde_json::to_value(kind)
        .ok()
        .and_then(|v| v.as_str().map(std::string::ToString::to_string))
        .unwrap_or_else(|| "file".to_string())
}

fn edge_kind_to_string(kind: EdgeKind) -> String {
    serde_json::to_value(kind)
        .ok()
        .and_then(|v| v.as_str().map(std::string::ToString::to_string))
        .unwrap_or_else(|| "contains".to_string())
}

fn visibility_to_string(visibility: Visibility) -> String {
    serde_json::to_value(visibility)
        .ok()
        .and_then(|v| v.as_str().map(std::string::ToString::to_string))
        .unwrap_or_else(|| "public".to_string())
}

fn parse_kind(raw: &str) -> NodeKind {
    serde_json::from_str::<NodeKind>(&format!("\"{raw}\"")).unwrap_or(NodeKind::File)
}

fn parse_language(raw: &str) -> Language {
    serde_json::from_str::<Language>(&format!("\"{raw}\"")).unwrap_or(Language::Unknown)
}

fn parse_visibility(raw: &str) -> Visibility {
    serde_json::from_str::<Visibility>(&format!("\"{raw}\"")).unwrap_or(Visibility::Public)
}

fn parse_edge_kind(raw: &str) -> EdgeKind {
    serde_json::from_str::<EdgeKind>(&format!("\"{raw}\"")).unwrap_or(EdgeKind::Contains)
}

fn row_to_node(row: &rusqlite::Row<'_>) -> rusqlite::Result<Node> {
    let kind_raw: String = row.get(1)?;
    let language_raw: String = row.get(5)?;
    let visibility_raw: Option<String> = row.get(12)?;
    let decorators: Option<String> = row.get(17)?;
    let type_parameters: Option<String> = row.get(18)?;

    Ok(Node {
        id: row.get(0)?,
        kind: parse_kind(&kind_raw),
        name: row.get(2)?,
        qualified_name: row.get(3)?,
        file_path: row.get(4)?,
        language: parse_language(&language_raw),
        start_line: row.get(6)?,
        end_line: row.get(7)?,
        start_column: row.get(8)?,
        end_column: row.get(9)?,
        docstring: row.get(10)?,
        signature: row.get(11)?,
        visibility: visibility_raw.as_deref().map(parse_visibility),
        is_exported: row.get::<_, i64>(13)? != 0,
        is_async: row.get::<_, i64>(14)? != 0,
        is_static: row.get::<_, i64>(15)? != 0,
        is_abstract: row.get::<_, i64>(16)? != 0,
        decorators: decorators.and_then(|raw| serde_json::from_str(&raw).ok()),
        type_parameters: type_parameters.and_then(|raw| serde_json::from_str(&raw).ok()),
        updated_at: row.get(19)?,
    })
}

fn row_to_edge(row: &rusqlite::Row<'_>) -> rusqlite::Result<Edge> {
    let kind_raw: String = row.get(2)?;
    let metadata: Option<String> = row.get(3)?;

    Ok(Edge {
        source: row.get(0)?,
        target: row.get(1)?,
        kind: parse_edge_kind(&kind_raw),
        metadata: metadata.and_then(|raw| serde_json::from_str(&raw).ok()),
        line: row.get(4)?,
        column: row.get(5)?,
    })
}

#[cfg(test)]
mod tests {
    use super::build_fts_query;
    use rusqlite::Connection;

    #[test]
    fn build_fts_query_quotes_slash_terms() {
        assert_eq!(
            build_fts_query("/auth/login/2fa"),
            Some("\"/auth/login/2fa\"".to_string())
        );
    }

    #[test]
    fn build_fts_query_escapes_embedded_quotes() {
        assert_eq!(
            build_fts_query("route \"name\""),
            Some("\"route\" OR \"\"\"name\"\"\"".to_string())
        );
    }

    #[test]
    fn build_fts_query_returns_none_for_blank_input() {
        assert_eq!(build_fts_query("   \n\t  "), None);
    }

    #[test]
    fn build_fts_query_executes_with_slash_and_quote_terms() {
        let conn = Connection::open_in_memory();
        assert!(conn.is_ok());
        let Some(conn) = conn.ok() else {
            return;
        };

        let create_result = conn.execute_batch(
            "CREATE VIRTUAL TABLE nodes_fts USING fts5(name, qualified_name, docstring, content='');",
        );
        assert!(create_result.is_ok());

        let insert_result = conn.execute(
            "INSERT INTO nodes_fts(rowid, name, qualified_name, docstring) VALUES (1, ?1, ?2, ?3)",
            ("auth_login_2fa", "/auth/login/2fa", "route \"name\""),
        );
        assert!(insert_result.is_ok());

        let queries = ["/auth/login/2fa", "route \"name\""];
        for raw in queries {
            let fts_query = build_fts_query(raw);
            assert!(fts_query.is_some());
            let Some(fts_query) = fts_query else {
                return;
            };

            let query_result: rusqlite::Result<i64> = conn.query_row(
                "SELECT COUNT(*) FROM nodes_fts WHERE nodes_fts MATCH ?1",
                [fts_query],
                |row| row.get(0),
            );

            assert!(query_result.is_ok());
            if let Ok(count) = query_result {
                assert!(count >= 1);
            }
        }
    }
}