Skip to main content

rustbrain_core/storage/
db.rs

1//! SQLite database handle with transactional, FTS-safe APIs.
2//!
3//! Prefer [`crate::Brain`] for application code. Use [`Database`] when building
4//! custom tools that need direct control over transactions, FTS, or migrations.
5
6use 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
16/// Master transactional store for a single brain (`.brain/db.sqlite`).
17///
18/// The connection is crate-visible for ranked-query helpers; external
19/// consumers use typed methods only.
20pub struct Database {
21    pub(crate) conn: Connection,
22}
23
24impl Database {
25    /// Open or create a database at `path`, apply pragmas, and run migrations.
26    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    /// Open an in-memory database (tests).
35    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        // WAL is best-effort (no-op / different for pure in-memory DBs).
47        let _ = self.conn.pragma_update(None, "journal_mode", "WAL");
48        let _ = self.conn.pragma_update(None, "synchronous", "NORMAL");
49        Ok(())
50    }
51
52    /// Run `f` inside a single transaction (unchecked; suitable for &self).
53    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    /// Insert or update a node. Preserves `created_at` on conflict when the
64    /// existing row is older (caller should pass original created_at when known).
65    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        // Preserve created_at if node already exists.
71        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    /// Fetch content_hash for a node if present.
108    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    /// Insert or update a weighted edge. Both endpoints must exist.
121    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    /// Record an unresolved WikiLink for later resolution / reporting.
145    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    /// Clear all pending links originating from `source_id` (before re-resolve).
173    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    /// Clear outbound relates_to edges for a source before re-link (idempotent reindex).
189    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    /// Insert or update a code symbol anchor row (AST metadata).
203    #[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    /// Replace the full tag set for a node.
231    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    /// Replace aliases for a node.
252    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    /// Idempotent FTS upsert: delete existing rows for `node_id`, then insert once.
278    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    /// Fetch indexed FTS body/content for a node (for context excerpts).
283    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    /// Search nodes using FTS5 BM25 ranking with a safely escaped query.
310    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    /// Fetch a single node by id, if present.
347    pub fn get_node(&self, id: &str) -> Result<Option<Node>> {
348        let mut stmt = self.conn.prepare(
349            "SELECT id, node_type, title, file_path, symbol_hash, summary, content_hash, created_at, updated_at
350             FROM nodes WHERE id = ?1",
351        )?;
352        let node = stmt
353            .query_row(params![id], Self::map_node_row)
354            .optional()?;
355        Ok(node)
356    }
357
358    fn map_node_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Node> {
359        let type_str: String = row.get(1)?;
360        let node_type = NodeType::parse(&type_str).unwrap_or(NodeType::Concept);
361        let symbol_hash_raw: Option<i64> = row.get(4)?;
362        Ok(Node {
363            id: row.get(0)?,
364            node_type,
365            title: row.get(2)?,
366            file_path: row.get(3)?,
367            symbol_hash: symbol_hash_raw.map(|h| h as u64),
368            summary: row.get(5)?,
369            content_hash: row.get(6)?,
370            created_at: row.get(7)?,
371            updated_at: row.get(8)?,
372        })
373    }
374
375    /// Number of rows in `nodes`.
376    pub fn count_nodes(&self) -> Result<usize> {
377        let count: usize = self
378            .conn
379            .query_row("SELECT COUNT(*) FROM nodes", [], |row| row.get(0))?;
380        Ok(count)
381    }
382
383    /// Number of rows in `edges`.
384    pub fn count_edges(&self) -> Result<usize> {
385        let count: usize = self
386            .conn
387            .query_row("SELECT COUNT(*) FROM edges", [], |row| row.get(0))?;
388        Ok(count)
389    }
390
391    /// Number of rows in the FTS5 `node_fts` table (should equal indexed notes).
392    pub fn count_fts_rows(&self) -> Result<usize> {
393        let count: usize = self
394            .conn
395            .query_row("SELECT COUNT(*) FROM node_fts", [], |row| row.get(0))?;
396        Ok(count)
397    }
398
399    /// Number of unresolved WikiLink / symbol refs in `pending_links`.
400    pub fn count_pending_links(&self) -> Result<usize> {
401        let count: usize = self
402            .conn
403            .query_row("SELECT COUNT(*) FROM pending_links", [], |row| row.get(0))?;
404        Ok(count)
405    }
406
407    /// Number of AST symbol anchor rows.
408    pub fn count_symbol_anchors(&self) -> Result<usize> {
409        let count: usize = self
410            .conn
411            .query_row("SELECT COUNT(*) FROM symbol_anchors", [], |row| row.get(0))?;
412        Ok(count)
413    }
414
415    /// All node IDs in stable ascending order (CSR index order).
416    pub fn get_all_node_ids(&self) -> Result<Vec<String>> {
417        let mut stmt = self
418            .conn
419            .prepare("SELECT id FROM nodes ORDER BY id ASC")?;
420        let rows = stmt.query_map([], |row| row.get(0))?;
421        let mut ids = Vec::new();
422        for r in rows {
423            ids.push(r?);
424        }
425        Ok(ids)
426    }
427
428    /// Full edge records (relation_type preserved).
429    pub fn get_all_edges(&self) -> Result<Vec<Edge>> {
430        let mut stmt = self.conn.prepare(
431            "SELECT source_id, target_id, relation_type, weight, decay_rate, created_at FROM edges",
432        )?;
433        let rows = stmt.query_map([], |row| {
434            let weight: f64 = row.get(3)?;
435            let decay: f64 = row.get(4)?;
436            Ok(Edge {
437                source_id: row.get(0)?,
438                target_id: row.get(1)?,
439                relation_type: row.get(2)?,
440                weight: weight as f32,
441                decay_rate: decay as f32,
442                created_at: row.get(5)?,
443            })
444        })?;
445
446        let mut edges = Vec::new();
447        for r in rows {
448            edges.push(r?);
449        }
450        Ok(edges)
451    }
452
453    /// Lightweight edge triples for CSR compile: (source, target, weight).
454    pub fn get_csr_edges(&self) -> Result<Vec<(String, String, f32)>> {
455        Ok(self
456            .get_all_edges()?
457            .into_iter()
458            .map(|e| (e.source_id, e.target_id, e.weight))
459            .collect())
460    }
461
462    /// All nodes ordered by id ascending (export / CSR compile order).
463    pub fn get_all_nodes(&self) -> Result<Vec<Node>> {
464        let mut stmt = self.conn.prepare(
465            "SELECT id, node_type, title, file_path, symbol_hash, summary, content_hash, created_at, updated_at
466             FROM nodes ORDER BY id ASC",
467        )?;
468        let rows = stmt.query_map([], Self::map_node_row)?;
469        let mut nodes = Vec::new();
470        for r in rows {
471            nodes.push(r?);
472        }
473        Ok(nodes)
474    }
475
476    /// Build resolution maps: ids, alias→id, lowercase title→id.
477    #[allow(clippy::type_complexity)]
478    pub fn link_resolution_maps(
479        &self,
480    ) -> Result<(
481        HashSet<String>,
482        HashMap<String, String>,
483        HashMap<String, String>,
484    )> {
485        let mut ids = HashSet::new();
486        let mut titles: HashMap<String, String> = HashMap::new();
487        {
488            let mut stmt = self.conn.prepare("SELECT id, title FROM nodes")?;
489            let rows = stmt.query_map([], |row| {
490                Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
491            })?;
492            for r in rows {
493                let (id, title) = r?;
494                titles
495                    .entry(title.to_lowercase())
496                    .or_insert_with(|| id.clone());
497                ids.insert(id);
498            }
499        }
500
501        let mut aliases: HashMap<String, String> = HashMap::new();
502        {
503            let mut stmt = self.conn.prepare("SELECT alias, node_id FROM node_aliases")?;
504            let rows = stmt.query_map([], |row| {
505                Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
506            })?;
507            for r in rows {
508                let (alias, node_id) = r?;
509                aliases.insert(alias, node_id);
510            }
511        }
512
513        Ok((ids, aliases, titles))
514    }
515
516    /// Attempt to resolve all pending links; returns (resolved, still_pending).
517    pub fn resolve_pending_links(&self) -> Result<(usize, usize)> {
518        let (ids, aliases, titles) = self.link_resolution_maps()?;
519        let pending: Vec<(String, String, String, i64)> = {
520            let mut stmt = self.conn.prepare(
521                "SELECT source_id, raw_target, relation_type, created_at FROM pending_links",
522            )?;
523            let rows = stmt.query_map([], |row| {
524                Ok((
525                    row.get::<_, String>(0)?,
526                    row.get::<_, String>(1)?,
527                    row.get::<_, String>(2)?,
528                    row.get::<_, i64>(3)?,
529                ))
530            })?;
531            let mut v = Vec::new();
532            for r in rows {
533                v.push(r?);
534            }
535            v
536        };
537
538        // Symbol node id set for `symbol:…` pending targets.
539        let symbol_ids: std::collections::HashSet<String> = ids
540            .iter()
541            .filter(|id| id.starts_with("symbol/"))
542            .cloned()
543            .collect();
544
545        let mut resolved = 0usize;
546        for (source_id, raw_target, relation_type, created_at) in &pending {
547            let target_id = if let Some(sym_path) = raw_target.strip_prefix("symbol:") {
548                crate::symbols::parse_symbol_path(sym_path)
549                    .and_then(|s| crate::symbols::resolve_symbol_ref(&s, &symbol_ids))
550                    .or_else(|| {
551                        // bare name via aliases/titles
552                        crate::symbols::parse_symbol_path(sym_path).and_then(|s| {
553                            crate::id::resolve_link_target(
554                                &s.symbol_name,
555                                &ids,
556                                &aliases,
557                                &titles,
558                            )
559                        })
560                    })
561            } else {
562                crate::id::resolve_link_target(raw_target, &ids, &aliases, &titles)
563            };
564
565            if let Some(target_id) = target_id {
566                let edge = Edge {
567                    source_id: source_id.clone(),
568                    target_id,
569                    relation_type: relation_type.clone(),
570                    weight: 1.0,
571                    decay_rate: 0.0,
572                    created_at: *created_at,
573                };
574                self.insert_edge(&edge)?;
575                self.conn.execute(
576                    "DELETE FROM pending_links WHERE source_id = ?1 AND raw_target = ?2 AND relation_type = ?3",
577                    params![source_id, raw_target, relation_type],
578                )?;
579                resolved += 1;
580            }
581        }
582
583        let still = self.count_pending_links()?;
584        Ok((resolved, still))
585    }
586}
587
588#[cfg(test)]
589mod tests {
590    use super::*;
591    use crate::types::NodeType;
592
593    fn sample_node(id: &str) -> Node {
594        Node {
595            id: id.to_string(),
596            node_type: NodeType::Concept,
597            title: id.to_string(),
598            file_path: Some(format!("{id}.md")),
599            symbol_hash: None,
600            summary: Some("summary".into()),
601            content_hash: Some("abc".into()),
602            created_at: 100,
603            updated_at: 100,
604        }
605    }
606
607    #[test]
608    fn fts_idempotent_reindex() {
609        let db = Database::open_in_memory().unwrap();
610        let n = sample_node("docs/raft");
611        db.insert_node(&n).unwrap();
612        db.index_fts(&n.id, &n.title, "raft consensus protocol", "raft").unwrap();
613        db.index_fts(&n.id, &n.title, "raft consensus protocol v2", "raft").unwrap();
614        assert_eq!(db.count_fts_rows().unwrap(), 1);
615        let hits = db.search_fts("raft").unwrap();
616        assert_eq!(hits.len(), 1);
617    }
618
619    #[test]
620    fn edge_requires_endpoints() {
621        let db = Database::open_in_memory().unwrap();
622        let edge = Edge {
623            source_id: "a".into(),
624            target_id: "b".into(),
625            relation_type: "relates_to".into(),
626            weight: 1.0,
627            decay_rate: 0.0,
628            created_at: 1,
629        };
630        assert!(db.insert_edge(&edge).is_err());
631    }
632
633    #[test]
634    fn full_edge_roundtrip() {
635        let db = Database::open_in_memory().unwrap();
636        db.insert_node(&sample_node("a")).unwrap();
637        db.insert_node(&sample_node("b")).unwrap();
638        let edge = Edge {
639            source_id: "a".into(),
640            target_id: "b".into(),
641            relation_type: "implements".into(),
642            weight: 0.75,
643            decay_rate: 0.1,
644            created_at: 42,
645        };
646        db.insert_edge(&edge).unwrap();
647        let edges = db.get_all_edges().unwrap();
648        assert_eq!(edges.len(), 1);
649        assert_eq!(edges[0].relation_type, "implements");
650        assert!((edges[0].weight - 0.75).abs() < 1e-6);
651        assert!((edges[0].decay_rate - 0.1).abs() < 1e-6);
652        assert_eq!(edges[0].created_at, 42);
653    }
654
655    #[test]
656    fn preserves_created_at_on_upsert() {
657        let db = Database::open_in_memory().unwrap();
658        let mut n = sample_node("x");
659        n.created_at = 10;
660        n.updated_at = 10;
661        db.insert_node(&n).unwrap();
662        n.created_at = 999;
663        n.updated_at = 20;
664        n.title = "updated".into();
665        db.insert_node(&n).unwrap();
666        let got = db.get_node("x").unwrap().unwrap();
667        assert_eq!(got.created_at, 10);
668        assert_eq!(got.updated_at, 20);
669        assert_eq!(got.title, "updated");
670    }
671}