1use crate::error::{BrainError, Result};
7use crate::fts::escape_fts5_query;
8use crate::types::{Edge, Node, NodeType};
9use rusqlite::{params, Connection, OptionalExtension};
10use std::collections::{HashMap, HashSet};
11use std::path::Path;
12
13#[cfg(feature = "ast")]
14use crate::ast::SymbolAnchor;
15
16pub struct Database {
21 pub(crate) conn: Connection,
22}
23
24impl Database {
25 pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
27 let conn = Connection::open(path.as_ref())?;
28 let db = Self { conn };
29 db.configure_connection()?;
30 super::migrations::migrate(&db.conn)?;
31 Ok(db)
32 }
33
34 pub fn open_in_memory() -> Result<Self> {
36 let conn = Connection::open_in_memory()?;
37 let db = Self { conn };
38 db.configure_connection()?;
39 super::migrations::migrate(&db.conn)?;
40 Ok(db)
41 }
42
43 fn configure_connection(&self) -> Result<()> {
44 self.conn.pragma_update(None, "foreign_keys", true)?;
45 self.conn.pragma_update(None, "busy_timeout", 5000i32)?;
46 let _ = self.conn.pragma_update(None, "journal_mode", "WAL");
48 let _ = self.conn.pragma_update(None, "synchronous", "NORMAL");
49 Ok(())
50 }
51
52 pub fn with_transaction<T, F>(&self, f: F) -> Result<T>
54 where
55 F: FnOnce(&Connection) -> Result<T>,
56 {
57 let tx = self.conn.unchecked_transaction()?;
58 let result = f(&tx)?;
59 tx.commit()?;
60 Ok(result)
61 }
62
63 pub fn insert_node(&self, node: &Node) -> Result<()> {
66 self.insert_node_on(&self.conn, node)
67 }
68
69 pub(crate) fn insert_node_on(&self, conn: &Connection, node: &Node) -> Result<()> {
70 let existing_created: Option<i64> = conn
72 .query_row(
73 "SELECT created_at FROM nodes WHERE id = ?1",
74 [&node.id],
75 |row| row.get(0),
76 )
77 .optional()?;
78
79 let created_at = existing_created.unwrap_or(node.created_at);
80
81 conn.execute(
82 "INSERT INTO nodes (id, node_type, title, file_path, symbol_hash, summary, content_hash, created_at, updated_at)
83 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
84 ON CONFLICT(id) DO UPDATE SET
85 node_type = excluded.node_type,
86 title = excluded.title,
87 file_path = excluded.file_path,
88 symbol_hash = excluded.symbol_hash,
89 summary = excluded.summary,
90 content_hash = excluded.content_hash,
91 updated_at = excluded.updated_at",
92 params![
93 node.id,
94 node.node_type.as_str(),
95 node.title,
96 node.file_path,
97 node.symbol_hash.map(|h| h as i64),
98 node.summary,
99 node.content_hash,
100 created_at,
101 node.updated_at,
102 ],
103 )?;
104 Ok(())
105 }
106
107 pub fn get_content_hash(&self, node_id: &str) -> Result<Option<String>> {
109 let v: Option<String> = self
110 .conn
111 .query_row(
112 "SELECT content_hash FROM nodes WHERE id = ?1",
113 [node_id],
114 |row| row.get(0),
115 )
116 .optional()?;
117 Ok(v)
118 }
119
120 pub fn insert_edge(&self, edge: &Edge) -> Result<()> {
122 self.insert_edge_on(&self.conn, edge)
123 }
124
125 pub(crate) fn insert_edge_on(&self, conn: &Connection, edge: &Edge) -> Result<()> {
126 conn.execute(
127 "INSERT INTO edges (source_id, target_id, relation_type, weight, decay_rate, created_at)
128 VALUES (?1, ?2, ?3, ?4, ?5, ?6)
129 ON CONFLICT(source_id, target_id, relation_type) DO UPDATE SET
130 weight = excluded.weight,
131 decay_rate = excluded.decay_rate",
132 params![
133 edge.source_id,
134 edge.target_id,
135 edge.relation_type,
136 edge.weight,
137 edge.decay_rate,
138 edge.created_at,
139 ],
140 )?;
141 Ok(())
142 }
143
144 pub fn insert_pending_link(
146 &self,
147 source_id: &str,
148 raw_target: &str,
149 relation_type: &str,
150 created_at: i64,
151 ) -> Result<()> {
152 self.insert_pending_link_on(&self.conn, source_id, raw_target, relation_type, created_at)
153 }
154
155 pub(crate) fn insert_pending_link_on(
156 &self,
157 conn: &Connection,
158 source_id: &str,
159 raw_target: &str,
160 relation_type: &str,
161 created_at: i64,
162 ) -> Result<()> {
163 conn.execute(
164 "INSERT INTO pending_links (source_id, raw_target, relation_type, created_at)
165 VALUES (?1, ?2, ?3, ?4)
166 ON CONFLICT(source_id, raw_target, relation_type) DO NOTHING",
167 params![source_id, raw_target, relation_type, created_at],
168 )?;
169 Ok(())
170 }
171
172 pub fn clear_pending_links_for(&self, source_id: &str) -> Result<()> {
174 self.conn
175 .execute("DELETE FROM pending_links WHERE source_id = ?1", [source_id])?;
176 Ok(())
177 }
178
179 pub(crate) fn clear_pending_links_for_on(
180 &self,
181 conn: &Connection,
182 source_id: &str,
183 ) -> Result<()> {
184 conn.execute("DELETE FROM pending_links WHERE source_id = ?1", [source_id])?;
185 Ok(())
186 }
187
188 pub(crate) fn clear_edges_from_on(
190 &self,
191 conn: &Connection,
192 source_id: &str,
193 relation_type: &str,
194 ) -> Result<()> {
195 conn.execute(
196 "DELETE FROM edges WHERE source_id = ?1 AND relation_type = ?2",
197 params![source_id, relation_type],
198 )?;
199 Ok(())
200 }
201
202 #[cfg(feature = "ast")]
204 pub fn insert_symbol_anchor(&self, anchor: &SymbolAnchor) -> Result<()> {
205 self.conn.execute(
206 "INSERT INTO symbol_anchors (symbol_hash, crate_name, module_path, symbol_name, file_path, start_line, end_line, doc_comment)
207 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
208 ON CONFLICT(symbol_hash) DO UPDATE SET
209 crate_name = excluded.crate_name,
210 module_path = excluded.module_path,
211 symbol_name = excluded.symbol_name,
212 file_path = excluded.file_path,
213 start_line = excluded.start_line,
214 end_line = excluded.end_line,
215 doc_comment = excluded.doc_comment",
216 params![
217 anchor.symbol_hash as i64,
218 anchor.crate_name,
219 anchor.module_path,
220 anchor.symbol_name,
221 anchor.file_path,
222 anchor.start_line,
223 anchor.end_line,
224 anchor.doc_comment,
225 ],
226 )?;
227 Ok(())
228 }
229
230 pub fn replace_node_tags(&self, node_id: &str, tags: &[String]) -> Result<()> {
232 self.replace_node_tags_on(&self.conn, node_id, tags)
233 }
234
235 pub(crate) fn replace_node_tags_on(
236 &self,
237 conn: &Connection,
238 node_id: &str,
239 tags: &[String],
240 ) -> Result<()> {
241 conn.execute("DELETE FROM node_tags WHERE node_id = ?1", [node_id])?;
242 for tag in tags {
243 conn.execute(
244 "INSERT OR IGNORE INTO node_tags (node_id, tag) VALUES (?1, ?2)",
245 params![node_id, tag],
246 )?;
247 }
248 Ok(())
249 }
250
251 pub fn replace_node_aliases(&self, node_id: &str, aliases: &[String]) -> Result<()> {
253 self.replace_node_aliases_on(&self.conn, node_id, aliases)
254 }
255
256 pub(crate) fn replace_node_aliases_on(
257 &self,
258 conn: &Connection,
259 node_id: &str,
260 aliases: &[String],
261 ) -> Result<()> {
262 conn.execute("DELETE FROM node_aliases WHERE node_id = ?1", [node_id])?;
263 for alias in aliases {
264 let key = alias.trim().to_lowercase();
265 if key.is_empty() {
266 continue;
267 }
268 conn.execute(
269 "INSERT INTO node_aliases (alias, node_id) VALUES (?1, ?2)
270 ON CONFLICT(alias) DO UPDATE SET node_id = excluded.node_id",
271 params![key, node_id],
272 )?;
273 }
274 Ok(())
275 }
276
277 pub fn index_fts(&self, node_id: &str, title: &str, content: &str, tags: &str) -> Result<()> {
279 self.index_fts_on(&self.conn, node_id, title, content, tags)
280 }
281
282 pub fn get_fts_content(&self, node_id: &str) -> Result<Option<String>> {
284 let mut stmt = self
285 .conn
286 .prepare("SELECT content FROM node_fts WHERE node_id = ?1 LIMIT 1")?;
287 let content: Option<String> = stmt
288 .query_row(params![node_id], |row| row.get(0))
289 .optional()?;
290 Ok(content)
291 }
292
293 pub(crate) fn index_fts_on(
294 &self,
295 conn: &Connection,
296 node_id: &str,
297 title: &str,
298 content: &str,
299 tags: &str,
300 ) -> Result<()> {
301 conn.execute("DELETE FROM node_fts WHERE node_id = ?1", [node_id])?;
302 conn.execute(
303 "INSERT INTO node_fts (node_id, title, content, tags) VALUES (?1, ?2, ?3, ?4)",
304 params![node_id, title, content, tags],
305 )?;
306 Ok(())
307 }
308
309 pub fn search_fts(&self, query: &str) -> Result<Vec<Node>> {
311 let escaped = escape_fts5_query(query)?;
312 let mut stmt = self.conn.prepare(
313 "SELECT n.id, n.node_type, n.title, n.file_path, n.symbol_hash, n.summary,
314 n.content_hash, n.created_at, n.updated_at
315 FROM node_fts f
316 JOIN nodes n ON n.id = f.node_id
317 WHERE node_fts MATCH ?1
318 ORDER BY rank
319 LIMIT 50",
320 )?;
321
322 let rows = stmt.query_map(params![escaped], |row| {
323 let type_str: String = row.get(1)?;
324 let node_type = NodeType::parse(&type_str).unwrap_or(NodeType::Concept);
325 let symbol_hash_raw: Option<i64> = row.get(4)?;
326 Ok(Node {
327 id: row.get(0)?,
328 node_type,
329 title: row.get(2)?,
330 file_path: row.get(3)?,
331 symbol_hash: symbol_hash_raw.map(|h| h as u64),
332 summary: row.get(5)?,
333 content_hash: row.get(6)?,
334 created_at: row.get(7)?,
335 updated_at: row.get(8)?,
336 })
337 })?;
338
339 let mut results = Vec::new();
340 for r in rows {
341 results.push(r.map_err(BrainError::from)?);
342 }
343 Ok(results)
344 }
345
346 pub fn list_node_ids_by_type(&self, node_type: &str) -> Result<Vec<String>> {
348 let mut stmt = self
349 .conn
350 .prepare("SELECT id FROM nodes WHERE node_type = ?1 ORDER BY id")?;
351 let rows = stmt.query_map(params![node_type], |row| row.get(0))?;
352 let mut out = Vec::new();
353 for r in rows {
354 out.push(r?);
355 }
356 Ok(out)
357 }
358
359 pub fn get_node(&self, id: &str) -> Result<Option<Node>> {
361 let mut stmt = self.conn.prepare(
362 "SELECT id, node_type, title, file_path, symbol_hash, summary, content_hash, created_at, updated_at
363 FROM nodes WHERE id = ?1",
364 )?;
365 let node = stmt
366 .query_row(params![id], Self::map_node_row)
367 .optional()?;
368 Ok(node)
369 }
370
371 fn map_node_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Node> {
372 let type_str: String = row.get(1)?;
373 let node_type = NodeType::parse(&type_str).unwrap_or(NodeType::Concept);
374 let symbol_hash_raw: Option<i64> = row.get(4)?;
375 Ok(Node {
376 id: row.get(0)?,
377 node_type,
378 title: row.get(2)?,
379 file_path: row.get(3)?,
380 symbol_hash: symbol_hash_raw.map(|h| h as u64),
381 summary: row.get(5)?,
382 content_hash: row.get(6)?,
383 created_at: row.get(7)?,
384 updated_at: row.get(8)?,
385 })
386 }
387
388 pub fn count_nodes(&self) -> Result<usize> {
390 let count: usize = self
391 .conn
392 .query_row("SELECT COUNT(*) FROM nodes", [], |row| row.get(0))?;
393 Ok(count)
394 }
395
396 pub fn count_edges(&self) -> Result<usize> {
398 let count: usize = self
399 .conn
400 .query_row("SELECT COUNT(*) FROM edges", [], |row| row.get(0))?;
401 Ok(count)
402 }
403
404 pub fn count_fts_rows(&self) -> Result<usize> {
406 let count: usize = self
407 .conn
408 .query_row("SELECT COUNT(*) FROM node_fts", [], |row| row.get(0))?;
409 Ok(count)
410 }
411
412 pub fn count_pending_links(&self) -> Result<usize> {
414 let count: usize = self
415 .conn
416 .query_row("SELECT COUNT(*) FROM pending_links", [], |row| row.get(0))?;
417 Ok(count)
418 }
419
420 pub fn count_symbol_anchors(&self) -> Result<usize> {
422 let count: usize = self
423 .conn
424 .query_row("SELECT COUNT(*) FROM symbol_anchors", [], |row| row.get(0))?;
425 Ok(count)
426 }
427
428 pub fn get_all_node_ids(&self) -> Result<Vec<String>> {
430 let mut stmt = self
431 .conn
432 .prepare("SELECT id FROM nodes ORDER BY id ASC")?;
433 let rows = stmt.query_map([], |row| row.get(0))?;
434 let mut ids = Vec::new();
435 for r in rows {
436 ids.push(r?);
437 }
438 Ok(ids)
439 }
440
441 pub fn get_all_edges(&self) -> Result<Vec<Edge>> {
443 let mut stmt = self.conn.prepare(
444 "SELECT source_id, target_id, relation_type, weight, decay_rate, created_at FROM edges",
445 )?;
446 let rows = stmt.query_map([], |row| {
447 let weight: f64 = row.get(3)?;
448 let decay: f64 = row.get(4)?;
449 Ok(Edge {
450 source_id: row.get(0)?,
451 target_id: row.get(1)?,
452 relation_type: row.get(2)?,
453 weight: weight as f32,
454 decay_rate: decay as f32,
455 created_at: row.get(5)?,
456 })
457 })?;
458
459 let mut edges = Vec::new();
460 for r in rows {
461 edges.push(r?);
462 }
463 Ok(edges)
464 }
465
466 pub fn get_csr_edges(&self) -> Result<Vec<(String, String, f32)>> {
468 Ok(self
469 .get_all_edges()?
470 .into_iter()
471 .map(|e| (e.source_id, e.target_id, e.weight))
472 .collect())
473 }
474
475 pub fn get_all_nodes(&self) -> Result<Vec<Node>> {
477 let mut stmt = self.conn.prepare(
478 "SELECT id, node_type, title, file_path, symbol_hash, summary, content_hash, created_at, updated_at
479 FROM nodes ORDER BY id ASC",
480 )?;
481 let rows = stmt.query_map([], Self::map_node_row)?;
482 let mut nodes = Vec::new();
483 for r in rows {
484 nodes.push(r?);
485 }
486 Ok(nodes)
487 }
488
489 #[allow(clippy::type_complexity)]
491 pub fn link_resolution_maps(
492 &self,
493 ) -> Result<(
494 HashSet<String>,
495 HashMap<String, String>,
496 HashMap<String, String>,
497 )> {
498 let mut ids = HashSet::new();
499 let mut titles: HashMap<String, String> = HashMap::new();
500 {
501 let mut stmt = self.conn.prepare("SELECT id, title FROM nodes")?;
502 let rows = stmt.query_map([], |row| {
503 Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
504 })?;
505 for r in rows {
506 let (id, title) = r?;
507 titles
508 .entry(title.to_lowercase())
509 .or_insert_with(|| id.clone());
510 ids.insert(id);
511 }
512 }
513
514 let mut aliases: HashMap<String, String> = HashMap::new();
515 {
516 let mut stmt = self.conn.prepare("SELECT alias, node_id FROM node_aliases")?;
517 let rows = stmt.query_map([], |row| {
518 Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
519 })?;
520 for r in rows {
521 let (alias, node_id) = r?;
522 aliases.insert(alias, node_id);
523 }
524 }
525
526 Ok((ids, aliases, titles))
527 }
528
529 pub fn resolve_pending_links(&self) -> Result<(usize, usize)> {
531 let (ids, aliases, titles) = self.link_resolution_maps()?;
532 let pending: Vec<(String, String, String, i64)> = {
533 let mut stmt = self.conn.prepare(
534 "SELECT source_id, raw_target, relation_type, created_at FROM pending_links",
535 )?;
536 let rows = stmt.query_map([], |row| {
537 Ok((
538 row.get::<_, String>(0)?,
539 row.get::<_, String>(1)?,
540 row.get::<_, String>(2)?,
541 row.get::<_, i64>(3)?,
542 ))
543 })?;
544 let mut v = Vec::new();
545 for r in rows {
546 v.push(r?);
547 }
548 v
549 };
550
551 let symbol_ids: std::collections::HashSet<String> = ids
553 .iter()
554 .filter(|id| id.starts_with("symbol/"))
555 .cloned()
556 .collect();
557
558 let mut resolved = 0usize;
559 for (source_id, raw_target, relation_type, created_at) in &pending {
560 let target_id = if let Some(sym_path) = raw_target.strip_prefix("symbol:") {
561 crate::symbols::parse_symbol_path(sym_path)
562 .and_then(|s| crate::symbols::resolve_symbol_ref(&s, &symbol_ids))
563 .or_else(|| {
564 crate::symbols::parse_symbol_path(sym_path).and_then(|s| {
566 crate::id::resolve_link_target(
567 &s.symbol_name,
568 &ids,
569 &aliases,
570 &titles,
571 )
572 })
573 })
574 } else {
575 crate::id::resolve_link_target(raw_target, &ids, &aliases, &titles)
576 };
577
578 if let Some(target_id) = target_id {
579 let edge = Edge {
580 source_id: source_id.clone(),
581 target_id,
582 relation_type: relation_type.clone(),
583 weight: 1.0,
584 decay_rate: 0.0,
585 created_at: *created_at,
586 };
587 self.insert_edge(&edge)?;
588 self.conn.execute(
589 "DELETE FROM pending_links WHERE source_id = ?1 AND raw_target = ?2 AND relation_type = ?3",
590 params![source_id, raw_target, relation_type],
591 )?;
592 resolved += 1;
593 }
594 }
595
596 let still = self.count_pending_links()?;
597 Ok((resolved, still))
598 }
599}
600
601#[cfg(test)]
602mod tests {
603 use super::*;
604 use crate::types::NodeType;
605
606 fn sample_node(id: &str) -> Node {
607 Node {
608 id: id.to_string(),
609 node_type: NodeType::Concept,
610 title: id.to_string(),
611 file_path: Some(format!("{id}.md")),
612 symbol_hash: None,
613 summary: Some("summary".into()),
614 content_hash: Some("abc".into()),
615 created_at: 100,
616 updated_at: 100,
617 }
618 }
619
620 #[test]
621 fn fts_idempotent_reindex() {
622 let db = Database::open_in_memory().unwrap();
623 let n = sample_node("docs/raft");
624 db.insert_node(&n).unwrap();
625 db.index_fts(&n.id, &n.title, "raft consensus protocol", "raft").unwrap();
626 db.index_fts(&n.id, &n.title, "raft consensus protocol v2", "raft").unwrap();
627 assert_eq!(db.count_fts_rows().unwrap(), 1);
628 let hits = db.search_fts("raft").unwrap();
629 assert_eq!(hits.len(), 1);
630 }
631
632 #[test]
633 fn edge_requires_endpoints() {
634 let db = Database::open_in_memory().unwrap();
635 let edge = Edge {
636 source_id: "a".into(),
637 target_id: "b".into(),
638 relation_type: "relates_to".into(),
639 weight: 1.0,
640 decay_rate: 0.0,
641 created_at: 1,
642 };
643 assert!(db.insert_edge(&edge).is_err());
644 }
645
646 #[test]
647 fn full_edge_roundtrip() {
648 let db = Database::open_in_memory().unwrap();
649 db.insert_node(&sample_node("a")).unwrap();
650 db.insert_node(&sample_node("b")).unwrap();
651 let edge = Edge {
652 source_id: "a".into(),
653 target_id: "b".into(),
654 relation_type: "implements".into(),
655 weight: 0.75,
656 decay_rate: 0.1,
657 created_at: 42,
658 };
659 db.insert_edge(&edge).unwrap();
660 let edges = db.get_all_edges().unwrap();
661 assert_eq!(edges.len(), 1);
662 assert_eq!(edges[0].relation_type, "implements");
663 assert!((edges[0].weight - 0.75).abs() < 1e-6);
664 assert!((edges[0].decay_rate - 0.1).abs() < 1e-6);
665 assert_eq!(edges[0].created_at, 42);
666 }
667
668 #[test]
669 fn preserves_created_at_on_upsert() {
670 let db = Database::open_in_memory().unwrap();
671 let mut n = sample_node("x");
672 n.created_at = 10;
673 n.updated_at = 10;
674 db.insert_node(&n).unwrap();
675 n.created_at = 999;
676 n.updated_at = 20;
677 n.title = "updated".into();
678 db.insert_node(&n).unwrap();
679 let got = db.get_node("x").unwrap().unwrap();
680 assert_eq!(got.created_at, 10);
681 assert_eq!(got.updated_at, 20);
682 assert_eq!(got.title, "updated");
683 }
684}