Skip to main content

graph_loom/gql/
query_interface.rs

1use anyhow::{anyhow, Result};
2use std::collections::HashMap;
3use std::fs::{create_dir_all, OpenOptions};
4use std::io::Write;
5use std::path::PathBuf;
6use std::sync::Mutex;
7use time::{macros::format_description, OffsetDateTime};
8use uuid::Uuid;
9use rayon::prelude::*;
10
11use crate::graph_utils::graph::{GraphDatabase, NodeId};
12use crate::semantic::embeddings::NodeEmbeddingIndex;
13
14/// Global embedding cache for reusing computed embeddings across queries
15#[allow(dead_code)]
16static EMBEDDING_CACHE: once_cell::sync::Lazy<Mutex<Option<(NodeEmbeddingIndex, usize)>>> = 
17    once_cell::sync::Lazy::new(|| Mutex::new(None));
18
19/// Set the global embedding cache
20#[allow(dead_code)]
21pub fn set_embedding_cache(index: NodeEmbeddingIndex, node_count: usize) {
22    if let Ok(mut cache) = EMBEDDING_CACHE.lock() {
23        *cache = Some((index, node_count));
24    }
25}
26
27/// Get a reference to the embedding cache (returns None if not initialized)
28#[allow(dead_code)]
29pub fn get_embedding_cache() -> Option<(NodeEmbeddingIndex, usize)> {
30    if let Ok(cache) = EMBEDDING_CACHE.lock() {
31        cache.clone()
32    } else {
33        None
34    }
35}
36
37/// Clear the embedding cache
38#[allow(dead_code)]
39pub fn clear_embedding_cache() {
40    if let Ok(mut cache) = EMBEDDING_CACHE.lock() {
41        *cache = None;
42    }
43}
44use crate::graph_utils::algorithms::{pagerank, betweenness_centrality, shortest_path, astar_path, all_paths};
45use crate::graph_utils::temporal::{get_timeline, get_timestamp_range, nodes_in_range, graph_at_time};
46use super::cypher_spec::{execute_cypher, execute_cypher_with_params};
47
48#[derive(Debug, Clone)]
49pub enum QueryResultRow {
50    Node { id: NodeId, label: String, metadata: HashMap<String, String> },
51    Relationship { id: Uuid, from: NodeId, to: NodeId, label: String, metadata: HashMap<String, String> },
52    #[allow(dead_code)]
53    Info(String),
54}
55
56#[derive(Debug, Default, Clone)]
57pub struct QueryOutcome {
58    pub rows: Vec<QueryResultRow>,
59    pub affected_nodes: usize,
60    pub affected_relationships: usize,
61    pub mutated: bool,
62}
63
64fn log_path_for_now() -> PathBuf {
65    let base = PathBuf::from("assets/logs");
66    let now = OffsetDateTime::now_utc();
67    let fmt = format_description!("[year][month][day]");
68    let date = now.format(&fmt).unwrap_or_else(|_| "unknown".into());
69    base.join(format!("queries_{}.log", date))
70}
71
72fn log_query(query: &str, outcome: &Result<QueryOutcome>) {
73    let _ = create_dir_all("assets/logs");
74    let mut path = log_path_for_now();
75    // ensure parent exists
76    if let Some(parent) = path.parent() { let _ = create_dir_all(parent); }
77    let now = OffsetDateTime::now_utc();
78    let ts_fmt = format_description!("[year]-[month]-[day] [hour]:[minute]:[second]");
79    let ts = now.format(&ts_fmt).unwrap_or_else(|_| "".into());
80    let status = match outcome {
81        Ok(o) => format!("OK mutated={} nodes={} rels={}", o.mutated, o.affected_nodes, o.affected_relationships),
82        Err(e) => format!("ERR {}", e),
83    };
84    let line = format!("{} | {}\n{}\n\n", ts, status, query.trim());
85    if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(&mut path) {
86        let _ = file.write_all(line.as_bytes());
87    }
88}
89
90fn _split_statements(input: &str) -> Vec<String> {
91    // Primary split by ';'. We avoid splitting if the semicolon is inside quotes or braces.
92    let mut statements = Vec::new();
93    let mut current = String::new();
94    let mut in_quote = None;
95    let mut brace_depth: i32 = 0;
96    
97    let chars: Vec<char> = input.chars().collect();
98    let mut i = 0;
99    while i < chars.len() {
100        let c = chars[i];
101        match c {
102            '"' | '\'' => {
103                if in_quote == Some(c) {
104                    in_quote = None;
105                } else if in_quote.is_none() {
106                    in_quote = Some(c);
107                }
108                current.push(c);
109            }
110            '{' | '(' | '[' if in_quote.is_none() => {
111                brace_depth += 1;
112                current.push(c);
113            }
114            '}' | ')' | ']' if in_quote.is_none() => {
115                brace_depth = brace_depth.saturating_sub(1);
116                current.push(c);
117            }
118            ';' if in_quote.is_none() && brace_depth == 0 => {
119                let s = current.trim().to_string();
120                if !s.is_empty() {
121                    statements.push(s);
122                }
123                current.clear();
124            }
125            _ => {
126                current.push(c);
127            }
128        }
129        i += 1;
130    }
131    let s = current.trim().to_string();
132    if !s.is_empty() {
133        statements.push(s);
134    }
135    statements
136}
137
138/// Batch consecutive CREATE statements into single combined statements.
139/// This allows variable bindings from one CREATE to be available in subsequent CREATEs.
140/// e.g., "CREATE (p1:Person)" followed by "CREATE (p1)-[:REL]->(c1)" becomes
141/// "CREATE (p1:Person) CREATE (p1)-[:REL]->(c1)" so p1 is bound when the relationship is created.
142fn batch_consecutive_creates(statements: &[String]) -> Vec<String> {
143    let mut result: Vec<String> = Vec::new();
144    let mut create_batch: Vec<String> = Vec::new();
145    
146    for stmt in statements {
147        let trimmed = stmt.trim();
148        let upper = trimmed.to_uppercase();
149        
150        // Check if this is a Cypher-style CREATE (not legacy CREATE NODE/REL)
151        let is_cypher_create = upper.starts_with("CREATE") 
152            && trimmed.len() > 6 
153            && trimmed[6..].trim_start().starts_with('(');
154        
155        if is_cypher_create {
156            create_batch.push(trimmed.to_string());
157        } else {
158            // Flush any accumulated CREATE batch
159            if !create_batch.is_empty() {
160                // Join with newline so parser sees multiple CREATE clauses
161                result.push(create_batch.join("\n"));
162                create_batch.clear();
163            }
164            result.push(trimmed.to_string());
165        }
166    }
167    
168    // Flush remaining CREATE batch
169    if !create_batch.is_empty() {
170        result.push(create_batch.join("\n"));
171    }
172    
173    result
174}
175
176/// Extract label from a MATCH clause like "MATCH (n:Person)" -> Some("Person")
177fn extract_match_label(upper_query: &str) -> Option<String> {
178    // Look for pattern like "MATCH (var:Label)" or "MATCH (:Label)"
179    if let Some(match_idx) = upper_query.find("MATCH") {
180        let after_match = &upper_query[match_idx + 5..];
181        if let Some(paren_idx) = after_match.find('(') {
182            let after_paren = &after_match[paren_idx + 1..];
183            // Find the colon that indicates a label
184            if let Some(colon_idx) = after_paren.find(':') {
185                let after_colon = &after_paren[colon_idx + 1..];
186                // Extract label until ) or space or {
187                let label_end = after_colon.find(|c: char| c == ')' || c == ' ' || c == '{' || c == '-' || c == ']')
188                    .unwrap_or(after_colon.len());
189                let label = after_colon[..label_end].trim();
190                if !label.is_empty() {
191                    return Some(label.to_string());
192                }
193            }
194        }
195    }
196    None
197}
198
199pub fn execute_query(db: &mut GraphDatabase, query: &str) -> Result<QueryOutcome> {
200    // Normalize line endings: convert CRLF to LF and remove stray CR
201    let normalized = query.replace("\r\n", "\n").replace('\r', "\n");
202    let mut trimmed = normalized.trim();
203    
204    // Strip outer quotes if the entire query is wrapped in them (common from CLI)
205    if (trimmed.starts_with('"') && trimmed.ends_with('"')) || 
206       (trimmed.starts_with('\'') && trimmed.ends_with('\'')) {
207        if trimmed.len() >= 2 {
208            trimmed = &trimmed[1..trimmed.len()-1];
209            trimmed = trimmed.trim();
210        }
211    }
212    
213    if trimmed.is_empty() {
214        return Err(anyhow!("empty query"));
215    }
216
217    // We allow multiple statements separated by semicolons; execute sequentially
218    let mut outcome = QueryOutcome::default();
219    let mut any_mut = false;
220    let statements = _split_statements(trimmed);
221    
222    // Batch consecutive CREATE statements so variable bindings persist across them
223    // e.g., CREATE (p1:Person) followed by CREATE (p1)-[:REL]->(c1) needs p1 bound
224    let batched_statements = batch_consecutive_creates(&statements);
225    
226    for stmt in batched_statements {
227        let stmt = stmt.trim();
228        if stmt.is_empty() { continue; }
229        let upper = stmt.to_uppercase();
230        let res = if upper.starts_with("MATCH (") && upper.contains(" MERGE ") {
231            // Legacy minimal Cypher-style pairwise support (kept for compatibility)
232            exec_cypher_match_merge(db, stmt)
233        // If the statement appears to be OpenCypher, route to the Cypher engine.
234        // Detect by keywords and forms that are NOT the legacy custom commands.
235        } else if (upper.starts_with("MATCH") && !upper.contains("CALL ") && (stmt[5..].trim_start().starts_with('(') || stmt[5..].trim_start().starts_with("(") || (stmt[5..].trim_start().contains('.') && !stmt[5..].trim_start().starts_with("NODE ") && !stmt[5..].trim_start().starts_with("REL ")))) ||
236        // WITH is Cypher-only
237        upper.starts_with("WITH ") ||
238        // UNWIND is Cypher-only
239        upper.starts_with("UNWIND ") ||
240        // DETACH DELETE is Cypher-only
241        upper.starts_with("DETACH DELETE ") ||
242        // OPTIONAL MATCH with '(' or shorthand
243        (upper.starts_with("OPTIONAL MATCH ") && (stmt[15..].trim_start().starts_with('(') || (stmt[15..].trim_start().contains('.') && !stmt[15..].trim_start().starts_with("NODE ") && !stmt[15..].trim_start().starts_with("REL ")))) ||
244        // MERGE is Cypher-only
245        upper.starts_with("MERGE ") ||
246        // RETURN is Cypher-only
247        upper.starts_with("RETURN ") ||
248        // SET / REMOVE are Cypher-only
249        upper.starts_with("SET ") || upper.starts_with("REMOVE ") ||
250        // DELETE / DETACH DELETE are Cypher-only, but avoid legacy DELETE NODE/REL
251        (upper.starts_with("DELETE ") && !upper.starts_with("DELETE NODE ") && !upper.starts_with("DELETE REL ")) ||
252        upper.starts_with("DETACH DELETE ") ||
253        // CREATE with '(' pattern (avoid legacy CREATE NODE/REL)
254        (upper.starts_with("CREATE") && stmt[6..].trim_start().starts_with('(')) ||
255        // Catch-all for multi-clause queries (but NOT if it contains CALL - those need special handling)
256        (upper.contains("WITH ") && (upper.contains("MATCH ") || upper.contains("RETURN ")) && !upper.contains("CALL ")) ||
257        (upper.contains("UNWIND ") && upper.contains("WITH ") && !upper.contains("CALL ")) {
258            let rows = execute_cypher(db, stmt)?;
259            // conservatively mark mutated if statement contains mutating keywords
260            let mutated = upper.contains("CREATE")
261                || upper.contains("MERGE")
262                || upper.contains("SET ")
263                || upper.contains("REMOVE ")
264                || upper.contains("DELETE")
265                || upper.contains("DETACH DELETE");
266            Ok((rows, 0, 0, mutated))
267        } else if upper.starts_with("CREATE NODE ") {
268            exec_create_node(db, &stmt[12..])
269        } else if upper.starts_with("CREATE REL ") {
270            exec_create_rel(db, &stmt[11..])
271        } else if upper.starts_with("MATCH NODE ") {
272            exec_match_node(db, &stmt[11..])
273        } else if upper.starts_with("MATCH REL ") {
274            exec_match_rel(db, &stmt[10..])
275        } else if upper.starts_with("DELETE NODE ") {
276            exec_delete_node(db, &stmt[12..]).map(|cnt| (Vec::new(), cnt, 0, true))
277        } else if upper.starts_with("DELETE REL ") {
278            exec_delete_rel(db, &stmt[11..]).map(|cnt| (Vec::new(), 0, cnt, true))
279        } else if upper.starts_with("CALL ") {
280            exec_call_procedure(db, &stmt[5..])
281        } else if upper.contains("CALL ") {
282            // Query contains CALL but doesn't start with it (e.g., "MATCH ... WITH ... CALL embedding.similar(...)")
283            // Extract label filter from MATCH clause if present (e.g., "MATCH (n:Person)")
284            let label_filter = extract_match_label(&upper);
285            
286            // Extract and execute just the CALL portion, injecting label filter if needed
287            if let Some(call_idx) = upper.find("CALL ") {
288                let call_part = &stmt[call_idx + 5..];
289                exec_call_procedure_with_label(db, call_part, label_filter)
290            } else {
291                return Err(anyhow!("unrecognized statement: {}", stmt));
292            }
293        } else {
294            return Err(anyhow!("unrecognized statement: {}", stmt));
295        }?;
296
297        let (rows, n_cnt, r_cnt, mutated) = res;
298        outcome.rows.extend(rows);
299        outcome.affected_nodes += n_cnt;
300        outcome.affected_relationships += r_cnt;
301        any_mut = any_mut || mutated;
302    }
303    outcome.mutated = any_mut;
304    Ok(outcome)
305}
306
307#[cfg_attr(not(test), allow(dead_code))]
308pub fn execute_and_log(db: &mut GraphDatabase, query: &str) -> Result<QueryOutcome> {
309    let res = execute_query(db, query);
310    log_query(query, &res);
311    res
312}
313
314/// Execute a query with parameters (for OpenCypher `$param` usage).
315#[cfg_attr(not(test), allow(dead_code))]
316pub fn execute_query_with_params(
317    db: &mut GraphDatabase,
318    query: &str,
319    params: &HashMap<String, String>,
320)
321-> Result<QueryOutcome> {
322    let trimmed = query.trim();
323    if trimmed.is_empty() {
324        return Err(anyhow!("empty query"));
325    }
326
327    let mut outcome = QueryOutcome::default();
328    let mut any_mut = false;
329    for stmt in trimmed.split(';') {
330        let stmt = stmt.trim();
331        if stmt.is_empty() { continue; }
332        let upper = stmt.to_uppercase();
333
334        // Check if it's a "standard" Cypher query
335        let is_cypher = (upper.starts_with("MATCH ") && stmt[6..].trim_start().starts_with('(')) ||
336            (upper.starts_with("OPTIONAL MATCH ") && stmt[15..].trim_start().starts_with('(')) ||
337            upper.starts_with("MERGE ") ||
338            upper.starts_with("RETURN ") ||
339            (upper.starts_with("DELETE ") && !upper.starts_with("DELETE NODE ") && !upper.starts_with("DELETE REL ")) ||
340            upper.starts_with("DETACH DELETE ") ||
341            (upper.starts_with("CREATE ") && stmt[7..].trim_start().starts_with('('));
342
343        let res = if is_cypher {
344            let rows = execute_cypher_with_params(db, stmt, params)?;
345            let mutated = upper.starts_with("CREATE ") || upper.starts_with("MERGE ") || 
346                (upper.starts_with("DELETE ") && !upper.starts_with("DELETE NODE ") && !upper.starts_with("DELETE REL ")) || 
347                upper.starts_with("DETACH DELETE ");
348            Ok((rows, 0, 0, mutated))
349        } else if upper.starts_with("MATCH (") && upper.contains(" MERGE ") {
350            exec_cypher_match_merge(db, stmt)
351        } else if upper.starts_with("CREATE NODE ") {
352            exec_create_node(db, &stmt[12..])
353        } else if upper.starts_with("CREATE REL ") {
354            exec_create_rel(db, &stmt[11..])
355        } else if upper.starts_with("MATCH NODE ") {
356            exec_match_node(db, &stmt[11..])
357        } else if upper.starts_with("MATCH REL ") {
358            exec_match_rel(db, &stmt[10..])
359        } else if upper.starts_with("DELETE NODE ") {
360            exec_delete_node(db, &stmt[12..]).map(|cnt| (Vec::new(), cnt, 0, true))
361        } else if upper.starts_with("DELETE REL ") {
362            exec_delete_rel(db, &stmt[11..]).map(|cnt| (Vec::new(), 0, cnt, true))
363        } else {
364            // Default to Cypher engine if it doesn't match legacy custom commands
365            let rows = execute_cypher_with_params(db, stmt, params)?;
366            let mutated = upper.starts_with("CREATE ") || upper.starts_with("MERGE ") || 
367                (upper.starts_with("DELETE ") && !upper.starts_with("DELETE NODE ") && !upper.starts_with("DELETE REL ")) || 
368                upper.starts_with("DETACH DELETE ");
369            Ok((rows, 0, 0, mutated))
370        }?;
371
372        let (rows, n_cnt, r_cnt, mutated) = res;
373        outcome.rows.extend(rows);
374        outcome.affected_nodes += n_cnt;
375        outcome.affected_relationships += r_cnt;
376        any_mut = any_mut || mutated;
377    }
378    outcome.mutated = any_mut;
379    Ok(outcome)
380}
381
382/// Same as execute_and_log but accepts parameters for OpenCypher `$param`s.
383#[cfg_attr(not(test), allow(dead_code))]
384pub fn _execute_and_log_with_params(
385    db: &mut GraphDatabase,
386    query: &str,
387    params: &HashMap<String, String>,
388) -> Result<QueryOutcome> {
389    let res = execute_query_with_params(db, query, params);
390    log_query(query, &res);
391    res
392}
393
394/// Execute a CALL procedure with an optional label filter from preceding MATCH clause
395fn exec_call_procedure_with_label(
396    db: &mut GraphDatabase,
397    rest: &str,
398    label_filter: Option<String>,
399) -> Result<(Vec<QueryResultRow>, usize, usize, bool)> {
400    let upper = rest.to_uppercase();
401    
402    // For embedding.similar and embedding.threshold, inject label filter if not already provided
403    if upper.starts_with("EMBEDDING.SIMILAR") || upper.starts_with("EMBEDDING.THRESHOLD") {
404        if let Some(label) = label_filter {
405            // Check if a label filter is already provided (3rd argument for similar, would need different handling)
406            let args = extract_call_args(rest)?;
407            if upper.starts_with("EMBEDDING.SIMILAR") && args.len() == 2 {
408                // Inject label as 3rd argument: embedding.similar("query", k, "Label")
409                let new_call = format!("embedding.similar(\"{}\", {}, \"{}\")", args[0], args[1], label);
410                return exec_call_procedure(db, &new_call);
411            }
412        }
413    }
414    
415    // Fall back to normal procedure execution
416    exec_call_procedure(db, rest)
417}
418
419// Split on a top-level WHERE (case-insensitive). Returns (head, where_clause)
420fn split_where(rest: &str) -> (String, Option<String>) {
421    // naive approach: find " WHERE " (case-insensitive). Also support trailing where without spaces around
422    let upper = rest.to_uppercase();
423    if let Some(idx) = upper.find(" WHERE ") {
424        let head = rest[..idx].trim().to_string();
425        let tail = rest[idx + 7..].trim().to_string();
426        (head, if tail.is_empty() { None } else { Some(tail) })
427    } else if let Some(idx) = upper.find(" WHERE") {
428        let head = rest[..idx].trim().to_string();
429        let tail = rest[idx + 6..].trim().to_string();
430        (head, if tail.is_empty() { None } else { Some(tail) })
431    } else {
432        (rest.trim().to_string(), None)
433    }
434}
435
436fn parse_label_and_props(rest: &str) -> Result<(String, HashMap<String, String>)> {
437    // Expect: Label {k:"v", a:"b"} or just Label
438    let mut label = rest.trim().to_string();
439    let mut props: HashMap<String, String> = HashMap::new();
440    if let Some(idx) = rest.find('{') {
441        label = rest[..idx].trim().to_string();
442        let after = &rest[idx..];
443        if let Some(end_idx) = after.rfind('}') {
444            let inside = &after[1..end_idx];
445            props = parse_keyvals(inside)?;
446        }
447    }
448    if label.is_empty() { return Err(anyhow!("missing label")); }
449    Ok((label, props))
450}
451
452#[derive(Debug, Clone)]
453enum WhereCond {
454    // Nodes and Relationships
455    IdEquals(Uuid),
456    LabelEquals(String),
457    HasKey(String),
458    MetaEq(String, String),
459    MetaNe(String, String),
460    // Relationships only
461    FromEquals(Uuid),
462    ToEquals(Uuid),
463}
464
465fn parse_where_conds(s: &str) -> Result<Vec<WhereCond>> {
466    // Conditions are separated by AND (case-insensitive)
467    let mut out = Vec::new();
468    // allow multi-line safety (we treat newlines/semicolons as plain text within this WHERE, since the parser splits statements earlier)
469    // Better: manually scan tokens separated by 'AND'
470    let mut start = 0usize;
471    let bytes = s.as_bytes();
472    let mut i = 0usize;
473    let mut conds: Vec<&str> = Vec::new();
474    while i < bytes.len() {
475        // try to match 'AND' case-insensitive with word boundaries
476        if i + 3 <= bytes.len() {
477            let sub = &s[i..i+3];
478            if sub.eq_ignore_ascii_case("AND") {
479                // word boundary: previous and next must be whitespace or punctuation
480                let prev_ok = i == 0 || s[..i].chars().last().map(|ch| ch.is_whitespace() || ch == ')' ).unwrap_or(true);
481                let next_ok = i + 3 >= s.len() || s[i+3..].chars().next().map(|ch| ch.is_whitespace() || ch == '(' ).unwrap_or(true);
482                if prev_ok && next_ok {
483                    conds.push(s[start..i].trim());
484                    i += 3;
485                    start = i;
486                    continue;
487                }
488            }
489        }
490        i += 1;
491    }
492    conds.push(s[start..].trim());
493
494    for c in conds.into_iter().filter(|c| !c.is_empty()) {
495        let cu = c.to_uppercase();
496        if cu.starts_with("HAS(") && c.ends_with(')') {
497            let inside = &c[4..c.len()-1];
498            let key = inside.trim().trim_matches('"').trim_matches('\'');
499            if key.is_empty() { return Err(anyhow!("WHERE has() requires a key")); }
500            out.push(WhereCond::HasKey(key.to_string()));
501            continue;
502        }
503        // inequality key!="v"
504        if let Some(pos) = c.find("!=") {
505            let key = c[..pos].trim();
506            let val = c[pos+2..].trim().trim_matches('"').trim_matches('\'');
507            if key.eq_ignore_ascii_case("id") || key.eq_ignore_ascii_case("label")
508                || key.eq_ignore_ascii_case("from") || key.eq_ignore_ascii_case("to") {
509                return Err(anyhow!("'!=' supported only for metadata keys"));
510            }
511            if key.is_empty() { return Err(anyhow!("missing key before !=")); }
512            out.push(WhereCond::MetaNe(key.to_string(), val.to_string()));
513            continue;
514        }
515        // equality key="v" or id=uuid or label=Label or from/to=uuid
516        if let Some(pos) = c.find('=') {
517            let key = c[..pos].trim();
518            let val_raw = c[pos+1..].trim();
519            if key.eq_ignore_ascii_case("id") {
520                let id = Uuid::parse_str(val_raw.trim_matches('"'))?;
521                out.push(WhereCond::IdEquals(id));
522                continue;
523            }
524            if key.eq_ignore_ascii_case("from") {
525                let id = Uuid::parse_str(val_raw.trim_matches('"'))?;
526                out.push(WhereCond::FromEquals(id));
527                continue;
528            }
529            if key.eq_ignore_ascii_case("to") {
530                let id = Uuid::parse_str(val_raw.trim_matches('"'))?;
531                out.push(WhereCond::ToEquals(id));
532                continue;
533            }
534            if key.eq_ignore_ascii_case("label") {
535                let v = val_raw.trim_matches('"').trim_matches('\'').to_string();
536                out.push(WhereCond::LabelEquals(v));
537                continue;
538            }
539            // metadata equality requires quoted value but we'll accept bare too
540            let v = val_raw.trim_matches('"').trim_matches('\'').to_string();
541            if key.is_empty() { return Err(anyhow!("missing key before =")); }
542            out.push(WhereCond::MetaEq(key.to_string(), v));
543            continue;
544        }
545        return Err(anyhow!("unrecognized WHERE condition: {}", c));
546    }
547    Ok(out)
548}
549
550fn parse_keyvals(s: &str) -> Result<HashMap<String, String>> {
551    let mut map = HashMap::new();
552    for part in s.split(',') {
553        let p = part.trim();
554        if p.is_empty() { continue; }
555        let mut kv = p.splitn(2, ':');
556        let k = kv.next().ok_or_else(|| anyhow!("missing key"))?.trim();
557        let v = kv.next().ok_or_else(|| anyhow!("missing value for {}", k))?.trim();
558        let v = v.trim_matches('"').trim_matches('\'');
559        map.insert(k.to_string(), v.to_string());
560    }
561    Ok(map)
562}
563
564// Minimal openCypher-style support for pattern-based pair matching and merge
565// Supports statements like:
566//   MATCH (a:Label), (b:Label) [WHERE id(a) < id(b) | id(a) <> id(b)] MERGE (a)-[:TYPE]->(b)
567// Limitations: single label per variable; WHERE only supports id(var) comparisons using <,>,<=,>=,=,<>
568fn exec_cypher_match_merge(db: &mut GraphDatabase, stmt: &str) -> Result<(Vec<QueryResultRow>, usize, usize, bool)> {
569    // Split into MATCH ... [WHERE ...] MERGE ...
570    let up = stmt.to_uppercase();
571    let match_pos = up.find("MATCH ").ok_or_else(|| anyhow!("invalid MATCH/MERGE statement"))?;
572    let merge_pos = up.rfind(" MERGE ").ok_or_else(|| anyhow!("MATCH ... MERGE ... required"))?;
573    if merge_pos <= match_pos { return Err(anyhow!("MERGE must come after MATCH")); }
574    let match_part = stmt[match_pos + 6..merge_pos].trim();
575    let merge_part = stmt[merge_pos + 7..].trim();
576
577    // Extract optional WHERE from match_part
578    let (patterns_part, where_opt) = split_where(match_part);
579    // Expect two node patterns separated by comma: (a:Label), (b:Label)
580    let mut pats = patterns_part.split(',').map(|s| s.trim());
581    let p1 = pats.next().ok_or_else(|| anyhow!("missing first pattern"))?;
582    let p2 = pats.next().ok_or_else(|| anyhow!("missing second pattern"))?;
583    if pats.next().is_some() { return Err(anyhow!("only two node patterns are supported")); }
584
585    fn parse_var_label(p: &str) -> Result<(String, String)> {
586        // form: (var:Label) or (var)
587        let p = p.trim();
588        if !p.starts_with('(') || !p.ends_with(')') { return Err(anyhow!("invalid node pattern: {}", p)); }
589        let inside = &p[1..p.len()-1];
590        let (var, label) = if let Some(col) = inside.find(':') {
591            (inside[..col].trim().to_string(), inside[col+1..].trim().to_string())
592        } else {
593            (inside.trim().to_string(), String::new())
594        };
595        if var.is_empty() { return Err(anyhow!("variable name required in node pattern")); }
596        Ok((var, label))
597    }
598
599    let (var_a, label_a) = parse_var_label(p1)?;
600    let (var_b, label_b) = parse_var_label(p2)?;
601    // For now require labels on both and allow same label or different
602    if label_a.is_empty() || label_b.is_empty() { return Err(anyhow!("labels required in MATCH node patterns")); }
603
604    // Collect candidate node sets by label
605    let ids_a = db.find_node_ids_by_label(&label_a);
606    let ids_b = db.find_node_ids_by_label(&label_b);
607
608    // WHERE: only id(var) comparator id(var)
609    enum CmpOp { Lt, Lte, Gt, Gte, Eq, Ne }
610    let mut cmp_filter: Option<(CmpOp, String, String)> = None; // (op, leftVar, rightVar)
611    if let Some(w) = where_opt {
612        // Normalize spaces and case a bit; expect pattern like: id(a) < id(b)
613        let wu = w.replace(" ", "");
614        // Identify operator by precedence
615        let (op, sym) = if let Some(_i) = wu.find("<=") { (CmpOp::Lte, "<=") }
616            else if let Some(_i) = wu.find(">=") { (CmpOp::Gte, ">=") }
617            else if let Some(_i) = wu.find("<>") { (CmpOp::Ne, "<>") }
618            else if let Some(_i) = wu.find('<') { (CmpOp::Lt, "<") }
619            else if let Some(_i) = wu.find('>') { (CmpOp::Gt, ">") }
620            else if let Some(_i) = wu.find('=') { (CmpOp::Eq, "=") }
621            else { return Err(anyhow!("unsupported WHERE comparator; use <,>,<=,>=,=,<>")); };
622        let parts: Vec<&str> = wu.split(sym).collect();
623        if parts.len() != 2 { return Err(anyhow!("malformed WHERE clause")); }
624        let parse_id_fn = |s: &str| -> Result<String> {
625            if !s.to_uppercase().starts_with("ID(") || !s.ends_with(')') { return Err(anyhow!("WHERE must use id(var)")); }
626            let v = s[3..s.len()-1].to_string();
627            if v.is_empty() { return Err(anyhow!("empty variable in id()")); }
628            Ok(v)
629        };
630        let left = parse_id_fn(parts[0])?;
631        let right = parse_id_fn(parts[1])?;
632        cmp_filter = Some((op, left, right));
633    }
634
635    // Helper to compare UUID order
636    let cmp = |a: &Uuid, b: &Uuid, op: &CmpOp| -> bool {
637        let au = a.as_u128();
638        let bu = b.as_u128();
639        match op {
640            CmpOp::Lt => au < bu,
641            CmpOp::Lte => au <= bu,
642            CmpOp::Gt => au > bu,
643            CmpOp::Gte => au >= bu,
644            CmpOp::Eq => au == bu,
645            CmpOp::Ne => au != bu,
646        }
647    };
648
649    // Parse MERGE pattern: (varA)-[:TYPE]->(varB)
650    let mp = merge_part.trim();
651    // very minimal parse
652    let m_up = mp.to_uppercase();
653    if !mp.starts_with('(') || !m_up.contains(")-[:") || !m_up.contains("]->(") || !mp.ends_with(')') {
654        return Err(anyhow!("unsupported MERGE pattern; expected (a)-[:TYPE]->(b)"));
655    }
656    // Extract left var
657    let left_end = mp.find(')').ok_or_else(|| anyhow!("bad MERGE left"))?;
658    let left_var = mp[1..left_end].trim().to_string();
659    // Extract type
660    let type_start = mp[left_end..].find("[:").ok_or_else(|| anyhow!("missing [:TYPE]"))? + left_end + 2;
661    let type_end = mp[type_start..].find(']').ok_or_else(|| anyhow!("missing ] in MERGE type"))? + type_start;
662    let rel_type = mp[type_start..type_end].trim().to_string();
663    // Extract right var after "]->("
664    let arrow = mp[type_end..].find("->(").ok_or_else(|| anyhow!("missing ->( in MERGE"))? + type_end;
665    let right_start = arrow + 3;
666    if !mp.ends_with(')') { return Err(anyhow!("missing closing ) for MERGE right var")); }
667    let right_var = mp[right_start..mp.len()-1].trim().to_string();
668
669    // Sanity check variables map
670    let map_var = |name: &str| -> Result<&str> {
671        if name == var_a { Ok("A") } else if name == var_b { Ok("B") } else { Err(anyhow!("MERGE references unknown variable: {}", name)) }
672    };
673    map_var(&left_var)?; map_var(&right_var)?; // validate
674
675    // Build all pairs according to WHERE comparator if present
676    let mut rows = Vec::new();
677    let mut rel_count = 0usize;
678    let mut created = false;
679
680    // Precompute existing relationships set for MERGE semantics: (from,to,label)
681    let mut exists = std::collections::HashSet::<(Uuid, Uuid, String)>::new();
682    for r in db.relationships.values() {
683        exists.insert((r.from_node, r.to_node, r.label.clone()));
684    }
685
686    for a_id in &ids_a {
687        for b_id in &ids_b {
688            // variable self equality allowed only if var names differ; but if it's the same label and same set, allow a!=b unless WHERE explicitly allows equals
689            if var_a == var_b && a_id == b_id { continue; }
690            if let Some((op, l, r)) = &cmp_filter {
691                let (lv, rv) = if &l[..] == var_a && &r[..] == var_b {
692                    (a_id, b_id)
693                } else if &l[..] == var_b && &r[..] == var_a {
694                    (b_id, a_id)
695                } else {
696                    // comparator references unknown variables
697                    return Err(anyhow!("WHERE references unknown variables"));
698                };
699                if !cmp(lv, rv, op) { continue; }
700            }
701            // Determine from/to based on MERGE order (left_var -> right_var)
702            let (from, to) = if left_var == var_a && right_var == var_b {
703                (*a_id, *b_id)
704            } else if left_var == var_b && right_var == var_a {
705                (*b_id, *a_id)
706            } else {
707                return Err(anyhow!("MERGE variable order does not match MATCH variables"));
708            };
709            let key = (from, to, rel_type.clone());
710            if !exists.contains(&key) {
711                if let Some(rid) = db.add_relationship(from, to, rel_type.clone(), HashMap::new()) {
712                    exists.insert(key);
713                    rel_count += 1;
714                    created = true;
715                    if let Some(r) = db.get_relationship(rid).cloned() {
716                        rows.push(QueryResultRow::Relationship { id: r.id, from: r.from_node, to: r.to_node, label: r.label, metadata: r.metadata });
717                    }
718                }
719            }
720        }
721    }
722
723    Ok((rows, 0, rel_count, created))
724}
725
726fn exec_create_node(db: &mut GraphDatabase, rest: &str) -> Result<(Vec<QueryResultRow>, usize, usize, bool)> {
727    // rest: Label {k:"v", ...}
728    let (label, props) = parse_label_and_props(rest)?;
729    let id = db.add_node(label.clone(), props.clone());
730    let mut rows = Vec::new();
731    if let Some(n) = db.get_node(id).cloned() {
732        rows.push(QueryResultRow::Node { id: n.id, label: n.label, metadata: n.metadata });
733    }
734    Ok((rows, 1, 0, true))
735}
736
737fn exec_create_rel(db: &mut GraphDatabase, rest: &str) -> Result<(Vec<QueryResultRow>, usize, usize, bool)> {
738    // rest: from=<uuid> to=<uuid> label=Label {k:"v", ...}
739    let mut from: Option<Uuid> = None;
740    let mut to: Option<Uuid> = None;
741    let mut label: Option<String> = None;
742    let mut props: HashMap<String, String> = HashMap::new();
743
744    // Split on spaces but keep brace content for props
745    let mut cursor = rest.trim();
746    // properties block
747    if let Some(brace_idx) = cursor.find('{') {
748        if let Some(end) = cursor.rfind('}') { props = parse_keyvals(&cursor[brace_idx+1..end])?; cursor = &cursor[..brace_idx]; }
749    }
750    for token in cursor.split_whitespace() {
751        let up = token.to_uppercase();
752        if up.starts_with("FROM=") { from = Some(Uuid::parse_str(&token[5..])?); }
753        else if up.starts_with("TO=") { to = Some(Uuid::parse_str(&token[3..])?); }
754        else if up.starts_with("LABEL=") { label = Some(token[6..].to_string()); }
755    }
756    let from = from.ok_or_else(|| anyhow!("missing from uuid"))?;
757    let to = to.ok_or_else(|| anyhow!("missing to uuid"))?;
758    let label = label.ok_or_else(|| anyhow!("missing label"))?;
759    let id = db.add_relationship(from, to, label.clone(), props.clone())
760        .ok_or_else(|| anyhow!("invalid endpoint(s) for relationship"))?;
761    let mut rows = Vec::new();
762    if let Some(r) = db.get_relationship(id).cloned() {
763        rows.push(QueryResultRow::Relationship { id: r.id, from: r.from_node, to: r.to_node, label: r.label, metadata: r.metadata });
764    }
765    Ok((rows, 0, 1, true))
766}
767
768fn exec_match_node(db: &GraphDatabase, rest: &str) -> Result<(Vec<QueryResultRow>, usize, usize, bool)> {
769    // Support optional WHERE after the label/props
770    let (head, where_clause) = split_where(rest);
771    let (label, props) = parse_label_and_props(&head)?;
772    let mut ids = db.find_node_ids_by_label(&label);
773    // Filter by props
774    if !props.is_empty() {
775        ids.retain(|id| {
776            db.get_node(*id).map(|n| props.iter().all(|(k, v)| n.metadata.get(k).map(|m| m == v).unwrap_or(false))).unwrap_or(false)
777        });
778    }
779    // Apply WHERE conditions, if any
780    let conds = if let Some(ws) = where_clause { parse_where_conds(&ws)? } else { Vec::new() };
781    if !conds.is_empty() {
782        ids = ids.into_par_iter().filter(|id| {
783            if let Some(n) = db.get_node(*id) {
784                for c in &conds {
785                    match c {
786                        WhereCond::IdEquals(u) => { if &n.id != u { return false; } }
787                        WhereCond::LabelEquals(l) => { if &n.label != l { return false; } }
788                        WhereCond::HasKey(k) => { if !n.metadata.contains_key(k) { return false; } }
789                        WhereCond::MetaEq(k, v) => { if n.metadata.get(k).map(|m| m == v).unwrap_or(false) == false { return false; } }
790                        WhereCond::MetaNe(k, v) => { if n.metadata.get(k).map(|m| m == v).unwrap_or(false) { return false; } }
791                        // Relationship-only filters are ignored for nodes
792                        WhereCond::FromEquals(_) | WhereCond::ToEquals(_) => { return false; }
793                    }
794                }
795                true
796            } else { false }
797        }).collect();
798    }
799    let mut rows = Vec::with_capacity(ids.len());
800    for id in ids {
801        if let Some(n) = db.get_node(id).cloned() {
802            rows.push(QueryResultRow::Node { id: n.id, label: n.label, metadata: n.metadata });
803        }
804    }
805    Ok((rows, 0, 0, false))
806}
807
808fn exec_match_rel(db: &GraphDatabase, rest: &str) -> Result<(Vec<QueryResultRow>, usize, usize, bool)> {
809    // Support optional WHERE after the label/props
810    let (head, where_clause) = split_where(rest);
811    let (label, props) = parse_label_and_props(&head)?;
812    let mut ids = db.find_relationship_ids_by_label(&label);
813    if !props.is_empty() {
814        ids.retain(|rid| {
815            db.get_relationship(*rid).map(|r| props.iter().all(|(k, v)| r.metadata.get(k).map(|m| m == v).unwrap_or(false))).unwrap_or(false)
816        });
817    }
818    let conds = if let Some(ws) = where_clause { parse_where_conds(&ws)? } else { Vec::new() };
819    if !conds.is_empty() {
820        ids = ids.into_par_iter().filter(|rid| {
821            if let Some(r) = db.get_relationship(*rid) {
822                for c in &conds {
823                    match c {
824                        WhereCond::IdEquals(u) => { if &r.id != u { return false; } }
825                        WhereCond::LabelEquals(l) => { if &r.label != l { return false; } }
826                        WhereCond::HasKey(k) => { if !r.metadata.contains_key(k) { return false; } }
827                        WhereCond::MetaEq(k, v) => { if r.metadata.get(k).map(|m| m == v).unwrap_or(false) == false { return false; } }
828                        WhereCond::MetaNe(k, v) => { if r.metadata.get(k).map(|m| m == v).unwrap_or(false) { return false; } }
829                        WhereCond::FromEquals(u) => { if &r.from_node != u { return false; } }
830                        WhereCond::ToEquals(u) => { if &r.to_node != u { return false; } }
831                    }
832                }
833                true
834            } else { false }
835        }).collect();
836    }
837    let mut rows = Vec::with_capacity(ids.len());
838    for rid in ids {
839        if let Some(r) = db.get_relationship(rid).cloned() {
840            rows.push(QueryResultRow::Relationship { id: r.id, from: r.from_node, to: r.to_node, label: r.label, metadata: r.metadata });
841        }
842    }
843    Ok((rows, 0, 0, false))
844}
845
846fn exec_delete_node(db: &mut GraphDatabase, rest: &str) -> Result<usize> {
847    let id = parse_uuid_from(rest)?;
848    let removed = db.remove_node(id);
849    Ok(if removed { 1 } else { 0 })
850}
851
852fn exec_delete_rel(db: &mut GraphDatabase, rest: &str) -> Result<usize> {
853    let id = parse_uuid_from(rest)?;
854    let removed = db.remove_relationship(id);
855    Ok(if removed { 1 } else { 0 })
856}
857
858fn parse_uuid_from(s: &str) -> Result<Uuid> { Uuid::parse_str(s.trim()).map_err(|e| anyhow!("invalid uuid: {}", e)) }
859
860/// Execute CALL procedure for graph algorithms
861/// Supported: CALL algo.pageRank(), CALL algo.betweenness(), CALL algo.shortestPath(from, to), CALL algo.allPaths(from, to, maxDepth)
862fn exec_call_procedure(db: &mut GraphDatabase, rest: &str) -> Result<(Vec<QueryResultRow>, usize, usize, bool)> {
863    let rest = rest.trim();
864    let upper = rest.to_uppercase();
865    
866    if upper.starts_with("ALGO.PAGERANK") {
867        // CALL algo.pageRank() or CALL algo.pageRank(damping, iterations)
868        let scores = pagerank(db, 0.85, 20);
869        let mut rows: Vec<QueryResultRow> = scores.iter()
870            .filter_map(|(id, score)| {
871                db.get_node(*id).map(|n| {
872                    let mut meta = n.metadata.clone();
873                    meta.insert("_score".to_string(), format!("{:.6}", score));
874                    QueryResultRow::Node { id: *id, label: n.label.clone(), metadata: meta }
875                })
876            })
877            .collect();
878        // Sort by score descending
879        rows.sort_by(|a, b| {
880            let score_a = match a { QueryResultRow::Node { metadata, .. } => metadata.get("_score").and_then(|s| s.parse::<f64>().ok()).unwrap_or(0.0), _ => 0.0 };
881            let score_b = match b { QueryResultRow::Node { metadata, .. } => metadata.get("_score").and_then(|s| s.parse::<f64>().ok()).unwrap_or(0.0), _ => 0.0 };
882            score_b.partial_cmp(&score_a).unwrap_or(std::cmp::Ordering::Equal)
883        });
884        Ok((rows, 0, 0, false))
885    } else if upper.starts_with("ALGO.BETWEENNESS") {
886        // CALL algo.betweenness()
887        let scores = betweenness_centrality(db);
888        let mut rows: Vec<QueryResultRow> = scores.iter()
889            .filter_map(|(id, score)| {
890                db.get_node(*id).map(|n| {
891                    let mut meta = n.metadata.clone();
892                    meta.insert("_score".to_string(), format!("{:.6}", score));
893                    QueryResultRow::Node { id: *id, label: n.label.clone(), metadata: meta }
894                })
895            })
896            .collect();
897        rows.sort_by(|a, b| {
898            let score_a = match a { QueryResultRow::Node { metadata, .. } => metadata.get("_score").and_then(|s| s.parse::<f64>().ok()).unwrap_or(0.0), _ => 0.0 };
899            let score_b = match b { QueryResultRow::Node { metadata, .. } => metadata.get("_score").and_then(|s| s.parse::<f64>().ok()).unwrap_or(0.0), _ => 0.0 };
900            score_b.partial_cmp(&score_a).unwrap_or(std::cmp::Ordering::Equal)
901        });
902        Ok((rows, 0, 0, false))
903    } else if upper.starts_with("ALGO.SHORTESTPATH") {
904        // CALL algo.shortestPath(fromId, toId)
905        let args = extract_call_args(rest)?;
906        if args.len() < 2 {
907            return Err(anyhow!("algo.shortestPath requires 2 arguments: fromId, toId"));
908        }
909        let from_id = Uuid::parse_str(&args[0]).map_err(|e| anyhow!("invalid from uuid: {}", e))?;
910        let to_id = Uuid::parse_str(&args[1]).map_err(|e| anyhow!("invalid to uuid: {}", e))?;
911        
912        match shortest_path(db, from_id, to_id) {
913            Some(path) => {
914                let rows: Vec<QueryResultRow> = path.iter()
915                    .enumerate()
916                    .filter_map(|(i, id)| {
917                        db.get_node(*id).map(|n| {
918                            let mut meta = n.metadata.clone();
919                            meta.insert("_pathIndex".to_string(), i.to_string());
920                            QueryResultRow::Node { id: *id, label: n.label.clone(), metadata: meta }
921                        })
922                    })
923                    .collect();
924                Ok((rows, 0, 0, false))
925            }
926            None => Ok((vec![QueryResultRow::Info("No path found".to_string())], 0, 0, false))
927        }
928    } else if upper.starts_with("ALGO.ASTAR") {
929        // CALL algo.astar(fromId, toId) - requires node positions, uses Euclidean heuristic
930        // Note: This requires positions which aren't available in query context, so we fall back to BFS
931        let args = extract_call_args(rest)?;
932        if args.len() < 2 {
933            return Err(anyhow!("algo.astar requires 2 arguments: fromId, toId"));
934        }
935        let from_id = Uuid::parse_str(&args[0]).map_err(|e| anyhow!("invalid from uuid: {}", e))?;
936        let to_id = Uuid::parse_str(&args[1]).map_err(|e| anyhow!("invalid to uuid: {}", e))?;
937        
938        // Use empty positions - astar will fall back to BFS behavior
939        let positions = std::collections::HashMap::new();
940        match astar_path(db, &positions, from_id, to_id) {
941            Some(path) => {
942                let rows: Vec<QueryResultRow> = path.iter()
943                    .enumerate()
944                    .filter_map(|(i, id)| {
945                        db.get_node(*id).map(|n| {
946                            let mut meta = n.metadata.clone();
947                            meta.insert("_pathIndex".to_string(), i.to_string());
948                            QueryResultRow::Node { id: *id, label: n.label.clone(), metadata: meta }
949                        })
950                    })
951                    .collect();
952                Ok((rows, 0, 0, false))
953            }
954            None => Ok((vec![QueryResultRow::Info("No path found".to_string())], 0, 0, false))
955        }
956    } else if upper.starts_with("ALGO.ALLPATHS") {
957        // CALL algo.allPaths(fromId, toId, maxDepth)
958        let args = extract_call_args(rest)?;
959        if args.len() < 3 {
960            return Err(anyhow!("algo.allPaths requires 3 arguments: fromId, toId, maxDepth"));
961        }
962        let from_id = Uuid::parse_str(&args[0]).map_err(|e| anyhow!("invalid from uuid: {}", e))?;
963        let to_id = Uuid::parse_str(&args[1]).map_err(|e| anyhow!("invalid to uuid: {}", e))?;
964        let max_depth: usize = args[2].parse().map_err(|_| anyhow!("invalid maxDepth"))?;
965        
966        let paths = all_paths(db, from_id, to_id, max_depth);
967        let mut rows = Vec::new();
968        for (path_idx, path) in paths.iter().enumerate() {
969            let path_str = path.iter().map(|id| id.to_string()).collect::<Vec<_>>().join(" -> ");
970            rows.push(QueryResultRow::Info(format!("Path {}: {} (length {})", path_idx + 1, path_str, path.len())));
971        }
972        if rows.is_empty() {
973            rows.push(QueryResultRow::Info("No paths found".to_string()));
974        }
975        Ok((rows, 0, 0, false))
976    } else if upper.starts_with("DB.SEARCH") {
977        // CALL db.search("query text") - Full-text search using FTS5
978        let args = extract_call_args(rest)?;
979        if args.is_empty() {
980            return Err(anyhow!("db.search requires 1 argument: search query"));
981        }
982        let query = &args[0];
983        
984        // Search in-memory by label and metadata (FTS5 is in SQLite, this is a fallback)
985        let mut rows = Vec::new();
986        let query_lower = query.to_lowercase();
987        for node in db.nodes.values() {
988            let label_match = node.label.to_lowercase().contains(&query_lower);
989            let meta_match = node.metadata.values().any(|v| v.to_lowercase().contains(&query_lower));
990            if label_match || meta_match {
991                rows.push(QueryResultRow::Node {
992                    id: node.id,
993                    label: node.label.clone(),
994                    metadata: node.metadata.clone(),
995                });
996            }
997        }
998        Ok((rows, 0, 0, false))
999    } else if upper.starts_with("TEMPORAL.TIMELINE") {
1000        // CALL temporal.timeline() - Get timeline of all graph events
1001        let timeline = get_timeline(db);
1002        let rows: Vec<QueryResultRow> = timeline.iter()
1003            .map(|e| QueryResultRow::Info(format!("{}: {:?} {} ({})", e.timestamp, e.event_type, e.entity_id, e.label)))
1004            .collect();
1005        Ok((rows, 0, 0, false))
1006    } else if upper.starts_with("TEMPORAL.RANGE") {
1007        // CALL temporal.range() - Get timestamp range of the graph
1008        match get_timestamp_range(db) {
1009            Some((min, max)) => Ok((vec![QueryResultRow::Info(format!("min: {}, max: {}", min, max))], 0, 0, false)),
1010            None => Ok((vec![QueryResultRow::Info("Graph is empty".to_string())], 0, 0, false)),
1011        }
1012    } else if upper.starts_with("TEMPORAL.NODESINRANGE") {
1013        // CALL temporal.nodesInRange(fromTimestamp, toTimestamp)
1014        let args = extract_call_args(rest)?;
1015        if args.len() < 2 {
1016            return Err(anyhow!("temporal.nodesInRange requires 2 arguments: fromTimestamp, toTimestamp"));
1017        }
1018        let from: i64 = args[0].parse().map_err(|_| anyhow!("invalid fromTimestamp"))?;
1019        let to: i64 = args[1].parse().map_err(|_| anyhow!("invalid toTimestamp"))?;
1020        let node_ids = nodes_in_range(db, from, to);
1021        let rows: Vec<QueryResultRow> = node_ids.iter()
1022            .filter_map(|id| db.get_node(*id).map(|n| QueryResultRow::Node {
1023                id: *id,
1024                label: n.label.clone(),
1025                metadata: n.metadata.clone(),
1026            }))
1027            .collect();
1028        Ok((rows, 0, 0, false))
1029    } else if upper.starts_with("TEMPORAL.ATTIME") {
1030        // CALL temporal.atTime(timestamp) - Get graph state at a specific time
1031        let args = extract_call_args(rest)?;
1032        if args.is_empty() {
1033            return Err(anyhow!("temporal.atTime requires 1 argument: timestamp"));
1034        }
1035        let timestamp: i64 = args[0].parse().map_err(|_| anyhow!("invalid timestamp"))?;
1036        let (nodes, rels) = graph_at_time(db, timestamp);
1037        let mut rows: Vec<QueryResultRow> = nodes.iter()
1038            .map(|n| QueryResultRow::Node { id: n.id, label: n.label.clone(), metadata: n.metadata.clone() })
1039            .collect();
1040        for r in &rels {
1041            rows.push(QueryResultRow::Relationship {
1042                id: r.id,
1043                from: r.from_node,
1044                to: r.to_node,
1045                label: r.label.clone(),
1046                metadata: r.metadata.clone(),
1047            });
1048        }
1049        Ok((rows, 0, 0, false))
1050    } else if upper.starts_with("DB.SCHEMA") {
1051        // CALL db.schema() - Get graph schema (labels and relationship types)
1052        use crate::semantic::rag::suggest_queries;
1053        let suggestions = suggest_queries(db);
1054        let mut rows = Vec::new();
1055        
1056        // List node labels
1057        for (label, ids) in &db.label_index {
1058            rows.push(QueryResultRow::Info(format!("Label: {} ({} nodes)", label, ids.len())));
1059        }
1060        
1061        // List relationship types
1062        let mut rel_counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
1063        for rel in db.relationships.values() {
1064            *rel_counts.entry(rel.label.clone()).or_insert(0) += 1;
1065        }
1066        for (label, count) in rel_counts {
1067            rows.push(QueryResultRow::Info(format!("RelType: {} ({} relationships)", label, count)));
1068        }
1069        
1070        // Add query suggestions
1071        rows.push(QueryResultRow::Info("--- Suggested Queries ---".to_string()));
1072        for suggestion in suggestions.iter().take(5) {
1073            rows.push(QueryResultRow::Info(suggestion.clone()));
1074        }
1075        
1076        Ok((rows, 0, 0, false))
1077    } else if upper.starts_with("SEMANTIC.EXTRACT") {
1078        // CALL semantic.extract("text") - Extract entities from text (simple heuristic mode)
1079        use crate::semantic::extraction::extract_entities_simple;
1080        let args = extract_call_args(rest)?;
1081        if args.is_empty() {
1082            return Err(anyhow!("semantic.extract requires 1 argument: text"));
1083        }
1084        let text = &args[0];
1085        let result = extract_entities_simple(text);
1086        
1087        let mut rows = Vec::new();
1088        for entity in &result.entities {
1089            rows.push(QueryResultRow::Info(format!(
1090                "Entity: {} [{}] (confidence: {:.2})",
1091                entity.name, entity.label, entity.confidence
1092            )));
1093        }
1094        if rows.is_empty() {
1095            rows.push(QueryResultRow::Info("No entities extracted".to_string()));
1096        }
1097        Ok((rows, 0, 0, false))
1098    } else if upper.starts_with("EMBEDDING.SIMILAR") {
1099        // CALL embedding.similar("query text", k, "Label") - Find k most similar nodes by embedding
1100        // Optional 3rd argument filters by node label
1101        use crate::semantic::embeddings::{UnifiedEmbedder, cosine_similarity, l2_distance, NearestNeighbor};
1102        use crate::persistence::settings::AppSettings;
1103        use crate::persistence::persist::get_current_embedding_model;
1104        
1105        let args = extract_call_args(rest)?;
1106        if args.is_empty() {
1107            return Err(anyhow!("embedding.similar requires at least 1 argument: query text"));
1108        }
1109        let query_text = &args[0];
1110        let k: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(10);
1111        let label_filter: Option<String> = args.get(2).map(|s| s.to_string());
1112        
1113        // Load model from SQLite first, fall back to settings file
1114        let model = get_current_embedding_model()
1115            .unwrap_or_else(|| AppSettings::load().map(|s| s.embedding_model).unwrap_or_default());
1116        
1117        // Create embedder for the configured model
1118        let mut embedder = UnifiedEmbedder::new(model)
1119            .map_err(|e| anyhow!("Failed to initialize embedder: {}", e))?;
1120        
1121        // For TF-IDF/Word2Vec, we MUST fit on the corpus first so the query embedding
1122        // uses the same vocabulary as the stored embeddings
1123        if matches!(model, crate::persistence::settings::EmbeddingModel::TfIdf | crate::persistence::settings::EmbeddingModel::Word2Vec) {
1124            let texts: Vec<String> = db.nodes.values()
1125                .map(|n| {
1126                    let mut parts = vec![n.label.clone()];
1127                    parts.extend(n.metadata.values().cloned());
1128                    parts.join(" ")
1129                })
1130                .collect();
1131            embedder.fit(&texts);
1132        }
1133        
1134        let query_embedding = embedder.embed(query_text);
1135        
1136        // Always generate fresh embeddings for comparison to ensure consistency
1137        // This guarantees the query and node embeddings use the same model state
1138        // Filter by label if provided
1139        let mut neighbors: Vec<NearestNeighbor> = db.nodes.iter()
1140            .filter(|(_, node)| {
1141                if let Some(ref label) = label_filter {
1142                    node.label.eq_ignore_ascii_case(label)
1143                } else {
1144                    true
1145                }
1146            })
1147            .map(|(id, node)| {
1148                let mut parts = vec![node.label.clone()];
1149                parts.extend(node.metadata.values().cloned());
1150                let text = parts.join(" ");
1151                let emb = embedder.embed(&text);
1152                let sim = cosine_similarity(&query_embedding, &emb);
1153                let dist = l2_distance(&query_embedding, &emb);
1154                NearestNeighbor { node_id: *id, similarity: sim, distance: dist }
1155            })
1156            .collect();
1157        neighbors.sort_by(|a, b| b.similarity.partial_cmp(&a.similarity).unwrap_or(std::cmp::Ordering::Equal));
1158        neighbors.truncate(k);
1159        let results = neighbors;
1160        
1161        let rows: Vec<QueryResultRow> = results.iter()
1162            .filter_map(|nn| {
1163                db.get_node(nn.node_id).map(|n| {
1164                    let mut meta = n.metadata.clone();
1165                    meta.insert("_similarity".to_string(), format!("{:.4}", nn.similarity));
1166                    meta.insert("_distance".to_string(), format!("{:.4}", nn.distance));
1167                    QueryResultRow::Node { id: nn.node_id, label: n.label.clone(), metadata: meta }
1168                })
1169            })
1170            .collect();
1171        Ok((rows, 0, 0, false))
1172    } else if upper.starts_with("EMBEDDING.NEIGHBORS") {
1173        // CALL embedding.neighbors(nodeId, k) - Find k nearest neighbors to a node
1174        use crate::semantic::embeddings::{cosine_similarity, l2_distance, NearestNeighbor};
1175        use crate::persistence::settings::AppSettings;
1176        use crate::persistence::persist::get_current_embedding_model;
1177        
1178        let args = extract_call_args(rest)?;
1179        if args.is_empty() {
1180            return Err(anyhow!("embedding.neighbors requires at least 1 argument: nodeId"));
1181        }
1182        let node_id = Uuid::parse_str(&args[0]).map_err(|e| anyhow!("invalid nodeId: {}", e))?;
1183        let k: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(10);
1184        
1185        // Load model from SQLite first, fall back to settings file
1186        let model = get_current_embedding_model()
1187            .unwrap_or_else(|| AppSettings::load().map(|s| s.embedding_model).unwrap_or_default());
1188        let model_type = match model {
1189            crate::persistence::settings::EmbeddingModel::TfIdf => "tfidf",
1190            crate::persistence::settings::EmbeddingModel::Word2Vec => "word2vec",
1191            crate::persistence::settings::EmbeddingModel::Onnx => "onnx",
1192        };
1193        
1194        // Load persisted embeddings from SQLite
1195        let stored_embeddings = if let Ok(storage) = get_embedding_storage() {
1196            storage.load_all_model_embeddings(model_type).unwrap_or_default()
1197        } else {
1198            HashMap::new()
1199        };
1200        
1201        let results: Vec<NearestNeighbor> = if let Some(source_emb) = stored_embeddings.get(&node_id) {
1202            let mut neighbors: Vec<NearestNeighbor> = stored_embeddings.iter()
1203                .filter(|(id, _)| **id != node_id)
1204                .map(|(id, emb)| {
1205                    let sim = cosine_similarity(source_emb, emb);
1206                    let dist = l2_distance(source_emb, emb);
1207                    NearestNeighbor { node_id: *id, similarity: sim, distance: dist }
1208                })
1209                .collect();
1210            neighbors.sort_by(|a, b| b.similarity.partial_cmp(&a.similarity).unwrap_or(std::cmp::Ordering::Equal));
1211            neighbors.truncate(k);
1212            neighbors
1213        } else {
1214            Vec::new()
1215        };
1216        
1217        let rows: Vec<QueryResultRow> = results.iter()
1218            .filter_map(|nn| {
1219                db.get_node(nn.node_id).map(|n| {
1220                    let mut meta = n.metadata.clone();
1221                    meta.insert("_similarity".to_string(), format!("{:.4}", nn.similarity));
1222                    meta.insert("_distance".to_string(), format!("{:.4}", nn.distance));
1223                    QueryResultRow::Node { id: nn.node_id, label: n.label.clone(), metadata: meta }
1224                })
1225            })
1226            .collect();
1227        Ok((rows, 0, 0, false))
1228    } else if upper.starts_with("EMBEDDING.THRESHOLD") {
1229        // CALL embedding.threshold("query text", threshold) - Find nodes above similarity threshold
1230        use crate::semantic::embeddings::{UnifiedEmbedder, cosine_similarity, l2_distance, NearestNeighbor};
1231        use crate::persistence::settings::AppSettings;
1232        use crate::persistence::persist::get_current_embedding_model;
1233        
1234        let args = extract_call_args(rest)?;
1235        if args.len() < 2 {
1236            return Err(anyhow!("embedding.threshold requires 2 arguments: query text, threshold (0.0-1.0)"));
1237        }
1238        let query_text = &args[0];
1239        let threshold: f32 = args[1].parse().map_err(|_| anyhow!("invalid threshold"))?;
1240        
1241        // Load model from SQLite first, fall back to settings file
1242        let model = get_current_embedding_model()
1243            .unwrap_or_else(|| AppSettings::load().map(|s| s.embedding_model).unwrap_or_default());
1244        
1245        // Create embedder for the configured model
1246        let mut embedder = UnifiedEmbedder::new(model)
1247            .map_err(|e| anyhow!("Failed to initialize embedder: {}", e))?;
1248        
1249        // For TF-IDF/Word2Vec, we MUST fit on the corpus first
1250        if matches!(model, crate::persistence::settings::EmbeddingModel::TfIdf | crate::persistence::settings::EmbeddingModel::Word2Vec) {
1251            let texts: Vec<String> = db.nodes.values()
1252                .map(|n| {
1253                    let mut parts = vec![n.label.clone()];
1254                    parts.extend(n.metadata.values().cloned());
1255                    parts.join(" ")
1256                })
1257                .collect();
1258            embedder.fit(&texts);
1259        }
1260        
1261        let query_embedding = embedder.embed(query_text);
1262        
1263        // Always generate fresh embeddings for comparison to ensure consistency
1264        let mut neighbors: Vec<NearestNeighbor> = db.nodes.iter()
1265            .filter_map(|(id, node)| {
1266                let mut parts = vec![node.label.clone()];
1267                parts.extend(node.metadata.values().cloned());
1268                let text = parts.join(" ");
1269                let emb = embedder.embed(&text);
1270                let sim = cosine_similarity(&query_embedding, &emb);
1271                if sim >= threshold {
1272                    Some(NearestNeighbor { node_id: *id, similarity: sim, distance: l2_distance(&query_embedding, &emb) })
1273                } else {
1274                    None
1275                }
1276            })
1277            .collect();
1278        neighbors.sort_by(|a, b| b.similarity.partial_cmp(&a.similarity).unwrap_or(std::cmp::Ordering::Equal));
1279        let results = neighbors;
1280        
1281        let rows: Vec<QueryResultRow> = results.iter()
1282            .filter_map(|nn| {
1283                db.get_node(nn.node_id).map(|n| {
1284                    let mut meta = n.metadata.clone();
1285                    meta.insert("_similarity".to_string(), format!("{:.4}", nn.similarity));
1286                    meta.insert("_distance".to_string(), format!("{:.4}", nn.distance));
1287                    QueryResultRow::Node { id: nn.node_id, label: n.label.clone(), metadata: meta }
1288                })
1289            })
1290            .collect();
1291        Ok((rows, 0, 0, false))
1292    } else {
1293        Err(anyhow!("unknown procedure: {}", rest))
1294    }
1295}
1296
1297/// Extract arguments from a CALL procedure invocation like "algo.pageRank(arg1, arg2)"
1298/// Properly handles quoted strings containing commas or spaces.
1299fn extract_call_args(s: &str) -> Result<Vec<String>> {
1300    if let Some(start) = s.find('(') {
1301        if let Some(end) = s.rfind(')') {
1302            let inner = s[start+1..end].trim();
1303            if inner.is_empty() {
1304                return Ok(Vec::new());
1305            }
1306            
1307            // Parse arguments respecting quoted strings
1308            let mut args = Vec::new();
1309            let mut current = String::new();
1310            let mut in_quote: Option<char> = None;
1311            
1312            for c in inner.chars() {
1313                match c {
1314                    '"' | '\'' => {
1315                        if in_quote == Some(c) {
1316                            // End of quoted string
1317                            in_quote = None;
1318                        } else if in_quote.is_none() {
1319                            // Start of quoted string
1320                            in_quote = Some(c);
1321                        } else {
1322                            // Different quote inside a quoted string
1323                            current.push(c);
1324                        }
1325                    }
1326                    ',' if in_quote.is_none() => {
1327                        // Argument separator outside quotes
1328                        let arg = current.trim().to_string();
1329                        if !arg.is_empty() {
1330                            args.push(arg);
1331                        }
1332                        current.clear();
1333                    }
1334                    _ => {
1335                        current.push(c);
1336                    }
1337                }
1338            }
1339            
1340            // Don't forget the last argument
1341            let arg = current.trim().to_string();
1342            if !arg.is_empty() {
1343                args.push(arg);
1344            }
1345            
1346            return Ok(args);
1347        }
1348    }
1349    Ok(Vec::new())
1350}
1351
1352/// Re-embed all nodes using the specified embedding model.
1353/// Only clears and rebuilds embeddings for the specified model, preserving other models' embeddings.
1354pub fn reembed_with_model(db: &GraphDatabase, model: crate::persistence::settings::EmbeddingModel) -> Result<String> {
1355    use crate::semantic::embeddings::UnifiedEmbedder;
1356    
1357    let node_count = db.nodes.len();
1358    if node_count == 0 {
1359        return Ok("No nodes to embed".to_string());
1360    }
1361
1362    // Create embedder for the specified model
1363    let mut embedder = UnifiedEmbedder::new(model)
1364        .map_err(|e| anyhow!("Failed to initialize embedder: {}", e))?;
1365
1366    // Collect all text from nodes
1367    let mut texts: Vec<String> = Vec::new();
1368    let mut node_ids: Vec<NodeId> = Vec::new();
1369    
1370    for (id, node) in &db.nodes {
1371        let mut text_parts = vec![node.label.clone()];
1372        for value in node.metadata.values() {
1373            text_parts.push(value.clone());
1374        }
1375        texts.push(text_parts.join(" "));
1376        node_ids.push(*id);
1377    }
1378
1379    // Fit the embedder (for TF-IDF models)
1380    embedder.fit(&texts);
1381
1382    // Generate embeddings
1383    let embeddings = embedder.embed_batch(&texts);
1384    
1385    let model_type = embedder.model_type_str();
1386    
1387    // Store embeddings in SQLite if available (using per-model tables)
1388    if let Ok(mut storage) = get_embedding_storage() {
1389        // Clear only this model's embeddings (not all embeddings)
1390        let _ = storage.clear_model_embeddings(model_type);
1391        
1392        // Save model state (for TF-IDF) with model-specific key
1393        if let Some(state) = embedder.serialize_state() {
1394            let state_key = format!("{}_state", model_type);
1395            let _ = storage.save_embedding_model_state(&state_key, &state);
1396        }
1397        
1398        // Batch save embeddings for better performance
1399        let embedding_pairs: Vec<(NodeId, Vec<f32>)> = node_ids.iter()
1400            .zip(embeddings.iter())
1401            .map(|(id, emb)| (*id, emb.clone()))
1402            .collect();
1403        let _ = storage.save_model_embeddings_batch(model_type, &embedding_pairs);
1404    }
1405
1406    let model_name = match model {
1407        crate::persistence::settings::EmbeddingModel::TfIdf => "TF-IDF",
1408        crate::persistence::settings::EmbeddingModel::Word2Vec => "Word2Vec",
1409        crate::persistence::settings::EmbeddingModel::Onnx => "ONNX (all-MiniLM-L6-v2)",
1410    };
1411
1412    Ok(format!("Re-embedded {} nodes using {}", node_count, model_name))
1413}
1414
1415/// Get SQLite storage for embeddings
1416fn get_embedding_storage() -> Result<crate::persistence::sqlite_backend::SqliteStorage> {
1417    let path = crate::persistence::persist::active_sqlite_path();
1418    crate::persistence::sqlite_backend::SqliteStorage::open(&path)
1419        .map_err(|e| anyhow!("Failed to open SQLite storage: {}", e))
1420}