Skip to main content

rinne_graph/
store.rs

1//! SQLite-backed store: persist files, freshness checks, neighborhood queries.
2
3use std::collections::hash_map::DefaultHasher;
4use std::hash::{Hash, Hasher};
5use std::path::{Path, PathBuf};
6
7use rusqlite::Connection;
8
9use crate::extract::extract;
10use crate::model::{Neighborhood, Symbol, SymbolKind, SymbolRef};
11use crate::resolve::resolve_file;
12use crate::schema::init_graph_schema;
13use rinne_types::skip::source_lang;
14
15pub struct Store {
16    pub(crate) conn: Connection,
17    root: PathBuf,
18}
19
20impl Store {
21    pub fn open(db_path: &Path, root: &Path) -> rusqlite::Result<Store> {
22        let conn = Connection::open(db_path)?;
23        conn.execute_batch(
24            "PRAGMA journal_mode=WAL;
25             PRAGMA synchronous=NORMAL;",
26        )?;
27        conn.busy_timeout(std::time::Duration::from_secs(5))?;
28        init_graph_schema(&conn)?;
29        Ok(Store { conn, root: root.to_path_buf() })
30    }
31
32    /// Stable content hash for freshness comparison.
33    /// Uses DefaultHasher — deterministic within a build, sufficient for this use.
34    pub fn hash_of(source: &str) -> String {
35        let mut h = DefaultHasher::new();
36        source.hash(&mut h);
37        format!("{:016x}", h.finish())
38    }
39
40    /// Returns true if the stored hash for `path` matches `hash_of(source)`.
41    pub fn is_current(&self, path: &str, source: &str) -> bool {
42        let hash = Self::hash_of(source);
43        self.conn
44            .query_row(
45                "SELECT content_hash FROM graph_files WHERE path = ?1",
46                [path],
47                |row| row.get::<_, String>(0),
48            )
49            .map(|stored| stored == hash)
50            .unwrap_or(false)
51    }
52
53    /// Transactionally re-index a file: delete prior rows, extract+resolve, insert new rows.
54    /// No-ops for files with unsupported languages (upserts only the file row with lang='').
55    pub fn index_file(&self, path: &str, source: &str, mtime: i64) -> rusqlite::Result<()> {
56        let hash = Self::hash_of(source);
57        let lang = source_lang(path);
58
59        let tx = self.conn.unchecked_transaction()?;
60
61        // Delete prior edges for this file's symbols first (FK-style manual cascade).
62        tx.execute(
63            "DELETE FROM graph_edges WHERE src_symbol IN (SELECT id FROM graph_symbols WHERE file = ?1) \
64             OR dst_symbol IN (SELECT id FROM graph_symbols WHERE file = ?1)",
65            rusqlite::params![path],
66        )?;
67        tx.execute(
68            "DELETE FROM graph_symbols WHERE file = ?1",
69            rusqlite::params![path],
70        )?;
71
72        if let Some(lang_str) = lang {
73            if let Some((raw_symbols, raw_edges)) = extract(lang_str, source) {
74                // Insert each symbol, capture its rowid immediately.
75                let mut name_to_id: std::collections::HashMap<String, i64> =
76                    std::collections::HashMap::new();
77
78                for rs in &raw_symbols {
79                    tx.execute(
80                        "INSERT INTO graph_symbols (file, name, kind, start_line, end_line, signature) \
81                         VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
82                        rusqlite::params![
83                            path,
84                            rs.name,
85                            rs.kind.as_str(),
86                            rs.start_line,
87                            rs.end_line,
88                            rs.signature,
89                        ],
90                    )?;
91                    let id = tx.last_insert_rowid();
92                    // Last-write-wins for duplicate names within one file (acceptable for v1).
93                    name_to_id.insert(rs.name.clone(), id);
94                }
95
96                let (_, edges) =
97                    resolve_file(path, raw_symbols, raw_edges, |name| {
98                        name_to_id.get(name).copied().unwrap_or(0)
99                    });
100
101                for edge in &edges {
102                    tx.execute(
103                        "INSERT INTO graph_edges (src_symbol, dst_symbol, dst_name, kind) \
104                         VALUES (?1, ?2, ?3, ?4)",
105                        rusqlite::params![
106                            edge.src,
107                            edge.dst,
108                            edge.dst_name,
109                            edge.kind.as_str(),
110                        ],
111                    )?;
112                }
113            }
114        }
115
116        let now = std::time::SystemTime::now()
117            .duration_since(std::time::UNIX_EPOCH)
118            .map(|d| d.as_secs() as i64)
119            .unwrap_or(0);
120
121        tx.execute(
122            "INSERT INTO graph_files (path, lang, content_hash, mtime, indexed_at)
123             VALUES (?1, ?2, ?3, ?4, ?5)
124             ON CONFLICT(path) DO UPDATE SET
125               lang         = excluded.lang,
126               content_hash = excluded.content_hash,
127               mtime        = excluded.mtime,
128               indexed_at   = excluded.indexed_at",
129            rusqlite::params![path, lang.unwrap_or(""), hash, mtime, now],
130        )?;
131
132        tx.commit()
133    }
134
135    /// Returns the definition + callers + callees + imports for a symbol by name.
136    pub fn neighborhood(&self, symbol_name: &str) -> Option<Neighborhood> {
137        // Look up the definition symbol.
138        let (sym_id, file, start_line): (i64, String, u32) = self
139            .conn
140            .query_row(
141                "SELECT id, file, start_line FROM graph_symbols WHERE name = ?1 LIMIT 1",
142                [symbol_name],
143                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
144            )
145            .ok()?;
146
147        let definition = SymbolRef {
148            name: symbol_name.to_string(),
149            file: file.clone(),
150            line: start_line,
151        };
152
153        // Callers: symbols whose id is src_symbol of an edge with dst_symbol = sym_id.
154        let callers = self
155            .conn
156            .prepare(
157                "SELECT s.name, s.file, s.start_line
158                 FROM graph_edges e
159                 JOIN graph_symbols s ON s.id = e.src_symbol
160                 WHERE e.dst_symbol = ?1 AND e.kind = 'calls'",
161            )
162            .and_then(|mut stmt| {
163                stmt.query_map([sym_id], |row| {
164                    Ok(SymbolRef {
165                        name: row.get(0)?,
166                        file: row.get(1)?,
167                        line: row.get(2)?,
168                    })
169                })
170                .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
171            })
172            .unwrap_or_default();
173
174        // Callees: symbols whose id is dst_symbol of an edge with src_symbol = sym_id.
175        let callees = self
176            .conn
177            .prepare(
178                "SELECT s.name, s.file, s.start_line
179                 FROM graph_edges e
180                 JOIN graph_symbols s ON s.id = e.dst_symbol
181                 WHERE e.src_symbol = ?1 AND e.kind = 'calls'",
182            )
183            .and_then(|mut stmt| {
184                stmt.query_map([sym_id], |row| {
185                    Ok(SymbolRef {
186                        name: row.get(0)?,
187                        file: row.get(1)?,
188                        line: row.get(2)?,
189                    })
190                })
191                .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
192            })
193            .unwrap_or_default();
194
195        // Imports: edges of kind 'imports' where src_symbol = sym_id; dst may be unresolved.
196        // When dst_symbol is set, join on symbols; otherwise use dst_name best-effort.
197        let imports = self
198            .conn
199            .prepare(
200                "SELECT COALESCE(s.name, e.dst_name), COALESCE(s.file, ''), COALESCE(s.start_line, 0)
201                 FROM graph_edges e
202                 LEFT JOIN graph_symbols s ON s.id = e.dst_symbol
203                 WHERE e.src_symbol = ?1 AND e.kind = 'imports'",
204            )
205            .and_then(|mut stmt| {
206                stmt.query_map([sym_id], |row| {
207                    Ok(SymbolRef {
208                        name: row.get(0)?,
209                        file: row.get(1)?,
210                        line: row.get(2)?,
211                    })
212                })
213                .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
214            })
215            .unwrap_or_default();
216
217        let stale = {
218            let abs = self.root.join(&definition.file);
219            match std::fs::read_to_string(&abs) {
220                Ok(contents) => {
221                    let cur = Self::hash_of(&contents);
222                    let stored: Option<String> = self
223                        .conn
224                        .query_row(
225                            "SELECT content_hash FROM graph_files WHERE path = ?1",
226                            [definition.file.as_str()],
227                            |r| r.get(0),
228                        )
229                        .ok();
230                    stored.map(|s| s != cur).unwrap_or(false)
231                }
232                Err(_) => false,
233            }
234        };
235
236        Some(Neighborhood {
237            definition,
238            callers,
239            callees,
240            imports,
241            stale,
242        })
243    }
244
245    /// Returns the names of every symbol currently in the index.
246    pub fn symbol_names(&self) -> Vec<String> {
247        self.conn
248            .prepare("SELECT DISTINCT name FROM graph_symbols")
249            .and_then(|mut stmt| {
250                stmt.query_map([], |row| row.get(0))
251                    .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
252            })
253            .unwrap_or_default()
254    }
255
256    /// Returns the first symbol named `name` in `file`.
257    pub fn resolve_in_file(&self, file: &str, name: &str) -> Option<SymbolRef> {
258        self.conn
259            .query_row(
260                "SELECT name, file, start_line FROM graph_symbols WHERE file = ?1 AND name = ?2 LIMIT 1",
261                rusqlite::params![file, name],
262                |row| {
263                    Ok(SymbolRef {
264                        name: row.get(0)?,
265                        file: row.get(1)?,
266                        line: row.get(2)?,
267                    })
268                },
269            )
270            .ok()
271    }
272
273    /// Returns (files, symbols, edges) counts for `rinne graph stats`.
274    pub fn stats(&self) -> (usize, usize, usize) {
275        let count = |sql: &str| -> usize {
276            self.conn
277                .query_row(sql, [], |row| row.get::<_, i64>(0))
278                .unwrap_or(0) as usize
279        };
280        (
281            count("SELECT COUNT(*) FROM graph_files"),
282            count("SELECT COUNT(*) FROM graph_symbols"),
283            count("SELECT COUNT(*) FROM graph_edges"),
284        )
285    }
286
287    /// Returns all symbols defined in a given file.
288    pub fn symbols_in(&self, path: &str) -> Vec<Symbol> {
289        self.conn
290            .prepare(
291                "SELECT id, file, name, kind, start_line, end_line, signature
292                 FROM graph_symbols WHERE file = ?1",
293            )
294            .and_then(|mut stmt| {
295                stmt.query_map([path], |row| {
296                    let kind_str: String = row.get(3)?;
297                    let kind =
298                        SymbolKind::from_str(&kind_str).unwrap_or(SymbolKind::Function);
299                    Ok(Symbol {
300                        id: row.get(0)?,
301                        file: row.get(1)?,
302                        name: row.get(2)?,
303                        kind,
304                        start_line: row.get(4)?,
305                        end_line: row.get(5)?,
306                        signature: row.get(6)?,
307                    })
308                })
309                .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
310            })
311            .unwrap_or_default()
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318
319    fn mem_store() -> Store {
320        let conn = rusqlite::Connection::open_in_memory().unwrap();
321        crate::schema::init_graph_schema(&conn).unwrap();
322        Store { conn, root: std::env::temp_dir() }
323    }
324
325    #[test]
326    fn index_then_query_neighborhood() {
327        let store = mem_store();
328        let src = "fn helper() {}\nfn main() { helper(); }\n";
329        store.index_file("src/main.rs", src, 0).unwrap();
330
331        let nb = store.neighborhood("helper").expect("helper indexed");
332        assert_eq!(nb.definition.name, "helper");
333        assert!(nb.callers.iter().any(|c| c.name == "main"));
334        assert!(!nb.stale);
335    }
336
337    #[test]
338    fn is_current_tracks_content_hash() {
339        let store = mem_store();
340        let src = "fn a() {}\n";
341        store.index_file("a.rs", src, 0).unwrap();
342        assert!(store.is_current("a.rs", src));
343        assert!(!store.is_current("a.rs", "fn a() {}\nfn b() {}\n"));
344    }
345
346    #[test]
347    fn reindex_replaces_prior_symbols() {
348        let store = mem_store();
349        store.index_file("a.rs", "fn a() {}\n", 0).unwrap();
350        store.index_file("a.rs", "fn c() {}\n", 1).unwrap();
351        assert!(store.neighborhood("a").is_none());
352        assert!(store.neighborhood("c").is_some());
353    }
354
355    #[test]
356    fn reindex_handles_path_with_quote() {
357        let store = mem_store();
358        let path = "weird'name.rs";
359        store.index_file(path, "fn first_sym() {}\n", 0).unwrap();
360        store.index_file(path, "fn second_sym() {}\n", 1).unwrap();
361        assert!(store.neighborhood("first_sym").is_none(), "old symbol must be gone after reindex");
362        assert!(store.neighborhood("second_sym").is_some(), "new symbol must exist after reindex");
363    }
364
365    #[test]
366    fn neighborhood_reports_stale_when_file_changed_on_disk() {
367        let dir = std::env::temp_dir().join(format!("rinne-stale-{}", std::process::id()));
368        std::fs::create_dir_all(&dir).unwrap();
369        let file = dir.join("m.rs");
370        std::fs::write(&file, "fn helper() {}\nfn main() { helper(); }\n").unwrap();
371
372        let store = Store::open(&dir.join("state.db"), &dir).unwrap();
373        let src = std::fs::read_to_string(&file).unwrap();
374        store.index_file("m.rs", &src, 0).unwrap();
375
376        // Fresh: not stale.
377        assert!(!store.neighborhood("helper").unwrap().stale);
378
379        // Mutate the file on disk without reindexing.
380        std::fs::write(&file, "fn helper() {}\nfn main() { helper(); helper(); }\n").unwrap();
381        assert!(store.neighborhood("helper").unwrap().stale, "must report stale after on-disk edit");
382
383        let _ = std::fs::remove_dir_all(&dir);
384    }
385}