1use 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 crate::schema::migrate_graph_if_stale(&conn)?;
31 init_graph_schema(&conn)?;
32 Ok(Store {
33 conn,
34 root: root.to_path_buf(),
35 })
36 }
37
38 pub fn hash_of(source: &str) -> String {
41 let mut h = DefaultHasher::new();
42 source.hash(&mut h);
43 format!("{:016x}", h.finish())
44 }
45
46 pub fn is_current(&self, path: &str, source: &str) -> bool {
48 let hash = Self::hash_of(source);
49 self.conn
50 .query_row(
51 "SELECT content_hash FROM graph_files WHERE path = ?1",
52 [path],
53 |row| row.get::<_, String>(0),
54 )
55 .map(|stored| stored == hash)
56 .unwrap_or(false)
57 }
58
59 pub fn index_file(&self, path: &str, source: &str, mtime: i64) -> rusqlite::Result<()> {
62 let hash = Self::hash_of(source);
63 let lang = source_lang(path);
64
65 let tx = self.conn.unchecked_transaction()?;
66
67 tx.execute(
69 "DELETE FROM graph_edges WHERE src_symbol IN (SELECT id FROM graph_symbols WHERE file = ?1) \
70 OR dst_symbol IN (SELECT id FROM graph_symbols WHERE file = ?1)",
71 rusqlite::params![path],
72 )?;
73 tx.execute(
74 "DELETE FROM graph_symbols WHERE file = ?1",
75 rusqlite::params![path],
76 )?;
77
78 if let Some(lang_str) = lang {
79 if let Some((raw_symbols, raw_edges)) = extract(lang_str, source) {
80 let mut ids: Vec<i64> = Vec::with_capacity(raw_symbols.len());
83 for rs in &raw_symbols {
84 tx.execute(
85 "INSERT INTO graph_symbols (file, name, kind, start_line, end_line, signature, container) \
86 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
87 rusqlite::params![
88 path,
89 rs.name,
90 rs.kind.as_str(),
91 rs.start_line,
92 rs.end_line,
93 rs.signature,
94 rs.container,
95 ],
96 )?;
97 ids.push(tx.last_insert_rowid());
98 }
99
100 let (_, edges) = resolve_file(path, raw_symbols, raw_edges, |i| ids[i]);
101
102 for edge in &edges {
103 tx.execute(
104 "INSERT INTO graph_edges (src_symbol, dst_symbol, dst_name, kind) \
105 VALUES (?1, ?2, ?3, ?4)",
106 rusqlite::params![edge.src, edge.dst, edge.dst_name, edge.kind.as_str(),],
107 )?;
108 }
109 }
110 }
111
112 let now = std::time::SystemTime::now()
113 .duration_since(std::time::UNIX_EPOCH)
114 .map(|d| d.as_secs() as i64)
115 .unwrap_or(0);
116
117 tx.execute(
118 "INSERT INTO graph_files (path, lang, content_hash, mtime, indexed_at)
119 VALUES (?1, ?2, ?3, ?4, ?5)
120 ON CONFLICT(path) DO UPDATE SET
121 lang = excluded.lang,
122 content_hash = excluded.content_hash,
123 mtime = excluded.mtime,
124 indexed_at = excluded.indexed_at",
125 rusqlite::params![path, lang.unwrap_or(""), hash, mtime, now],
126 )?;
127
128 tx.commit()
129 }
130
131 pub fn neighborhood(&self, symbol_name: &str) -> Option<Neighborhood> {
137 self.neighborhood_all(symbol_name).into_iter().next()
138 }
139
140 pub fn neighborhood_all(&self, symbol_name: &str) -> Vec<Neighborhood> {
145 let defs: Vec<(i64, String, u32, u32)> = self
147 .conn
148 .prepare(
149 "SELECT id, file, start_line, COALESCE(end_line, start_line) \
150 FROM graph_symbols WHERE name = ?1 ORDER BY file, start_line",
151 )
152 .and_then(|mut stmt| {
153 stmt.query_map([symbol_name], |row| {
154 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
155 })
156 .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
157 })
158 .unwrap_or_default();
159
160 defs.into_iter()
161 .map(|(sym_id, file, start_line, end_line)| {
162 self.neighborhood_for(symbol_name, sym_id, file, start_line, end_line)
163 })
164 .collect()
165 }
166
167 fn neighborhood_for(
169 &self,
170 symbol_name: &str,
171 sym_id: i64,
172 file: String,
173 start_line: u32,
174 end_line: u32,
175 ) -> Neighborhood {
176 let definition = SymbolRef {
177 name: symbol_name.to_string(),
178 file: file.clone(),
179 line: start_line,
180 end_line,
181 };
182
183 let callers = self
185 .conn
186 .prepare(
187 "SELECT s.name, s.file, s.start_line, COALESCE(s.end_line, s.start_line)
188 FROM graph_edges e
189 JOIN graph_symbols s ON s.id = e.src_symbol
190 WHERE e.dst_symbol = ?1 AND e.kind = 'calls'",
191 )
192 .and_then(|mut stmt| {
193 stmt.query_map([sym_id], |row| {
194 Ok(SymbolRef {
195 name: row.get(0)?,
196 file: row.get(1)?,
197 line: row.get(2)?,
198 end_line: row.get(3)?,
199 })
200 })
201 .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
202 })
203 .unwrap_or_default();
204
205 let callees = self
207 .conn
208 .prepare(
209 "SELECT s.name, s.file, s.start_line, COALESCE(s.end_line, s.start_line)
210 FROM graph_edges e
211 JOIN graph_symbols s ON s.id = e.dst_symbol
212 WHERE e.src_symbol = ?1 AND e.kind = 'calls'",
213 )
214 .and_then(|mut stmt| {
215 stmt.query_map([sym_id], |row| {
216 Ok(SymbolRef {
217 name: row.get(0)?,
218 file: row.get(1)?,
219 line: row.get(2)?,
220 end_line: row.get(3)?,
221 })
222 })
223 .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
224 })
225 .unwrap_or_default();
226
227 let imports = self
230 .conn
231 .prepare(
232 "SELECT COALESCE(s.name, e.dst_name), COALESCE(s.file, ''), \
233 COALESCE(s.start_line, 0), COALESCE(s.end_line, s.start_line, 0)
234 FROM graph_edges e
235 LEFT JOIN graph_symbols s ON s.id = e.dst_symbol
236 WHERE e.src_symbol = ?1 AND e.kind = 'imports'",
237 )
238 .and_then(|mut stmt| {
239 stmt.query_map([sym_id], |row| {
240 Ok(SymbolRef {
241 name: row.get(0)?,
242 file: row.get(1)?,
243 line: row.get(2)?,
244 end_line: row.get(3)?,
245 })
246 })
247 .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
248 })
249 .unwrap_or_default();
250
251 let stale = {
252 let abs = self.root.join(&definition.file);
253 match std::fs::read_to_string(&abs) {
254 Ok(contents) => {
255 let cur = Self::hash_of(&contents);
256 let stored: Option<String> = self
257 .conn
258 .query_row(
259 "SELECT content_hash FROM graph_files WHERE path = ?1",
260 [definition.file.as_str()],
261 |r| r.get(0),
262 )
263 .ok();
264 stored.map(|s| s != cur).unwrap_or(false)
265 }
266 Err(_) => false,
267 }
268 };
269
270 Neighborhood {
271 definition,
272 callers,
273 callees,
274 imports,
275 stale,
276 }
277 }
278
279 pub fn symbol_names(&self) -> Vec<String> {
281 self.conn
282 .prepare("SELECT DISTINCT name FROM graph_symbols")
283 .and_then(|mut stmt| {
284 stmt.query_map([], |row| row.get(0))
285 .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
286 })
287 .unwrap_or_default()
288 }
289
290 pub fn resolve_in_file(&self, file: &str, name: &str) -> Option<SymbolRef> {
292 self.conn
293 .query_row(
294 "SELECT name, file, start_line, COALESCE(end_line, start_line) \
295 FROM graph_symbols WHERE file = ?1 AND name = ?2 LIMIT 1",
296 rusqlite::params![file, name],
297 |row| {
298 Ok(SymbolRef {
299 name: row.get(0)?,
300 file: row.get(1)?,
301 line: row.get(2)?,
302 end_line: row.get(3)?,
303 })
304 },
305 )
306 .ok()
307 }
308
309 pub fn stats(&self) -> (usize, usize, usize) {
311 let count = |sql: &str| -> usize {
312 self.conn
313 .query_row(sql, [], |row| row.get::<_, i64>(0))
314 .unwrap_or(0) as usize
315 };
316 (
317 count("SELECT COUNT(*) FROM graph_files"),
318 count("SELECT COUNT(*) FROM graph_symbols"),
319 count("SELECT COUNT(*) FROM graph_edges"),
320 )
321 }
322
323 pub fn symbols_in(&self, path: &str) -> Vec<Symbol> {
325 self.conn
326 .prepare(
327 "SELECT id, file, name, kind, start_line, end_line, signature, container
328 FROM graph_symbols WHERE file = ?1",
329 )
330 .and_then(|mut stmt| {
331 stmt.query_map([path], |row| {
332 let kind_str: String = row.get(3)?;
333 let kind = SymbolKind::from_str(&kind_str).unwrap_or(SymbolKind::Function);
334 Ok(Symbol {
335 id: row.get(0)?,
336 file: row.get(1)?,
337 name: row.get(2)?,
338 kind,
339 start_line: row.get(4)?,
340 end_line: row.get(5)?,
341 signature: row.get(6)?,
342 container: row.get(7)?,
343 })
344 })
345 .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
346 })
347 .unwrap_or_default()
348 }
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354
355 fn mem_store() -> Store {
356 let conn = rusqlite::Connection::open_in_memory().unwrap();
357 crate::schema::init_graph_schema(&conn).unwrap();
358 Store {
359 conn,
360 root: std::env::temp_dir(),
361 }
362 }
363
364 #[test]
365 fn index_then_query_neighborhood() {
366 let store = mem_store();
367 let src = "fn helper() {}\nfn main() { helper(); }\n";
368 store.index_file("src/main.rs", src, 0).unwrap();
369
370 let nb = store.neighborhood("helper").expect("helper indexed");
371 assert_eq!(nb.definition.name, "helper");
372 assert!(nb.callers.iter().any(|c| c.name == "main"));
373 assert!(!nb.stale);
374 }
375
376 #[test]
377 fn is_current_tracks_content_hash() {
378 let store = mem_store();
379 let src = "fn a() {}\n";
380 store.index_file("a.rs", src, 0).unwrap();
381 assert!(store.is_current("a.rs", src));
382 assert!(!store.is_current("a.rs", "fn a() {}\nfn b() {}\n"));
383 }
384
385 #[test]
386 fn reindex_replaces_prior_symbols() {
387 let store = mem_store();
388 store.index_file("a.rs", "fn a() {}\n", 0).unwrap();
389 store.index_file("a.rs", "fn c() {}\n", 1).unwrap();
390 assert!(store.neighborhood("a").is_none());
391 assert!(store.neighborhood("c").is_some());
392 }
393
394 #[test]
395 fn reindex_handles_path_with_quote() {
396 let store = mem_store();
397 let path = "weird'name.rs";
398 store.index_file(path, "fn first_sym() {}\n", 0).unwrap();
399 store.index_file(path, "fn second_sym() {}\n", 1).unwrap();
400 assert!(
401 store.neighborhood("first_sym").is_none(),
402 "old symbol must be gone after reindex"
403 );
404 assert!(
405 store.neighborhood("second_sym").is_some(),
406 "new symbol must exist after reindex"
407 );
408 }
409
410 #[test]
422 fn resolve_in_file_disambiguates_same_name_across_files() {
423 let store = mem_store();
424 store
425 .index_file(
426 "assembler.rs",
427 "fn build() {}\nfn assemble() { build(); }\n",
428 0,
429 )
430 .unwrap();
431 store
432 .index_file(
433 "blackboard.rs",
434 "fn build() {}\nfn open() { build(); }\n",
435 0,
436 )
437 .unwrap();
438
439 let in_assembler = store
440 .resolve_in_file("assembler.rs", "build")
441 .expect("build exists in assembler.rs");
442 assert_eq!(in_assembler.file, "assembler.rs");
443
444 let in_blackboard = store
445 .resolve_in_file("blackboard.rs", "build")
446 .expect("build exists in blackboard.rs");
447 assert_eq!(in_blackboard.file, "blackboard.rs");
448 }
449
450 #[test]
455 fn neighborhood_surfaces_all_same_name_definitions() {
456 let store = mem_store();
457 store
458 .index_file("assembler.rs", "fn build() {}\n", 0)
459 .unwrap();
460 store
461 .index_file("blackboard.rs", "fn build() {}\n", 0)
462 .unwrap();
463
464 let all = store.neighborhood_all("build");
465 let mut files: Vec<&str> = all.iter().map(|n| n.definition.file.as_str()).collect();
466 files.sort_unstable();
467 assert_eq!(
468 files,
469 vec!["assembler.rs", "blackboard.rs"],
470 "neighborhood_all must surface BOTH build definitions, not collapse to one"
471 );
472
473 assert_eq!(all.first().unwrap().definition.file, "assembler.rs");
475
476 assert_eq!(
478 store.neighborhood("build").unwrap().definition.file,
479 "assembler.rs"
480 );
481 }
482
483 #[test]
505 fn same_name_symbols_in_one_file_get_distinct_ids() {
506 let store = mem_store();
507 let src = "\
508fn build() {}
509mod second { pub fn build() {} }
510";
511 store.index_file("dup.rs", src, 0).unwrap();
512 let builds: Vec<_> = store
513 .symbols_in("dup.rs")
514 .into_iter()
515 .filter(|s| s.name == "build")
516 .collect();
517 assert_eq!(builds.len(), 2, "both `build` symbols indexed");
519 assert_ne!(builds[0].id, builds[1].id, "distinct rows get distinct ids");
520 }
521
522 #[test]
523 fn same_name_defs_in_one_file_get_correct_edge_attribution() {
524 let store = mem_store();
525 let src = "\
527fn build() {}
528fn caller_one() { build(); }
529mod second { pub fn build() {} pub fn caller_two() { build(); } }
530";
531 store.index_file("dup.rs", src, 0).unwrap();
532
533 let builds: Vec<_> = store
534 .symbols_in("dup.rs")
535 .into_iter()
536 .filter(|s| s.name == "build")
537 .collect();
538 assert_eq!(builds.len(), 2);
539
540 let nbs = store.neighborhood_all("build");
544 let caller_counts: Vec<usize> = nbs.iter().map(|n| n.callers.len()).collect();
545 assert!(
546 caller_counts.iter().all(|&c| c == 1),
547 "each same-file `build` must own exactly its caller, got caller counts {caller_counts:?} \
548 (last-write-wins mis-attribution)"
549 );
550 }
551
552 #[test]
564 fn method_carries_its_impl_container() {
565 let store = mem_store();
566 let src = "\
568struct ContextAssembler;
569impl ContextAssembler {
570 fn build(&self) {}
571}
572";
573 store.index_file("assembler.rs", src, 0).unwrap();
574
575 let build = store
576 .symbols_in("assembler.rs")
577 .into_iter()
578 .find(|s| s.name == "build")
579 .expect("build method indexed");
580
581 assert_eq!(
583 build.container.as_deref(),
584 Some("ContextAssembler"),
585 "method `build` must record its container `ContextAssembler`"
586 );
587 assert!(
588 build.signature.as_deref().unwrap_or("").contains("build"),
589 "placeholder: strengthen to assert container == \"ContextAssembler\" once \
590 the container column is added"
591 );
592 }
593
594 #[test]
595 fn neighborhood_reports_stale_when_file_changed_on_disk() {
596 let dir = std::env::temp_dir().join(format!("rinne-stale-{}", std::process::id()));
597 std::fs::create_dir_all(&dir).unwrap();
598 let file = dir.join("m.rs");
599 std::fs::write(&file, "fn helper() {}\nfn main() { helper(); }\n").unwrap();
600
601 let store = Store::open(&dir.join("state.db"), &dir).unwrap();
602 let src = std::fs::read_to_string(&file).unwrap();
603 store.index_file("m.rs", &src, 0).unwrap();
604
605 assert!(!store.neighborhood("helper").unwrap().stale);
607
608 std::fs::write(&file, "fn helper() {}\nfn main() { helper(); helper(); }\n").unwrap();
610 assert!(
611 store.neighborhood("helper").unwrap().stale,
612 "must report stale after on-disk edit"
613 );
614
615 let _ = std::fs::remove_dir_all(&dir);
616 }
617}