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(crate) fn index_fts_on(
283 &self,
284 conn: &Connection,
285 node_id: &str,
286 title: &str,
287 content: &str,
288 tags: &str,
289 ) -> Result<()> {
290 conn.execute("DELETE FROM node_fts WHERE node_id = ?1", [node_id])?;
291 conn.execute(
292 "INSERT INTO node_fts (node_id, title, content, tags) VALUES (?1, ?2, ?3, ?4)",
293 params![node_id, title, content, tags],
294 )?;
295 Ok(())
296 }
297
298 pub fn search_fts(&self, query: &str) -> Result<Vec<Node>> {
300 let escaped = escape_fts5_query(query)?;
301 let mut stmt = self.conn.prepare(
302 "SELECT n.id, n.node_type, n.title, n.file_path, n.symbol_hash, n.summary,
303 n.content_hash, n.created_at, n.updated_at
304 FROM node_fts f
305 JOIN nodes n ON n.id = f.node_id
306 WHERE node_fts MATCH ?1
307 ORDER BY rank
308 LIMIT 50",
309 )?;
310
311 let rows = stmt.query_map(params![escaped], |row| {
312 let type_str: String = row.get(1)?;
313 let node_type = NodeType::parse(&type_str).unwrap_or(NodeType::Concept);
314 let symbol_hash_raw: Option<i64> = row.get(4)?;
315 Ok(Node {
316 id: row.get(0)?,
317 node_type,
318 title: row.get(2)?,
319 file_path: row.get(3)?,
320 symbol_hash: symbol_hash_raw.map(|h| h as u64),
321 summary: row.get(5)?,
322 content_hash: row.get(6)?,
323 created_at: row.get(7)?,
324 updated_at: row.get(8)?,
325 })
326 })?;
327
328 let mut results = Vec::new();
329 for r in rows {
330 results.push(r.map_err(BrainError::from)?);
331 }
332 Ok(results)
333 }
334
335 pub fn get_node(&self, id: &str) -> Result<Option<Node>> {
337 let mut stmt = self.conn.prepare(
338 "SELECT id, node_type, title, file_path, symbol_hash, summary, content_hash, created_at, updated_at
339 FROM nodes WHERE id = ?1",
340 )?;
341 let node = stmt
342 .query_row(params![id], Self::map_node_row)
343 .optional()?;
344 Ok(node)
345 }
346
347 fn map_node_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Node> {
348 let type_str: String = row.get(1)?;
349 let node_type = NodeType::parse(&type_str).unwrap_or(NodeType::Concept);
350 let symbol_hash_raw: Option<i64> = row.get(4)?;
351 Ok(Node {
352 id: row.get(0)?,
353 node_type,
354 title: row.get(2)?,
355 file_path: row.get(3)?,
356 symbol_hash: symbol_hash_raw.map(|h| h as u64),
357 summary: row.get(5)?,
358 content_hash: row.get(6)?,
359 created_at: row.get(7)?,
360 updated_at: row.get(8)?,
361 })
362 }
363
364 pub fn count_nodes(&self) -> Result<usize> {
366 let count: usize = self
367 .conn
368 .query_row("SELECT COUNT(*) FROM nodes", [], |row| row.get(0))?;
369 Ok(count)
370 }
371
372 pub fn count_edges(&self) -> Result<usize> {
374 let count: usize = self
375 .conn
376 .query_row("SELECT COUNT(*) FROM edges", [], |row| row.get(0))?;
377 Ok(count)
378 }
379
380 pub fn count_fts_rows(&self) -> Result<usize> {
382 let count: usize = self
383 .conn
384 .query_row("SELECT COUNT(*) FROM node_fts", [], |row| row.get(0))?;
385 Ok(count)
386 }
387
388 pub fn count_pending_links(&self) -> Result<usize> {
390 let count: usize = self
391 .conn
392 .query_row("SELECT COUNT(*) FROM pending_links", [], |row| row.get(0))?;
393 Ok(count)
394 }
395
396 pub fn count_symbol_anchors(&self) -> Result<usize> {
398 let count: usize = self
399 .conn
400 .query_row("SELECT COUNT(*) FROM symbol_anchors", [], |row| row.get(0))?;
401 Ok(count)
402 }
403
404 pub fn get_all_node_ids(&self) -> Result<Vec<String>> {
406 let mut stmt = self
407 .conn
408 .prepare("SELECT id FROM nodes ORDER BY id ASC")?;
409 let rows = stmt.query_map([], |row| row.get(0))?;
410 let mut ids = Vec::new();
411 for r in rows {
412 ids.push(r?);
413 }
414 Ok(ids)
415 }
416
417 pub fn get_all_edges(&self) -> Result<Vec<Edge>> {
419 let mut stmt = self.conn.prepare(
420 "SELECT source_id, target_id, relation_type, weight, decay_rate, created_at FROM edges",
421 )?;
422 let rows = stmt.query_map([], |row| {
423 let weight: f64 = row.get(3)?;
424 let decay: f64 = row.get(4)?;
425 Ok(Edge {
426 source_id: row.get(0)?,
427 target_id: row.get(1)?,
428 relation_type: row.get(2)?,
429 weight: weight as f32,
430 decay_rate: decay as f32,
431 created_at: row.get(5)?,
432 })
433 })?;
434
435 let mut edges = Vec::new();
436 for r in rows {
437 edges.push(r?);
438 }
439 Ok(edges)
440 }
441
442 pub fn get_csr_edges(&self) -> Result<Vec<(String, String, f32)>> {
444 Ok(self
445 .get_all_edges()?
446 .into_iter()
447 .map(|e| (e.source_id, e.target_id, e.weight))
448 .collect())
449 }
450
451 pub fn get_all_nodes(&self) -> Result<Vec<Node>> {
453 let mut stmt = self.conn.prepare(
454 "SELECT id, node_type, title, file_path, symbol_hash, summary, content_hash, created_at, updated_at
455 FROM nodes ORDER BY id ASC",
456 )?;
457 let rows = stmt.query_map([], Self::map_node_row)?;
458 let mut nodes = Vec::new();
459 for r in rows {
460 nodes.push(r?);
461 }
462 Ok(nodes)
463 }
464
465 #[allow(clippy::type_complexity)]
467 pub fn link_resolution_maps(
468 &self,
469 ) -> Result<(
470 HashSet<String>,
471 HashMap<String, String>,
472 HashMap<String, String>,
473 )> {
474 let mut ids = HashSet::new();
475 let mut titles: HashMap<String, String> = HashMap::new();
476 {
477 let mut stmt = self.conn.prepare("SELECT id, title FROM nodes")?;
478 let rows = stmt.query_map([], |row| {
479 Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
480 })?;
481 for r in rows {
482 let (id, title) = r?;
483 titles
484 .entry(title.to_lowercase())
485 .or_insert_with(|| id.clone());
486 ids.insert(id);
487 }
488 }
489
490 let mut aliases: HashMap<String, String> = HashMap::new();
491 {
492 let mut stmt = self.conn.prepare("SELECT alias, node_id FROM node_aliases")?;
493 let rows = stmt.query_map([], |row| {
494 Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
495 })?;
496 for r in rows {
497 let (alias, node_id) = r?;
498 aliases.insert(alias, node_id);
499 }
500 }
501
502 Ok((ids, aliases, titles))
503 }
504
505 pub fn resolve_pending_links(&self) -> Result<(usize, usize)> {
507 let (ids, aliases, titles) = self.link_resolution_maps()?;
508 let pending: Vec<(String, String, String, i64)> = {
509 let mut stmt = self.conn.prepare(
510 "SELECT source_id, raw_target, relation_type, created_at FROM pending_links",
511 )?;
512 let rows = stmt.query_map([], |row| {
513 Ok((
514 row.get::<_, String>(0)?,
515 row.get::<_, String>(1)?,
516 row.get::<_, String>(2)?,
517 row.get::<_, i64>(3)?,
518 ))
519 })?;
520 let mut v = Vec::new();
521 for r in rows {
522 v.push(r?);
523 }
524 v
525 };
526
527 let symbol_ids: std::collections::HashSet<String> = ids
529 .iter()
530 .filter(|id| id.starts_with("symbol/"))
531 .cloned()
532 .collect();
533
534 let mut resolved = 0usize;
535 for (source_id, raw_target, relation_type, created_at) in &pending {
536 let target_id = if let Some(sym_path) = raw_target.strip_prefix("symbol:") {
537 crate::symbols::parse_symbol_path(sym_path)
538 .and_then(|s| crate::symbols::resolve_symbol_ref(&s, &symbol_ids))
539 .or_else(|| {
540 crate::symbols::parse_symbol_path(sym_path).and_then(|s| {
542 crate::id::resolve_link_target(
543 &s.symbol_name,
544 &ids,
545 &aliases,
546 &titles,
547 )
548 })
549 })
550 } else {
551 crate::id::resolve_link_target(raw_target, &ids, &aliases, &titles)
552 };
553
554 if let Some(target_id) = target_id {
555 let edge = Edge {
556 source_id: source_id.clone(),
557 target_id,
558 relation_type: relation_type.clone(),
559 weight: 1.0,
560 decay_rate: 0.0,
561 created_at: *created_at,
562 };
563 self.insert_edge(&edge)?;
564 self.conn.execute(
565 "DELETE FROM pending_links WHERE source_id = ?1 AND raw_target = ?2 AND relation_type = ?3",
566 params![source_id, raw_target, relation_type],
567 )?;
568 resolved += 1;
569 }
570 }
571
572 let still = self.count_pending_links()?;
573 Ok((resolved, still))
574 }
575}
576
577#[cfg(test)]
578mod tests {
579 use super::*;
580 use crate::types::NodeType;
581
582 fn sample_node(id: &str) -> Node {
583 Node {
584 id: id.to_string(),
585 node_type: NodeType::Concept,
586 title: id.to_string(),
587 file_path: Some(format!("{id}.md")),
588 symbol_hash: None,
589 summary: Some("summary".into()),
590 content_hash: Some("abc".into()),
591 created_at: 100,
592 updated_at: 100,
593 }
594 }
595
596 #[test]
597 fn fts_idempotent_reindex() {
598 let db = Database::open_in_memory().unwrap();
599 let n = sample_node("docs/raft");
600 db.insert_node(&n).unwrap();
601 db.index_fts(&n.id, &n.title, "raft consensus protocol", "raft").unwrap();
602 db.index_fts(&n.id, &n.title, "raft consensus protocol v2", "raft").unwrap();
603 assert_eq!(db.count_fts_rows().unwrap(), 1);
604 let hits = db.search_fts("raft").unwrap();
605 assert_eq!(hits.len(), 1);
606 }
607
608 #[test]
609 fn edge_requires_endpoints() {
610 let db = Database::open_in_memory().unwrap();
611 let edge = Edge {
612 source_id: "a".into(),
613 target_id: "b".into(),
614 relation_type: "relates_to".into(),
615 weight: 1.0,
616 decay_rate: 0.0,
617 created_at: 1,
618 };
619 assert!(db.insert_edge(&edge).is_err());
620 }
621
622 #[test]
623 fn full_edge_roundtrip() {
624 let db = Database::open_in_memory().unwrap();
625 db.insert_node(&sample_node("a")).unwrap();
626 db.insert_node(&sample_node("b")).unwrap();
627 let edge = Edge {
628 source_id: "a".into(),
629 target_id: "b".into(),
630 relation_type: "implements".into(),
631 weight: 0.75,
632 decay_rate: 0.1,
633 created_at: 42,
634 };
635 db.insert_edge(&edge).unwrap();
636 let edges = db.get_all_edges().unwrap();
637 assert_eq!(edges.len(), 1);
638 assert_eq!(edges[0].relation_type, "implements");
639 assert!((edges[0].weight - 0.75).abs() < 1e-6);
640 assert!((edges[0].decay_rate - 0.1).abs() < 1e-6);
641 assert_eq!(edges[0].created_at, 42);
642 }
643
644 #[test]
645 fn preserves_created_at_on_upsert() {
646 let db = Database::open_in_memory().unwrap();
647 let mut n = sample_node("x");
648 n.created_at = 10;
649 n.updated_at = 10;
650 db.insert_node(&n).unwrap();
651 n.created_at = 999;
652 n.updated_at = 20;
653 n.title = "updated".into();
654 db.insert_node(&n).unwrap();
655 let got = db.get_node("x").unwrap().unwrap();
656 assert_eq!(got.created_at, 10);
657 assert_eq!(got.updated_at, 20);
658 assert_eq!(got.title, "updated");
659 }
660}