-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathconnection.rs
More file actions
1559 lines (1457 loc) · 60.5 KB
/
Copy pathconnection.rs
File metadata and controls
1559 lines (1457 loc) · 60.5 KB
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! NativeDatabase — persistent rusqlite Connection exposed as a napi-rs class.
//!
//! Phase 6.13: foundation for moving all DB operations to rusqlite on the native
//! engine path. Handles lifecycle (open/close), schema migrations, and build
//! metadata KV operations.
//!
//! IMPORTANT: Migration DDL is mirrored from src/db/migrations.ts.
//! Any changes there MUST be reflected here (and vice-versa).
use napi_derive::napi;
use rusqlite::{params, types::ValueRef, Connection, OpenFlags};
use send_wrapper::SendWrapper;
use crate::db::repository::ast::{self, FileAstBatch};
use crate::db::repository::edges::{self, EdgeRow};
use crate::domain::graph::builder::stages::insert_nodes::{self, FileHashEntry, InsertNodesBatch};
use crate::graph::classifiers::roles::{self, RoleSummary};
// ── Migration DDL (mirrored from src/db/migrations.ts) ──────────────────
struct Migration {
version: u32,
up: &'static str,
}
const MIGRATIONS: &[Migration] = &[
Migration {
version: 1,
up: r#"
CREATE TABLE IF NOT EXISTS nodes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
kind TEXT NOT NULL,
file TEXT NOT NULL,
line INTEGER,
end_line INTEGER,
UNIQUE(name, kind, file, line)
);
CREATE TABLE IF NOT EXISTS edges (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source_id INTEGER NOT NULL,
target_id INTEGER NOT NULL,
kind TEXT NOT NULL,
confidence REAL DEFAULT 1.0,
dynamic INTEGER DEFAULT 0,
FOREIGN KEY(source_id) REFERENCES nodes(id),
FOREIGN KEY(target_id) REFERENCES nodes(id)
);
CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name);
CREATE INDEX IF NOT EXISTS idx_nodes_file ON nodes(file);
CREATE INDEX IF NOT EXISTS idx_nodes_kind ON nodes(kind);
CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source_id);
CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target_id);
CREATE INDEX IF NOT EXISTS idx_edges_kind ON edges(kind);
CREATE TABLE IF NOT EXISTS node_metrics (
node_id INTEGER PRIMARY KEY,
line_count INTEGER,
symbol_count INTEGER,
import_count INTEGER,
export_count INTEGER,
fan_in INTEGER,
fan_out INTEGER,
cohesion REAL,
file_count INTEGER,
FOREIGN KEY(node_id) REFERENCES nodes(id)
);
CREATE INDEX IF NOT EXISTS idx_node_metrics_node ON node_metrics(node_id);
"#,
},
Migration {
version: 2,
up: r#"
CREATE INDEX IF NOT EXISTS idx_nodes_name_kind_file ON nodes(name, kind, file);
CREATE INDEX IF NOT EXISTS idx_nodes_file_kind ON nodes(file, kind);
CREATE INDEX IF NOT EXISTS idx_edges_source_kind ON edges(source_id, kind);
CREATE INDEX IF NOT EXISTS idx_edges_target_kind ON edges(target_id, kind);
"#,
},
Migration {
version: 3,
up: r#"
CREATE TABLE IF NOT EXISTS file_hashes (
file TEXT PRIMARY KEY,
hash TEXT NOT NULL,
mtime INTEGER NOT NULL
);
"#,
},
Migration {
version: 4,
up: "ALTER TABLE file_hashes ADD COLUMN size INTEGER DEFAULT 0;",
},
Migration {
version: 5,
up: r#"
CREATE TABLE IF NOT EXISTS co_changes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
file_a TEXT NOT NULL,
file_b TEXT NOT NULL,
commit_count INTEGER NOT NULL,
jaccard REAL NOT NULL,
last_commit_epoch INTEGER,
UNIQUE(file_a, file_b)
);
CREATE INDEX IF NOT EXISTS idx_co_changes_file_a ON co_changes(file_a);
CREATE INDEX IF NOT EXISTS idx_co_changes_file_b ON co_changes(file_b);
CREATE INDEX IF NOT EXISTS idx_co_changes_jaccard ON co_changes(jaccard DESC);
CREATE TABLE IF NOT EXISTS co_change_meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
"#,
},
Migration {
version: 6,
up: r#"
CREATE TABLE IF NOT EXISTS file_commit_counts (
file TEXT PRIMARY KEY,
commit_count INTEGER NOT NULL DEFAULT 0
);
"#,
},
Migration {
version: 7,
up: r#"
CREATE TABLE IF NOT EXISTS build_meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
"#,
},
Migration {
version: 8,
up: r#"
CREATE TABLE IF NOT EXISTS function_complexity (
node_id INTEGER PRIMARY KEY,
cognitive INTEGER NOT NULL,
cyclomatic INTEGER NOT NULL,
max_nesting INTEGER NOT NULL,
FOREIGN KEY(node_id) REFERENCES nodes(id)
);
CREATE INDEX IF NOT EXISTS idx_fc_cognitive ON function_complexity(cognitive DESC);
CREATE INDEX IF NOT EXISTS idx_fc_cyclomatic ON function_complexity(cyclomatic DESC);
"#,
},
Migration {
version: 9,
up: r#"
ALTER TABLE function_complexity ADD COLUMN loc INTEGER DEFAULT 0;
ALTER TABLE function_complexity ADD COLUMN sloc INTEGER DEFAULT 0;
ALTER TABLE function_complexity ADD COLUMN comment_lines INTEGER DEFAULT 0;
ALTER TABLE function_complexity ADD COLUMN halstead_n1 INTEGER DEFAULT 0;
ALTER TABLE function_complexity ADD COLUMN halstead_n2 INTEGER DEFAULT 0;
ALTER TABLE function_complexity ADD COLUMN halstead_big_n1 INTEGER DEFAULT 0;
ALTER TABLE function_complexity ADD COLUMN halstead_big_n2 INTEGER DEFAULT 0;
ALTER TABLE function_complexity ADD COLUMN halstead_vocabulary INTEGER DEFAULT 0;
ALTER TABLE function_complexity ADD COLUMN halstead_length INTEGER DEFAULT 0;
ALTER TABLE function_complexity ADD COLUMN halstead_volume REAL DEFAULT 0;
ALTER TABLE function_complexity ADD COLUMN halstead_difficulty REAL DEFAULT 0;
ALTER TABLE function_complexity ADD COLUMN halstead_effort REAL DEFAULT 0;
ALTER TABLE function_complexity ADD COLUMN halstead_bugs REAL DEFAULT 0;
ALTER TABLE function_complexity ADD COLUMN maintainability_index REAL DEFAULT 0;
CREATE INDEX IF NOT EXISTS idx_fc_mi ON function_complexity(maintainability_index ASC);
"#,
},
Migration {
version: 10,
up: r#"
CREATE TABLE IF NOT EXISTS dataflow (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source_id INTEGER NOT NULL,
target_id INTEGER NOT NULL,
kind TEXT NOT NULL,
param_index INTEGER,
expression TEXT,
line INTEGER,
confidence REAL DEFAULT 1.0,
FOREIGN KEY(source_id) REFERENCES nodes(id),
FOREIGN KEY(target_id) REFERENCES nodes(id)
);
CREATE INDEX IF NOT EXISTS idx_dataflow_source ON dataflow(source_id);
CREATE INDEX IF NOT EXISTS idx_dataflow_target ON dataflow(target_id);
CREATE INDEX IF NOT EXISTS idx_dataflow_kind ON dataflow(kind);
CREATE INDEX IF NOT EXISTS idx_dataflow_source_kind ON dataflow(source_id, kind);
"#,
},
Migration {
version: 11,
up: r#"
ALTER TABLE nodes ADD COLUMN parent_id INTEGER REFERENCES nodes(id);
CREATE INDEX IF NOT EXISTS idx_nodes_parent ON nodes(parent_id);
CREATE INDEX IF NOT EXISTS idx_nodes_kind_parent ON nodes(kind, parent_id);
"#,
},
Migration {
version: 12,
up: r#"
CREATE TABLE IF NOT EXISTS cfg_blocks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
function_node_id INTEGER NOT NULL,
block_index INTEGER NOT NULL,
block_type TEXT NOT NULL,
start_line INTEGER,
end_line INTEGER,
label TEXT,
FOREIGN KEY(function_node_id) REFERENCES nodes(id),
UNIQUE(function_node_id, block_index)
);
CREATE INDEX IF NOT EXISTS idx_cfg_blocks_fn ON cfg_blocks(function_node_id);
CREATE TABLE IF NOT EXISTS cfg_edges (
id INTEGER PRIMARY KEY AUTOINCREMENT,
function_node_id INTEGER NOT NULL,
source_block_id INTEGER NOT NULL,
target_block_id INTEGER NOT NULL,
kind TEXT NOT NULL,
FOREIGN KEY(function_node_id) REFERENCES nodes(id),
FOREIGN KEY(source_block_id) REFERENCES cfg_blocks(id),
FOREIGN KEY(target_block_id) REFERENCES cfg_blocks(id)
);
CREATE INDEX IF NOT EXISTS idx_cfg_edges_fn ON cfg_edges(function_node_id);
CREATE INDEX IF NOT EXISTS idx_cfg_edges_src ON cfg_edges(source_block_id);
CREATE INDEX IF NOT EXISTS idx_cfg_edges_tgt ON cfg_edges(target_block_id);
"#,
},
Migration {
version: 13,
up: r#"
CREATE TABLE IF NOT EXISTS ast_nodes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
file TEXT NOT NULL,
line INTEGER NOT NULL,
kind TEXT NOT NULL,
name TEXT NOT NULL,
text TEXT,
receiver TEXT,
parent_node_id INTEGER,
FOREIGN KEY(parent_node_id) REFERENCES nodes(id)
);
CREATE INDEX IF NOT EXISTS idx_ast_kind ON ast_nodes(kind);
CREATE INDEX IF NOT EXISTS idx_ast_name ON ast_nodes(name);
CREATE INDEX IF NOT EXISTS idx_ast_file ON ast_nodes(file);
CREATE INDEX IF NOT EXISTS idx_ast_parent ON ast_nodes(parent_node_id);
CREATE INDEX IF NOT EXISTS idx_ast_kind_name ON ast_nodes(kind, name);
"#,
},
Migration {
version: 14,
up: r#"
ALTER TABLE nodes ADD COLUMN exported INTEGER DEFAULT 0;
CREATE INDEX IF NOT EXISTS idx_nodes_exported ON nodes(exported);
"#,
},
Migration {
version: 15,
up: r#"
ALTER TABLE nodes ADD COLUMN qualified_name TEXT;
ALTER TABLE nodes ADD COLUMN scope TEXT;
ALTER TABLE nodes ADD COLUMN visibility TEXT;
UPDATE nodes SET qualified_name = name WHERE qualified_name IS NULL;
CREATE INDEX IF NOT EXISTS idx_nodes_qualified_name ON nodes(qualified_name);
CREATE INDEX IF NOT EXISTS idx_nodes_scope ON nodes(scope);
"#,
},
Migration {
version: 16,
up: r#"
CREATE INDEX IF NOT EXISTS idx_edges_kind_target ON edges(kind, target_id);
CREATE INDEX IF NOT EXISTS idx_edges_kind_source ON edges(kind, source_id);
"#,
},
Migration {
version: 17,
up: r#"
ALTER TABLE edges ADD COLUMN technique TEXT;
CREATE INDEX IF NOT EXISTS idx_edges_technique ON edges(technique);
"#,
},
Migration {
version: 18,
up: r#"
CREATE TABLE IF NOT EXISTS dataflow_vertices (
id INTEGER PRIMARY KEY AUTOINCREMENT,
func_id INTEGER NOT NULL REFERENCES nodes(id),
kind TEXT NOT NULL,
name TEXT,
param_index INTEGER,
line INTEGER,
node_id INTEGER REFERENCES nodes(id)
);
CREATE INDEX IF NOT EXISTS idx_dfv_func ON dataflow_vertices(func_id);
CREATE INDEX IF NOT EXISTS idx_dfv_func_kind ON dataflow_vertices(func_id, kind);
CREATE INDEX IF NOT EXISTS idx_dfv_node ON dataflow_vertices(node_id);
ALTER TABLE dataflow ADD COLUMN source_vertex INTEGER REFERENCES dataflow_vertices(id);
ALTER TABLE dataflow ADD COLUMN target_vertex INTEGER REFERENCES dataflow_vertices(id);
ALTER TABLE dataflow ADD COLUMN scope TEXT;
ALTER TABLE dataflow ADD COLUMN call_edge_id INTEGER REFERENCES edges(id);
CREATE INDEX IF NOT EXISTS idx_dataflow_sv ON dataflow(source_vertex);
CREATE INDEX IF NOT EXISTS idx_dataflow_tv ON dataflow(target_vertex);
CREATE INDEX IF NOT EXISTS idx_dataflow_scope ON dataflow(scope);
CREATE TABLE IF NOT EXISTS dataflow_summary (
func_id INTEGER NOT NULL REFERENCES nodes(id),
param_index INTEGER NOT NULL,
flows_to_return INTEGER NOT NULL DEFAULT 0,
is_mutated INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY(func_id, param_index)
);
CREATE INDEX IF NOT EXISTS idx_dfs_func ON dataflow_summary(func_id);
CREATE VIEW IF NOT EXISTS dataflow_fn AS
SELECT
sv.func_id AS source_id,
tv.func_id AS target_id,
d.kind,
d.param_index,
d.expression,
d.line,
d.confidence
FROM dataflow d
JOIN dataflow_vertices sv ON d.source_vertex = sv.id
JOIN dataflow_vertices tv ON d.target_vertex = tv.id
WHERE sv.func_id != tv.func_id;
"#,
},
Migration {
version: 19,
// P6 sentinel: forces a full rebuild so that databases built with the native
// fast path (which skipped vertex extraction before P6) backfill
// dataflow_vertices and dataflow_summary on the next `codegraph build`.
up: "SELECT 1",
},
];
// ── napi types ──────────────────────────────────────────────────────────
/// A key-value entry for build metadata.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct BuildMetaEntry {
pub key: String,
pub value: String,
}
// ── Bulk-insert input types ────────────────────────────────────────────
/// A single complexity metrics row for bulk insertion.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct ComplexityRow {
pub node_id: i64,
pub cognitive: u32,
pub cyclomatic: u32,
pub max_nesting: u32,
pub loc: u32,
pub sloc: u32,
pub comment_lines: u32,
pub halstead_n1: u32,
pub halstead_n2: u32,
pub halstead_big_n1: u32,
pub halstead_big_n2: u32,
pub halstead_vocabulary: u32,
pub halstead_length: u32,
pub halstead_volume: f64,
pub halstead_difficulty: f64,
pub halstead_effort: f64,
pub halstead_bugs: f64,
pub maintainability_index: f64,
}
/// A CFG entry for a single function: blocks + edges.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct CfgEntry {
pub node_id: i64,
pub blocks: Vec<CfgBlockRow>,
pub edges: Vec<CfgEdgeRow>,
}
/// A single CFG block for bulk insertion.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct CfgBlockRow {
pub index: u32,
pub block_type: String,
pub start_line: Option<u32>,
pub end_line: Option<u32>,
pub label: Option<String>,
}
/// A single CFG edge for bulk insertion.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct CfgEdgeRow {
pub source_index: u32,
pub target_index: u32,
pub kind: String,
}
/// A single dataflow edge for bulk insertion.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct DataflowEdge {
pub source_id: i64,
pub target_id: i64,
pub kind: String,
pub param_index: Option<u32>,
pub expression: Option<String>,
pub line: Option<u32>,
pub confidence: f64,
}
// ── Build-glue return types ────────────────────────────────────────────
/// A single row from file_hashes.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct FileHashRow {
pub file: String,
pub hash: String,
pub mtime: i64,
pub size: i64,
}
/// Batched result of file_hashes table read.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct FileHashData {
pub exists: bool,
pub rows: Vec<FileHashRow>,
pub max_mtime: i64,
}
/// Counts for pending analysis tables.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct PendingAnalysisCounts {
pub cfg_count: i64,
pub dataflow_count: i64,
}
/// Batched node/edge counts for finalize.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct FinalizeCounts {
pub node_count: i64,
pub edge_count: i64,
}
/// Batched advisory check results.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct AdvisoryCheckResult {
pub orphaned_embeddings: i64,
pub embed_built_at: Option<String>,
pub unused_exports: i64,
}
/// Batched collect-files data.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct CollectFilesData {
pub count: i64,
pub files: Vec<String>,
}
// ── NativeDatabase class ────────────────────────────────────────────────
/// Persistent rusqlite Connection wrapper exposed to JS via napi-rs.
///
/// Holds a single `rusqlite::Connection` for the lifetime of a build pipeline.
/// Replaces `better-sqlite3` for schema initialization and build metadata on
/// the native engine path.
#[napi]
pub struct NativeDatabase {
conn: SendWrapper<Option<Connection>>,
db_path: String,
}
#[napi]
impl NativeDatabase {
/// Open a read-write connection to the database at `db_path`.
/// Creates the file and parent directories if they don't exist.
#[napi(factory)]
pub fn open_read_write(db_path: String) -> napi::Result<Self> {
let flags = OpenFlags::SQLITE_OPEN_READ_WRITE
| OpenFlags::SQLITE_OPEN_CREATE
| OpenFlags::SQLITE_OPEN_NO_MUTEX;
let conn = Connection::open_with_flags(&db_path, flags)
.map_err(|e| napi::Error::from_reason(format!("Failed to open DB: {e}")))?;
// 64 entries comfortably holds the 40+ prepare_cached() queries in read_queries.rs
// plus build-path queries, avoiding LRU eviction (default is 16).
conn.set_prepared_statement_cache_capacity(64);
// Disable mmap for read-write connections: when both rusqlite and
// better-sqlite3 share the same WAL-mode file, mmap and regular I/O
// are not cache-coherent on Windows, leading to SQLITE_CORRUPT (#715).
// Read-only connections keep mmap since they don't share a WAL file
// with a concurrent writer from a different library.
conn.execute_batch(
"PRAGMA journal_mode = WAL; \
PRAGMA synchronous = NORMAL; \
PRAGMA busy_timeout = 5000; \
PRAGMA temp_store = MEMORY;",
)
.map_err(|e| napi::Error::from_reason(format!("Failed to set pragmas: {e}")))?;
Ok(Self {
conn: SendWrapper::new(Some(conn)),
db_path,
})
}
/// Open a read-only connection to the database at `db_path`.
#[napi(factory)]
pub fn open_readonly(db_path: String) -> napi::Result<Self> {
let flags = OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX;
let conn = Connection::open_with_flags(&db_path, flags)
.map_err(|e| napi::Error::from_reason(format!("Failed to open DB readonly: {e}")))?;
conn.set_prepared_statement_cache_capacity(64);
conn.execute_batch(
"PRAGMA busy_timeout = 5000; \
PRAGMA mmap_size = 268435456; \
PRAGMA temp_store = MEMORY;",
)
.map_err(|e| napi::Error::from_reason(format!("Failed to set pragmas: {e}")))?;
Ok(Self {
conn: SendWrapper::new(Some(conn)),
db_path,
})
}
/// Close the database connection. Idempotent — safe to call multiple times.
#[napi]
pub fn close(&mut self) {
(*self.conn).take();
}
/// The path this database was opened with.
#[napi(getter)]
pub fn db_path(&self) -> String {
self.db_path.clone()
}
/// Whether the connection is still open.
#[napi(getter)]
pub fn is_open(&self) -> bool {
self.conn.is_some()
}
/// Execute one or more SQL statements (no result returned).
#[napi]
pub fn exec(&self, sql: String) -> napi::Result<()> {
let conn = self.conn()?;
conn.execute_batch(&sql)
.map_err(|e| napi::Error::from_reason(format!("exec failed: {e}")))
}
/// Execute a read-only PRAGMA statement and return the first result as a string.
/// Returns `null` if the pragma produces no output.
///
/// **Note:** This method is intended for read-only PRAGMAs (e.g. `journal_mode`,
/// `page_count`). Write-mode PRAGMAs (e.g. `journal_mode = DELETE`) should use
/// `exec()` instead. No validation is performed — callers are trusted internal code.
#[napi]
pub fn pragma(&self, sql: String) -> napi::Result<Option<String>> {
let conn = self.conn()?;
let query = format!("PRAGMA {sql}");
let mut stmt = conn
.prepare(&query)
.map_err(|e| napi::Error::from_reason(format!("pragma prepare failed: {e}")))?;
let mut rows = stmt
.query([])
.map_err(|e| napi::Error::from_reason(format!("pragma query failed: {e}")))?;
match rows.next() {
Ok(Some(row)) => {
let val: String = row
.get(0)
.map_err(|e| napi::Error::from_reason(format!("pragma get failed: {e}")))?;
Ok(Some(val))
}
Ok(None) => Ok(None),
Err(e) => Err(napi::Error::from_reason(format!("pragma next failed: {e}"))),
}
}
/// Run all schema migrations. Mirrors `initSchema()` from `src/db/migrations.ts`.
#[napi]
pub fn init_schema(&self) -> napi::Result<()> {
let conn = self.conn()?;
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL DEFAULT 0)",
)
.map_err(|e| napi::Error::from_reason(format!("create schema_version failed: {e}")))?;
let mut current_version: u32 = conn
.query_row(
"SELECT version FROM schema_version ORDER BY rowid DESC LIMIT 1",
[],
|row| row.get(0),
)
.unwrap_or(0);
// Insert version 0 if table was just created (empty)
let count: u32 = conn
.query_row("SELECT COUNT(*) FROM schema_version", [], |row| row.get(0))
.unwrap_or(0);
if count == 0 {
conn.execute("INSERT INTO schema_version (version) VALUES (0)", [])
.map_err(|e| {
napi::Error::from_reason(format!("insert schema_version failed: {e}"))
})?;
}
for migration in MIGRATIONS {
if migration.version > current_version {
let tx = conn.unchecked_transaction().map_err(|e| {
napi::Error::from_reason(format!("begin migration tx failed: {e}"))
})?;
tx.execute_batch(migration.up).map_err(|e| {
napi::Error::from_reason(format!(
"migration v{} failed: {e}",
migration.version
))
})?;
tx.execute(
"UPDATE schema_version SET version = ?1",
params![migration.version],
)
.map_err(|e| {
napi::Error::from_reason(format!("update schema_version failed: {e}"))
})?;
tx.commit().map_err(|e| {
napi::Error::from_reason(format!(
"commit migration v{} failed: {e}",
migration.version
))
})?;
current_version = migration.version;
}
}
// Legacy column compat — add columns that may be missing from pre-migration DBs.
// Mirrors the post-migration block in src/db/migrations.ts initSchema().
if has_table(conn, "nodes") {
if !has_column(conn, "nodes", "end_line") {
let _ = conn.execute_batch("ALTER TABLE nodes ADD COLUMN end_line INTEGER");
}
if !has_column(conn, "nodes", "role") {
let _ = conn.execute_batch("ALTER TABLE nodes ADD COLUMN role TEXT");
}
let _ = conn.execute_batch("CREATE INDEX IF NOT EXISTS idx_nodes_role ON nodes(role)");
if !has_column(conn, "nodes", "parent_id") {
let _ = conn.execute_batch(
"ALTER TABLE nodes ADD COLUMN parent_id INTEGER REFERENCES nodes(id)",
);
}
let _ = conn
.execute_batch("CREATE INDEX IF NOT EXISTS idx_nodes_parent ON nodes(parent_id)");
let _ = conn.execute_batch(
"CREATE INDEX IF NOT EXISTS idx_nodes_kind_parent ON nodes(kind, parent_id)",
);
if !has_column(conn, "nodes", "qualified_name") {
let _ = conn.execute_batch("ALTER TABLE nodes ADD COLUMN qualified_name TEXT");
}
if !has_column(conn, "nodes", "scope") {
let _ = conn.execute_batch("ALTER TABLE nodes ADD COLUMN scope TEXT");
}
if !has_column(conn, "nodes", "visibility") {
let _ = conn.execute_batch("ALTER TABLE nodes ADD COLUMN visibility TEXT");
}
let _ = conn.execute_batch(
"UPDATE nodes SET qualified_name = name WHERE qualified_name IS NULL",
);
let _ = conn.execute_batch(
"CREATE INDEX IF NOT EXISTS idx_nodes_qualified_name ON nodes(qualified_name)",
);
let _ =
conn.execute_batch("CREATE INDEX IF NOT EXISTS idx_nodes_scope ON nodes(scope)");
}
if has_table(conn, "edges") {
if !has_column(conn, "edges", "confidence") {
let _ =
conn.execute_batch("ALTER TABLE edges ADD COLUMN confidence REAL DEFAULT 1.0");
}
if !has_column(conn, "edges", "dynamic") {
let _ =
conn.execute_batch("ALTER TABLE edges ADD COLUMN dynamic INTEGER DEFAULT 0");
}
}
Ok(())
}
/// Retrieve a single build metadata value by key. Returns `null` if missing.
#[napi]
pub fn get_build_meta(&self, key: String) -> napi::Result<Option<String>> {
let conn = self.conn()?;
if !has_table(conn, "build_meta") {
return Ok(None);
}
let result = conn.query_row(
"SELECT value FROM build_meta WHERE key = ?1",
params![key],
|row| row.get::<_, String>(0),
);
match result {
Ok(val) => Ok(Some(val)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(e) => Err(napi::Error::from_reason(format!(
"getBuildMeta failed for key \"{key}\": {e}"
))),
}
}
/// Upsert multiple build metadata entries in a single transaction.
#[napi]
pub fn set_build_meta(&self, entries: Vec<BuildMetaEntry>) -> napi::Result<()> {
let conn = self.conn()?;
// Ensure build_meta table exists (may be called before full migration on edge cases)
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS build_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)",
)
.map_err(|e| napi::Error::from_reason(format!("ensure build_meta table failed: {e}")))?;
let tx = conn
.unchecked_transaction()
.map_err(|e| napi::Error::from_reason(format!("begin transaction failed: {e}")))?;
{
let mut stmt = tx
.prepare_cached("INSERT OR REPLACE INTO build_meta (key, value) VALUES (?1, ?2)")
.map_err(|e| {
napi::Error::from_reason(format!("prepare setBuildMeta failed: {e}"))
})?;
for entry in &entries {
stmt.execute(params![entry.key, entry.value]).map_err(|e| {
napi::Error::from_reason(format!(
"setBuildMeta insert failed for \"{}\": {e}",
entry.key
))
})?;
}
}
tx.commit()
.map_err(|e| napi::Error::from_reason(format!("commit setBuildMeta failed: {e}")))?;
Ok(())
}
// ── Phase 6.16: Generic query execution & version validation ────────
/// Execute a parameterized query and return all rows as JSON objects.
/// Each row is a `{ column_name: value, ... }` object.
/// Params are positional (`?1, ?2, ...`) and accept string, number, or null.
///
/// **Note**: Designed for SELECT statements. Passing DML/DDL will not error
/// at the Rust layer but is not an intended use — all current callers pass
/// SELECT-only SQL generated by `NodeQuery.build()`.
#[napi]
pub fn query_all(
&self,
sql: String,
params: Vec<serde_json::Value>,
) -> napi::Result<Vec<serde_json::Value>> {
let conn = self.conn()?;
let rusqlite_params = json_to_rusqlite_params(¶ms)?;
let param_refs: Vec<&dyn rusqlite::types::ToSql> =
rusqlite_params.iter().map(|v| v as &dyn rusqlite::types::ToSql).collect();
let mut stmt = conn
.prepare(&sql)
.map_err(|e| napi::Error::from_reason(format!("queryAll prepare failed: {e}")))?;
let col_count = stmt.column_count();
let col_names: Vec<String> = (0..col_count)
.map(|i| stmt.column_name(i).unwrap_or("?").to_owned())
.collect();
let rows = stmt
.query_map(param_refs.as_slice(), |row| {
Ok(row_to_json(row, col_count, &col_names))
})
.map_err(|e| napi::Error::from_reason(format!("queryAll query failed: {e}")))?;
let mut result = Vec::new();
for row in rows {
let val =
row.map_err(|e| napi::Error::from_reason(format!("queryAll row failed: {e}")))?;
result.push(val);
}
Ok(result)
}
/// Execute a parameterized query and return the first row, or null.
/// See `query_all` for parameter and contract details.
#[napi]
pub fn query_get(
&self,
sql: String,
params: Vec<serde_json::Value>,
) -> napi::Result<Option<serde_json::Value>> {
let conn = self.conn()?;
let rusqlite_params = json_to_rusqlite_params(¶ms)?;
let param_refs: Vec<&dyn rusqlite::types::ToSql> =
rusqlite_params.iter().map(|v| v as &dyn rusqlite::types::ToSql).collect();
let mut stmt = conn
.prepare(&sql)
.map_err(|e| napi::Error::from_reason(format!("queryGet prepare failed: {e}")))?;
let col_count = stmt.column_count();
let col_names: Vec<String> = (0..col_count)
.map(|i| stmt.column_name(i).unwrap_or("?").to_owned())
.collect();
let mut query_rows = stmt
.query(param_refs.as_slice())
.map_err(|e| napi::Error::from_reason(format!("queryGet query failed: {e}")))?;
match query_rows.next() {
Ok(Some(row)) => Ok(Some(row_to_json(row, col_count, &col_names))),
Ok(None) => Ok(None),
Err(e) => Err(napi::Error::from_reason(format!(
"queryGet row failed: {e}"
))),
}
}
/// Validate that the DB's codegraph_version matches the expected version.
/// Returns `true` if versions match or no version is stored.
/// Prints a warning to stderr on mismatch.
#[napi]
pub fn validate_schema_version(&self, expected_version: String) -> napi::Result<bool> {
let stored = self.get_build_meta("codegraph_version".to_string())?;
match stored {
None => Ok(true),
Some(ref v) if v == &expected_version => Ok(true),
Some(v) => {
eprintln!(
"[codegraph] DB was built with v{v}, running v{expected_version}. \
Consider: codegraph build --no-incremental"
);
Ok(false)
}
}
}
// ── Phase 6.15: Build pipeline write operations ─────────────────────
/// Bulk-insert nodes, children, containment edges, exports, and file hashes.
/// Reuses the persistent connection instead of opening a new one.
/// Returns `true` on success, `false` on failure.
///
/// Batches are received as `serde_json::Value` and deserialized via serde so
/// that `null` visibility values map to `None` instead of crashing napi's
/// `Option<String>` object conversion (#709).
///
/// `file_hashes` is committed in its own transaction, separate from node
/// insertion (#1731) — callers that need edge-consistent hashes (i.e. the
/// standard incremental build pipeline) should pass an empty array here
/// and commit hashes themselves once resolveImports/buildEdges have
/// finished rebuilding the affected files' edges (see
/// `insertNodes.commitFileHashes` on the JS side, or
/// `insert_nodes::commit_file_hashes` for the all-Rust orchestrator).
#[napi(ts_args_type = "batches: Array<{ file: string; definitions: Array<{ name: string; kind: string; line: number; endLine?: number; visibility?: string; children: Array<{ name: string; kind: string; line: number; endLine?: number; visibility?: string }> }>; exports: Array<{ name: string; kind: string; line: number }> }>, fileHashes: FileHashEntry[], removedFiles: string[]")]
pub fn bulk_insert_nodes(
&self,
batches: serde_json::Value,
file_hashes: Vec<FileHashEntry>,
removed_files: Vec<String>,
) -> napi::Result<bool> {
let batches: Vec<InsertNodesBatch> = serde_json::from_value(batches)
.map_err(|e| {
napi::Error::from_reason(format!("bulk_insert_nodes: invalid batches: {e}"))
})?;
let conn = self.conn()?;
let insert_ok = insert_nodes::do_insert_nodes(conn, &batches, &removed_files)
.inspect_err(|e| eprintln!("[NativeDatabase] bulk_insert_nodes failed: {e}"))
.is_ok();
let hashes_ok = insert_nodes::commit_file_hashes(conn, &file_hashes)
.inspect_err(|e| eprintln!("[NativeDatabase] bulk_insert_nodes hash commit failed: {e}"))
.is_ok();
Ok(insert_ok && hashes_ok)
}
/// Bulk-insert edge rows using chunked multi-value INSERT statements.
/// Returns `true` on success, `false` on failure.
#[napi]
pub fn bulk_insert_edges(&self, edges: Vec<EdgeRow>) -> napi::Result<bool> {
if edges.is_empty() {
return Ok(true);
}
let conn = self.conn()?;
Ok(edges::do_insert_edges(conn, &edges)
.inspect_err(|e| eprintln!("[NativeDatabase] bulk_insert_edges failed: {e}"))
.is_ok())
}
/// Bulk-insert AST nodes, resolving parent_node_id from the nodes table.
/// Returns the number of rows inserted (0 on failure).
#[napi]
pub fn bulk_insert_ast_nodes(&self, batches: Vec<FileAstBatch>) -> napi::Result<u32> {
let conn = self.conn()?;
Ok(ast::do_insert_ast_nodes(conn, &batches).unwrap_or(0))
}
/// Bulk-insert complexity metrics for functions/methods.
/// Each row maps a node_id to its complexity metrics.
/// Returns the number of rows inserted (0 on failure).
#[napi]
pub fn bulk_insert_complexity(&self, rows: Vec<ComplexityRow>) -> napi::Result<u32> {
if rows.is_empty() {
return Ok(0);
}
let conn = self.conn()?;
if !has_table(conn, "function_complexity") {
return Ok(0);
}
let tx = conn
.unchecked_transaction()
.map_err(|e| napi::Error::from_reason(format!("complexity tx failed: {e}")))?;
let mut total = 0u32;
{
let mut stmt = tx.prepare(
"INSERT OR REPLACE INTO function_complexity \
(node_id, cognitive, cyclomatic, max_nesting, \
loc, sloc, comment_lines, \
halstead_n1, halstead_n2, halstead_big_n1, halstead_big_n2, \
halstead_vocabulary, halstead_length, halstead_volume, \
halstead_difficulty, halstead_effort, halstead_bugs, \
maintainability_index) \
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18)",
)
.map_err(|e| napi::Error::from_reason(format!("complexity prepare failed: {e}")))?;
for r in &rows {
if stmt
.execute(params![
r.node_id,
r.cognitive,
r.cyclomatic,
r.max_nesting,
r.loc,
r.sloc,
r.comment_lines,
r.halstead_n1,
r.halstead_n2,
r.halstead_big_n1,
r.halstead_big_n2,
r.halstead_vocabulary,
r.halstead_length,
r.halstead_volume,
r.halstead_difficulty,
r.halstead_effort,
r.halstead_bugs,
r.maintainability_index,
])
.is_ok()
{
total += 1;
}
}
}
tx.commit()
.map_err(|e| napi::Error::from_reason(format!("complexity commit failed: {e}")))?;
Ok(total)
}
/// Bulk-insert CFG blocks and edges for functions/methods.
/// Returns the number of blocks inserted (0 on failure).
#[napi]
pub fn bulk_insert_cfg(&self, entries: Vec<CfgEntry>) -> napi::Result<u32> {
if entries.is_empty() {
return Ok(0);
}
let conn = self.conn()?;
if !has_table(conn, "cfg_blocks") {
return Ok(0);
}
let tx = conn
.unchecked_transaction()
.map_err(|e| napi::Error::from_reason(format!("cfg tx failed: {e}")))?;
let mut total = 0u32;
{
let mut block_stmt = tx.prepare(
"INSERT INTO cfg_blocks \
(function_node_id, block_index, block_type, start_line, end_line, label) \
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
)
.map_err(|e| napi::Error::from_reason(format!("cfg_blocks prepare failed: {e}")))?;
let mut edge_stmt = tx.prepare(
"INSERT INTO cfg_edges \
(function_node_id, source_block_id, target_block_id, kind) \
VALUES (?1, ?2, ?3, ?4)",
)
.map_err(|e| napi::Error::from_reason(format!("cfg_edges prepare failed: {e}")))?;