Skip to main content

graphd_engine/
journal_types.rs

1//! Minimal journal types shared between graphd-engine and the graphd binary.
2//!
3//! The full journal writer/reader lives in the graphd binary. This module
4//! provides only the types needed by the engine for mutation detection and
5//! optional write-ahead logging.
6
7/// A pending journal entry (query + params) to be written.
8pub struct PendingEntry {
9    pub query: String,
10    pub params: Option<serde_json::Value>,
11}
12
13/// Commands sent to the journal writer thread.
14pub enum JournalCommand {
15    Write(PendingEntry),
16    Flush(std::sync::mpsc::SyncSender<()>),
17    Shutdown,
18}
19
20/// Channel sender for journal commands.
21pub type JournalSender = std::sync::mpsc::Sender<JournalCommand>;
22
23// ─── Mutation detection ───
24
25const MUTATION_KEYWORDS: &[&str] = &[
26    "CREATE", "MERGE", "DELETE", "DROP", "ALTER", "COPY", "SET",
27    "INSTALL", "UNINSTALL", "IMPORT", "ATTACH", "DETACH",
28];
29
30/// Returns true if the query likely contains a mutation keyword.
31/// Over-journaling reads is harmless; missing mutations would be catastrophic.
32pub fn is_mutation(query: &str) -> bool {
33    let upper = query.to_ascii_uppercase();
34    let bytes = upper.as_bytes();
35    for keyword in MUTATION_KEYWORDS {
36        let kw_bytes = keyword.as_bytes();
37        let kw_len = kw_bytes.len();
38        let mut i = 0;
39        while i + kw_len <= bytes.len() {
40            if &bytes[i..i + kw_len] == kw_bytes {
41                let before_ok = i == 0 || !bytes[i - 1].is_ascii_alphanumeric();
42                let after_ok =
43                    i + kw_len >= bytes.len() || !bytes[i + kw_len].is_ascii_alphanumeric();
44                if before_ok && after_ok {
45                    return true;
46                }
47            }
48            i += 1;
49        }
50    }
51    false
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn test_mutation_keywords() {
60        assert!(is_mutation("CREATE (:Person {name: 'Alice'})"));
61        assert!(is_mutation("MERGE (n:Person)"));
62        assert!(is_mutation("DELETE n"));
63        assert!(is_mutation("DROP TABLE foo"));
64        assert!(is_mutation("ALTER TABLE foo"));
65        assert!(is_mutation("SET n.name = 'Bob'"));
66        assert!(is_mutation("COPY FROM 'file.csv'"));
67    }
68
69    #[test]
70    fn test_non_mutations() {
71        assert!(!is_mutation("MATCH (n) RETURN n"));
72        assert!(!is_mutation("RETURN 1 AS n"));
73        assert!(!is_mutation("EXPLAIN MATCH (n) RETURN n"));
74    }
75
76    #[test]
77    fn test_word_boundary() {
78        // "CREATED" should not match "CREATE"
79        assert!(!is_mutation("MATCH (n:CREATED) RETURN n"));
80        // But "CREATE " should
81        assert!(is_mutation("CREATE NODE TABLE Foo(id INT64, PRIMARY KEY(id))"));
82    }
83
84    // ─── New mutation keywords (INSTALL, UNINSTALL, IMPORT, ATTACH, DETACH) ───
85
86    #[test]
87    fn test_is_mutation_install() {
88        assert!(is_mutation("INSTALL extension_name"));
89        assert!(is_mutation("install myext"));
90        assert!(is_mutation("Install SomeExtension"));
91    }
92
93    #[test]
94    fn test_is_mutation_uninstall() {
95        assert!(is_mutation("UNINSTALL extension_name"));
96        assert!(is_mutation("uninstall myext"));
97    }
98
99    #[test]
100    fn test_is_mutation_import() {
101        assert!(is_mutation("IMPORT DATABASE '/path/to/db'"));
102        assert!(is_mutation("import database '/tmp/backup'"));
103    }
104
105    #[test]
106    fn test_is_mutation_attach() {
107        assert!(is_mutation("ATTACH DATABASE '/path/to/other.db'"));
108        assert!(is_mutation("attach database '/tmp/other'"));
109    }
110
111    #[test]
112    fn test_is_mutation_detach() {
113        assert!(is_mutation("DETACH DATABASE other_db"));
114        assert!(is_mutation("detach database mydb"));
115    }
116
117    #[test]
118    fn test_uninstall_not_caught_by_install_boundary() {
119        // UNINSTALL must be caught by its own keyword, not by INSTALL
120        // (word boundary: 'N' before INSTALL is alphanumeric → INSTALL alone won't match)
121        assert!(is_mutation("UNINSTALL ext"));
122    }
123
124    #[test]
125    fn test_not_mutation_new_keywords_substring() {
126        // Suffixed forms should not match
127        assert!(!is_mutation("RETURN 'INSTALLED'"));
128        assert!(!is_mutation("RETURN 'IMPORTING'"));
129        assert!(!is_mutation("RETURN 'ATTACHED'"));
130        assert!(!is_mutation("RETURN 'DETACHED'"));
131        assert!(!is_mutation("RETURN 'DETACHING'"));
132    }
133
134    #[test]
135    fn test_not_mutation_new_keywords_prefixed() {
136        // Prefixed forms should not match (alpha before keyword)
137        assert!(!is_mutation("RETURN 'REIMPORT'"));
138        assert!(!is_mutation("RETURN 'REATTACH'"));
139    }
140
141    // ─── Comprehensive replica safety: every ladybug mutation type ───
142
143    /// This test documents every mutation type that ladybug supports
144    /// and verifies is_mutation catches all of them. If ladybug adds
145    /// new mutation types, add them here.
146    #[test]
147    fn test_replica_safety_all_mutation_types() {
148        // ── Data modification clauses ──
149        assert!(is_mutation("CREATE (:Person {name: 'Alice'})"));
150        assert!(is_mutation("CREATE NODE TABLE Person(name STRING, PRIMARY KEY(name))"));
151        assert!(is_mutation("CREATE REL TABLE KNOWS(FROM Person TO Person)"));
152        assert!(is_mutation("MATCH (a:Person), (b:Person) CREATE (a)-[:KNOWS]->(b)"));
153        assert!(is_mutation("MERGE (n:Person {name: 'Bob'})"));
154        assert!(is_mutation("MATCH (n:Person) SET n.age = 30"));
155        assert!(is_mutation("MATCH (n:Person) DELETE n"));
156        assert!(is_mutation("MATCH (n:Person) DETACH DELETE n"));
157
158        // ── DDL ──
159        assert!(is_mutation("DROP TABLE Person"));
160        assert!(is_mutation("DROP TABLE IF EXISTS Person"));
161        assert!(is_mutation("ALTER TABLE Person ADD age INT64"));
162        assert!(is_mutation("ALTER TABLE Person DROP col"));
163        assert!(is_mutation("ALTER TABLE Person RENAME TO People"));
164        assert!(is_mutation("CREATE SEQUENCE my_seq"));
165        assert!(is_mutation("DROP SEQUENCE my_seq"));
166        assert!(is_mutation("CREATE TYPE my_type AS STRUCT(x INT64)"));
167        assert!(is_mutation("CREATE MACRO my_func(x) AS x + 1"));
168        assert!(is_mutation("DROP MACRO my_func"));
169        assert!(is_mutation("CREATE GRAPH my_graph"));
170        assert!(is_mutation("DROP GRAPH my_graph"));
171
172        // ── Data import/export ──
173        assert!(is_mutation("COPY Person FROM 'people.csv'"));
174        assert!(is_mutation("COPY Person FROM 'people.parquet'"));
175
176        // ── Extension management ──
177        assert!(is_mutation("INSTALL httpfs"));
178        assert!(is_mutation("UNINSTALL httpfs"));
179
180        // ── Database management ──
181        assert!(is_mutation("IMPORT DATABASE '/path/to/export'"));
182        assert!(is_mutation("ATTACH DATABASE '/other/db' AS other"));
183        assert!(is_mutation("DETACH DATABASE other"));
184
185        // ── Read-only operations (must NOT trigger) ──
186        assert!(!is_mutation("MATCH (n:Person) RETURN n"));
187        assert!(!is_mutation("MATCH (n:Person) RETURN n.name ORDER BY n.name"));
188        assert!(!is_mutation("MATCH (n:Person) RETURN count(n)"));
189        assert!(!is_mutation("RETURN 1"));
190        assert!(!is_mutation("RETURN 'hello world'"));
191        assert!(!is_mutation("UNWIND [1, 2, 3] AS x RETURN x"));
192        assert!(!is_mutation("CALL current_setting('threads')"));
193        assert!(!is_mutation("EXPLAIN MATCH (n) RETURN n"));
194        assert!(!is_mutation("EXPORT DATABASE '/path/to/export'"));
195        assert!(!is_mutation("LOAD EXTENSION httpfs"));
196        assert!(!is_mutation("USE DATABASE other"));
197        assert!(!is_mutation("USE GRAPH my_graph"));
198    }
199}