Skip to main content

rinne_graph/
schema.rs

1//! SQLite DDL for the code graph tables, colocated with the blackboard state.
2
3use rusqlite::Connection;
4
5/// Version of the graph schema *and* the extractor's output shape.
6///
7/// Bump this whenever a change would make previously-indexed rows stale even
8/// though the source files are unchanged — e.g. a new column, a change to how a
9/// field is extracted, or a new edge kind. On open, a graph whose stored version
10/// differs is wiped and rebuilt automatically (see [`migrate_graph_if_stale`]),
11/// so an upgraded binary re-extracts once with no manual `rm .rinne/state.db`.
12///
13/// History:
14///   1 — initial versioned schema; adds `container` column + container extraction
15///       and scope-aware edge resolution (previously unversioned, no `container`).
16pub const GRAPH_SCHEMA_VERSION: i64 = 1;
17
18/// The graph tables. Kept as a list so migration can drop exactly these without
19/// touching sibling tables (run state, budget ledger) that share the same DB.
20const GRAPH_TABLES: &[&str] = &["graph_edges", "graph_symbols", "graph_files"];
21
22/// The SQLite key under which we stash the graph schema version. We can't use the
23/// DB-wide `PRAGMA user_version` because the graph shares `state.db` with the
24/// blackboard, so a small dedicated table scopes the version to the graph.
25const VERSION_TABLE: &str = "graph_schema_version";
26
27/// If the stored graph schema version differs from [`GRAPH_SCHEMA_VERSION`], drop
28/// the graph tables so [`init_graph_schema`] recreates them empty and the next
29/// index pass re-extracts every file. No-op when the version already matches
30/// (the common path) or on a brand-new DB (version 0 → treated as "needs build",
31/// but the tables don't exist yet so the drops are harmless).
32pub fn migrate_graph_if_stale(conn: &Connection) -> rusqlite::Result<()> {
33    conn.execute_batch(&format!(
34        "CREATE TABLE IF NOT EXISTS {VERSION_TABLE} (version INTEGER NOT NULL);"
35    ))?;
36
37    let stored: Option<i64> = conn
38        .query_row(
39            &format!("SELECT version FROM {VERSION_TABLE} LIMIT 1"),
40            [],
41            |r| r.get(0),
42        )
43        .ok();
44
45    if stored == Some(GRAPH_SCHEMA_VERSION) {
46        return Ok(()); // up to date — nothing to do
47    }
48
49    // Stale or absent: drop graph tables (only these; siblings untouched) and
50    // stamp the current version. Recreation happens in init_graph_schema.
51    for table in GRAPH_TABLES {
52        conn.execute_batch(&format!("DROP TABLE IF EXISTS {table};"))?;
53    }
54    conn.execute(&format!("DELETE FROM {VERSION_TABLE}"), [])?;
55    conn.execute(
56        &format!("INSERT INTO {VERSION_TABLE} (version) VALUES (?1)"),
57        [GRAPH_SCHEMA_VERSION],
58    )?;
59    Ok(())
60}
61
62pub fn init_graph_schema(conn: &Connection) -> rusqlite::Result<()> {
63    conn.execute_batch(
64        r#"
65        CREATE TABLE IF NOT EXISTS graph_files (
66            path         TEXT PRIMARY KEY,
67            lang         TEXT NOT NULL,
68            content_hash TEXT NOT NULL,
69            mtime        INTEGER NOT NULL,
70            indexed_at   INTEGER NOT NULL
71        );
72
73        CREATE TABLE IF NOT EXISTS graph_symbols (
74            id         INTEGER PRIMARY KEY AUTOINCREMENT,
75            file       TEXT NOT NULL,
76            name       TEXT NOT NULL,
77            kind       TEXT NOT NULL,
78            start_line INTEGER NOT NULL,
79            end_line   INTEGER NOT NULL,
80            signature  TEXT,
81            -- Enclosing type/class/trait for a method (e.g. "ContextAssembler" for
82            -- ContextAssembler::build), NULL for free functions. Gives same-file
83            -- same-name defs a qualified identity so they can be disambiguated.
84            container  TEXT
85        );
86
87        CREATE TABLE IF NOT EXISTS graph_edges (
88            src_symbol INTEGER,
89            dst_symbol INTEGER,
90            dst_name   TEXT NOT NULL,
91            kind       TEXT NOT NULL
92        );
93
94        CREATE INDEX IF NOT EXISTS idx_symbols_name ON graph_symbols(name);
95        CREATE INDEX IF NOT EXISTS idx_symbols_file ON graph_symbols(file);
96        CREATE INDEX IF NOT EXISTS idx_edges_src ON graph_edges(src_symbol);
97        CREATE INDEX IF NOT EXISTS idx_edges_dst ON graph_edges(dst_symbol);
98        CREATE INDEX IF NOT EXISTS idx_edges_dstname ON graph_edges(dst_name);
99        "#,
100    )
101    // Note: schema changes that must invalidate existing rows are handled by
102    // `migrate_graph_if_stale` (version-gated table wipe), not per-column ALTERs.
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    #[test]
110    fn init_is_idempotent_and_creates_tables() {
111        let conn = Connection::open_in_memory().unwrap();
112        init_graph_schema(&conn).unwrap();
113        init_graph_schema(&conn).unwrap(); // second call must not error
114
115        let count: i64 = conn
116            .query_row(
117                "SELECT count(*) FROM sqlite_master WHERE type='table' \
118                 AND name IN ('graph_files','graph_symbols','graph_edges')",
119                [],
120                |r| r.get(0),
121            )
122            .unwrap();
123        assert_eq!(count, 3);
124    }
125
126    #[test]
127    fn stale_version_wipes_graph_tables_but_keeps_siblings() {
128        let conn = Connection::open_in_memory().unwrap();
129
130        // Simulate an OLD graph: a sibling (non-graph) table with data that must
131        // survive, plus a graph table stamped with a stale version.
132        conn.execute_batch(
133            "CREATE TABLE run_meta (k TEXT, v TEXT);
134             INSERT INTO run_meta VALUES ('run', 'keep-me');",
135        )
136        .unwrap();
137        migrate_graph_if_stale(&conn).unwrap();
138        init_graph_schema(&conn).unwrap();
139        conn.execute(
140            "INSERT INTO graph_symbols (file, name, kind, start_line, end_line) \
141             VALUES ('a.rs','old','function',1,1)",
142            [],
143        )
144        .unwrap();
145
146        // Force a version mismatch as if the binary was upgraded.
147        conn.execute(
148            &format!("UPDATE {VERSION_TABLE} SET version = ?1"),
149            [GRAPH_SCHEMA_VERSION - 1],
150        )
151        .unwrap();
152
153        // Reopen path: migrate should wipe graph tables, keep run_meta.
154        migrate_graph_if_stale(&conn).unwrap();
155        init_graph_schema(&conn).unwrap();
156
157        let graph_rows: i64 = conn
158            .query_row("SELECT COUNT(*) FROM graph_symbols", [], |r| r.get(0))
159            .unwrap();
160        assert_eq!(graph_rows, 0, "stale graph rows must be wiped");
161
162        let sibling: String = conn
163            .query_row("SELECT v FROM run_meta WHERE k='run'", [], |r| r.get(0))
164            .unwrap();
165        assert_eq!(sibling, "keep-me", "non-graph tables must survive the wipe");
166
167        let ver: i64 = conn
168            .query_row(&format!("SELECT version FROM {VERSION_TABLE}"), [], |r| {
169                r.get(0)
170            })
171            .unwrap();
172        assert_eq!(ver, GRAPH_SCHEMA_VERSION, "version stamped to current");
173    }
174
175    #[test]
176    fn matching_version_is_a_noop() {
177        let conn = Connection::open_in_memory().unwrap();
178        migrate_graph_if_stale(&conn).unwrap();
179        init_graph_schema(&conn).unwrap();
180        conn.execute(
181            "INSERT INTO graph_symbols (file, name, kind, start_line, end_line) \
182             VALUES ('a.rs','keep','function',1,1)",
183            [],
184        )
185        .unwrap();
186
187        // Second open with the SAME version must NOT wipe existing rows.
188        migrate_graph_if_stale(&conn).unwrap();
189        init_graph_schema(&conn).unwrap();
190
191        let rows: i64 = conn
192            .query_row("SELECT COUNT(*) FROM graph_symbols", [], |r| r.get(0))
193            .unwrap();
194        assert_eq!(rows, 1, "matching version must preserve indexed rows");
195    }
196}