Skip to main content

reddb_server/storage/query/unified/
executor.rs

1use std::collections::{HashMap, HashSet, VecDeque};
2use std::sync::Arc;
3
4use super::{
5    ExecutionError, GraphPath, MatchedEdge, MatchedNode, QueryStats, UnifiedRecord, UnifiedResult,
6};
7use crate::storage::engine::graph_store::{GraphStore, Namespace, StoredNode};
8use crate::storage::engine::graph_table_index::GraphTableIndex;
9use crate::storage::query::ast::{
10    CompareOp, EdgeDirection, EdgePattern, FieldRef, Filter, GraphPattern, GraphQuery, JoinQuery,
11    JoinType, NodePattern, NodeSelector, PathQuery, Projection, QueryExpr, TableQuery,
12};
13use crate::storage::query::sql_lowering::{
14    effective_graph_filter, effective_graph_projections, effective_path_filter,
15};
16use crate::storage::schema::Value;
17
18pub type EdgeProperties = HashMap<(String, String, String), HashMap<String, Value>>;
19
20pub struct UnifiedExecutor {
21    /// Graph storage
22    graph: Arc<GraphStore>,
23    /// Graph-table index for joins
24    index: Arc<GraphTableIndex>,
25    /// Optional node properties loaded from the unified entity store
26    node_properties: Arc<HashMap<String, HashMap<String, Value>>>,
27    /// Optional edge properties loaded from the unified entity store, keyed by
28    /// `(from, canonical_label, to)` because GraphStore adjacency omits edge ids.
29    edge_properties: Arc<EdgeProperties>,
30}
31
32impl UnifiedExecutor {
33    /// Create a new executor
34    pub fn new(graph: Arc<GraphStore>, index: Arc<GraphTableIndex>) -> Self {
35        Self::new_with_node_properties(graph, index, HashMap::new())
36    }
37
38    /// Create a new executor with node properties
39    pub fn new_with_node_properties(
40        graph: Arc<GraphStore>,
41        index: Arc<GraphTableIndex>,
42        node_properties: HashMap<String, HashMap<String, Value>>,
43    ) -> Self {
44        Self::new_with_graph_properties(graph, index, node_properties, HashMap::new())
45    }
46
47    pub fn new_with_graph_properties(
48        graph: Arc<GraphStore>,
49        index: Arc<GraphTableIndex>,
50        node_properties: HashMap<String, HashMap<String, Value>>,
51        edge_properties: EdgeProperties,
52    ) -> Self {
53        Self {
54            graph,
55            index,
56            node_properties: Arc::new(node_properties),
57            edge_properties: Arc::new(edge_properties),
58        }
59    }
60
61    fn matched_node(&self, node: &StoredNode) -> MatchedNode {
62        let mut node = MatchedNode::from_stored(node);
63        if let Some(properties) = self.node_properties.get(&node.id) {
64            node.properties = properties.clone();
65        }
66        node
67    }
68
69    fn matched_edge(
70        &self,
71        source: &str,
72        edge_label: &str,
73        target: &str,
74        weight: f32,
75    ) -> MatchedEdge {
76        let mut edge = MatchedEdge::from_tuple(source, edge_label, target, weight);
77        if let Some(properties) = self.edge_properties.get(&(
78            source.to_string(),
79            edge_label.to_string(),
80            target.to_string(),
81        )) {
82            edge.properties = properties.clone();
83        }
84        edge
85    }
86
87    fn node_stored_property_value(node: &StoredNode, property: &str) -> Option<Value> {
88        if let Some(properties) = match property {
89            "id" => Some(Value::text(node.id.clone())),
90            "label" => Some(Value::text(node.label.clone())),
91            "type" | "node_type" => Some(Value::text(node.node_type.as_str().to_string())),
92            _ => None,
93        } {
94            return Some(properties);
95        }
96
97        None
98    }
99
100    fn node_property_value(&self, node: &StoredNode, property: &str) -> Option<Value> {
101        self.node_properties
102            .get(&node.id)
103            .and_then(|properties| properties.get(property).cloned())
104            .or_else(|| Self::node_stored_property_value(node, property))
105    }
106
107    fn node_property_value_by_id(&self, node_id: &str, property: &str) -> Option<Value> {
108        if property == "id" {
109            return Some(Value::text(node_id.to_string()));
110        }
111        if property == "label" {
112            if let Some(node) = self.graph.get_node(node_id).as_ref() {
113                return Some(Value::text(node.label.clone()));
114            }
115            return None;
116        }
117        if property == "type" || property == "node_type" {
118            return self
119                .graph
120                .get_node(node_id)
121                .map(|node| Value::text(node.node_type.as_str().to_string()));
122        }
123        self.node_properties
124            .get(node_id)
125            .and_then(|properties| properties.get(property).cloned())
126    }
127
128    /// Execute a query directly against a graph reference
129    ///
130    /// This is a convenience method for simple graph-only queries.
131    /// For table joins, use `new()` with proper Arc ownership.
132    pub fn execute_on(
133        graph: &GraphStore,
134        query: &QueryExpr,
135    ) -> Result<UnifiedResult, ExecutionError> {
136        Self::execute_on_with_node_properties(graph, query, HashMap::new())
137    }
138
139    /// Execute a query directly against a graph reference with custom node properties
140    pub fn execute_on_with_node_properties(
141        graph: &GraphStore,
142        query: &QueryExpr,
143        node_properties: HashMap<String, HashMap<String, Value>>,
144    ) -> Result<UnifiedResult, ExecutionError> {
145        Self::execute_on_with_graph_properties(graph, query, node_properties, HashMap::new())
146    }
147
148    pub fn execute_on_with_graph_properties(
149        graph: &GraphStore,
150        query: &QueryExpr,
151        node_properties: HashMap<String, HashMap<String, Value>>,
152        edge_properties: EdgeProperties,
153    ) -> Result<UnifiedResult, ExecutionError> {
154        let temp = Self::new_with_graph_properties(
155            Arc::new(GraphStore::new()),
156            Arc::new(GraphTableIndex::new()),
157            node_properties,
158            edge_properties,
159        );
160
161        match query {
162            QueryExpr::Graph(q) => temp.exec_graph_on(graph, q),
163            QueryExpr::Path(q) => temp.exec_path_on(graph, q),
164            QueryExpr::Table(_) => Err(ExecutionError::new(
165                "Table queries require proper executor initialization",
166            )),
167            QueryExpr::Join(_) => Err(ExecutionError::new(
168                "Join queries require proper executor initialization",
169            )),
170            QueryExpr::Vector(_) => Err(ExecutionError::new(
171                "Vector queries require VectorStore integration",
172            )),
173            QueryExpr::Hybrid(_) => Err(ExecutionError::new(
174                "Hybrid queries require VectorStore integration",
175            )),
176            QueryExpr::Insert(_)
177            | QueryExpr::Update(_)
178            | QueryExpr::Delete(_)
179            | QueryExpr::CreateTable(_)
180            | QueryExpr::CreateCollection(_)
181            | QueryExpr::CreateVector(_)
182            | QueryExpr::DropTable(_)
183            | QueryExpr::DropGraph(_)
184            | QueryExpr::DropVector(_)
185            | QueryExpr::DropDocument(_)
186            | QueryExpr::DropKv(_)
187            | QueryExpr::DropCollection(_)
188            | QueryExpr::Truncate(_)
189            | QueryExpr::AlterTable(_)
190            | QueryExpr::CreateVcsRef(_)
191            | QueryExpr::DropVcsRef(_)
192            | QueryExpr::VcsCommand(_)
193            | QueryExpr::GraphCommand(_)
194            | QueryExpr::SearchCommand(_)
195            | QueryExpr::CreateIndex(_)
196            | QueryExpr::DropIndex(_)
197            | QueryExpr::ProbabilisticCommand(_)
198            | QueryExpr::Ask(_)
199            | QueryExpr::SetConfig { .. }
200            | QueryExpr::ShowConfig { .. }
201            | QueryExpr::SetSecret { .. }
202            | QueryExpr::DeleteSecret { .. }
203            | QueryExpr::ShowSecrets { .. }
204            | QueryExpr::SetTenant(_)
205            | QueryExpr::ShowTenant
206            | QueryExpr::CreateTimeSeries(_)
207            | QueryExpr::CreateMetric(_)
208            | QueryExpr::AlterMetric(_)
209            | QueryExpr::CreateSlo(_)
210            | QueryExpr::DropTimeSeries(_)
211            | QueryExpr::CreateQueue(_)
212            | QueryExpr::AlterQueue(_)
213            | QueryExpr::DropQueue(_)
214            | QueryExpr::QueueSelect(_)
215            | QueryExpr::QueueCommand(_)
216            | QueryExpr::KvCommand(_)
217            | QueryExpr::ConfigCommand(_)
218            | QueryExpr::CreateTree(_)
219            | QueryExpr::DropTree(_)
220            | QueryExpr::TreeCommand(_)
221            | QueryExpr::ExplainAlter(_)
222            | QueryExpr::TransactionControl(_)
223            | QueryExpr::MaintenanceCommand(_)
224            | QueryExpr::CreateSchema(_)
225            | QueryExpr::DropSchema(_)
226            | QueryExpr::CreateSequence(_)
227            | QueryExpr::DropSequence(_)
228            | QueryExpr::CopyFrom(_)
229            | QueryExpr::CreateView(_)
230            | QueryExpr::DropView(_)
231            | QueryExpr::RefreshMaterializedView(_)
232            | QueryExpr::CreatePolicy(_)
233            | QueryExpr::DropPolicy(_)
234            | QueryExpr::CreateServer(_)
235            | QueryExpr::DropServer(_)
236            | QueryExpr::CreateForeignTable(_)
237            | QueryExpr::DropForeignTable(_)
238            | QueryExpr::Grant(_)
239            | QueryExpr::Revoke(_)
240            | QueryExpr::AlterUser(_)
241            | QueryExpr::CreateUser(_)
242            | QueryExpr::CreateIamPolicy { .. }
243            | QueryExpr::DropIamPolicy { .. }
244            | QueryExpr::AttachPolicy { .. }
245            | QueryExpr::DetachPolicy { .. }
246            | QueryExpr::ShowPolicies { .. }
247            | QueryExpr::ShowEffectivePermissions { .. }
248            | QueryExpr::RankOf(_)
249            | QueryExpr::ApproxRankOf(_)
250            | QueryExpr::RankRange(_)
251            | QueryExpr::SimulatePolicy { .. }
252            | QueryExpr::LintPolicy { .. }
253            | QueryExpr::MigratePolicyMode { .. }
254            | QueryExpr::CreateMigration(_)
255            | QueryExpr::ApplyMigration(_)
256            | QueryExpr::RollbackMigration(_)
257            | QueryExpr::ExplainMigration(_)
258            | QueryExpr::EventsBackfill(_)
259            | QueryExpr::EventsBackfillStatus { .. } => Err(ExecutionError::new(
260                "DML/DDL/Command statements are not supported in UnifiedExecutor",
261            )),
262        }
263    }
264
265    /// Execute a graph query on a specific graph reference
266    ///
267    /// Runtime `MATCH` execution uses the passed `graph` because the
268    /// runtime materialises a fresh `GraphStore` per query, so
269    /// `self.graph` is empty here.
270    fn exec_graph_on(
271        &self,
272        graph: &GraphStore,
273        query: &GraphQuery,
274    ) -> Result<UnifiedResult, ExecutionError> {
275        let mut result = UnifiedResult::empty();
276        let mut stats = QueryStats::default();
277        let effective_filter = effective_graph_filter(query);
278        let effective_projections = effective_graph_projections(query);
279
280        let matches = self.match_pattern_on(graph, &query.pattern, &mut stats)?;
281
282        for matched in matches {
283            if Self::graph_limit_reached(result.records.len(), query.limit) {
284                break;
285            }
286            if !self.eval_filter_on_match(&effective_filter, &matched) {
287                continue;
288            }
289            let record = self.project_match(&matched, &effective_projections);
290            result.records.push(record);
291        }
292
293        result.stats = stats;
294        Ok(result)
295    }
296
297    /// Execute a path query on a specific graph reference
298    fn exec_path_on(
299        &self,
300        graph: &GraphStore,
301        query: &PathQuery,
302    ) -> Result<UnifiedResult, ExecutionError> {
303        let mut result = UnifiedResult::empty();
304
305        // BFS to find paths
306        let mut queue: VecDeque<(String, GraphPath)> = VecDeque::new();
307        let mut visited: HashSet<String> = HashSet::new();
308
309        // Get start node IDs from selector
310        let start_ids = self.resolve_selector_on(graph, &query.from);
311
312        for start in start_ids {
313            queue.push_back((start.clone(), GraphPath::start(&start)));
314            visited.insert(start);
315        }
316
317        let target_ids: HashSet<_> = self
318            .resolve_selector_on(graph, &query.to)
319            .into_iter()
320            .collect();
321        let max_len = query.max_length as usize;
322
323        while let Some((current, path)) = queue.pop_front() {
324            if path.len() > max_len {
325                continue;
326            }
327
328            if target_ids.contains(&current) && !path.is_empty() {
329                let mut record = UnifiedRecord::new();
330                record.paths.push(path.clone());
331                result.records.push(record);
332                continue;
333            }
334
335            // Expand to neighbors
336            for (edge_type, neighbor, weight) in graph.outgoing_edges(&current) {
337                // Check via filter — strings, compared against the legacy
338                // edge enum's canonical name.
339                if !query.via.is_empty() && !query.via.iter().any(|via| via == edge_type.as_str()) {
340                    continue;
341                }
342
343                if !visited.contains(&neighbor) {
344                    visited.insert(neighbor.clone());
345                    let edge = MatchedEdge::from_tuple(&current, edge_type, &neighbor, weight);
346                    let new_path = path.extend(edge, &neighbor);
347                    queue.push_back((neighbor, new_path));
348                }
349            }
350        }
351
352        result.stats.edges_scanned = visited.len() as u64;
353        Ok(result)
354    }
355
356    /// Resolve a node selector to IDs on a specific graph
357    fn resolve_selector_on(&self, graph: &GraphStore, selector: &NodeSelector) -> Vec<String> {
358        match selector {
359            NodeSelector::ById(id) => vec![id.clone()],
360            NodeSelector::ByType {
361                node_label,
362                filter: _,
363            } => graph
364                .nodes_with_category(node_label)
365                .into_iter()
366                .map(|n| n.id)
367                .collect(),
368            NodeSelector::ByRow { table, row_id } => {
369                if let Some((table_id, row_id)) = match (table.as_str().parse::<u16>(), *row_id) {
370                    (Ok(table_id), row_id) => Some((table_id, row_id)),
371                    _ => None,
372                } {
373                    let mut ids = Vec::new();
374
375                    // Fast path: query the bidirectional graph-table index first
376                    if let Some(node_id) = self.index.get_node_for_row(table_id, row_id) {
377                        ids.push(node_id);
378                    }
379
380                    // Fallback path: for callers that don't register index mappings yet,
381                    // scan graph nodes directly by table_ref row linkage.
382                    if ids.is_empty() {
383                        ids.extend(graph.iter_nodes().filter_map(|node| {
384                            let table_ref = node.table_ref?;
385                            if table_ref.table_id == table_id && table_ref.row_id == row_id {
386                                Some(node.id)
387                            } else {
388                                None
389                            }
390                        }));
391                    }
392
393                    ids
394                } else {
395                    Vec::new()
396                }
397            }
398        }
399    }
400
401    /// Execute a query
402    pub fn execute(&self, query: &QueryExpr) -> Result<UnifiedResult, ExecutionError> {
403        match query {
404            QueryExpr::Table(q) => self.exec_table(q),
405            QueryExpr::Graph(q) => self.exec_graph(q),
406            QueryExpr::Join(q) => self.exec_join(q),
407            QueryExpr::Path(q) => self.exec_path(q),
408            QueryExpr::Vector(_) => {
409                // Vector execution requires VectorStore integration
410                // This will be implemented in the VectorExecutor
411                Err(ExecutionError::new(
412                    "Vector queries not yet implemented in UnifiedExecutor",
413                ))
414            }
415            QueryExpr::Hybrid(_) => {
416                // Hybrid execution requires both structured and vector execution
417                // This will be implemented in the HybridExecutor
418                Err(ExecutionError::new(
419                    "Hybrid queries not yet implemented in UnifiedExecutor",
420                ))
421            }
422            QueryExpr::Insert(_)
423            | QueryExpr::Update(_)
424            | QueryExpr::Delete(_)
425            | QueryExpr::CreateTable(_)
426            | QueryExpr::CreateCollection(_)
427            | QueryExpr::CreateVector(_)
428            | QueryExpr::DropTable(_)
429            | QueryExpr::DropGraph(_)
430            | QueryExpr::DropVector(_)
431            | QueryExpr::DropDocument(_)
432            | QueryExpr::DropKv(_)
433            | QueryExpr::DropCollection(_)
434            | QueryExpr::Truncate(_)
435            | QueryExpr::AlterTable(_)
436            | QueryExpr::CreateVcsRef(_)
437            | QueryExpr::DropVcsRef(_)
438            | QueryExpr::VcsCommand(_)
439            | QueryExpr::GraphCommand(_)
440            | QueryExpr::SearchCommand(_)
441            | QueryExpr::CreateIndex(_)
442            | QueryExpr::DropIndex(_)
443            | QueryExpr::ProbabilisticCommand(_)
444            | QueryExpr::Ask(_)
445            | QueryExpr::SetConfig { .. }
446            | QueryExpr::ShowConfig { .. }
447            | QueryExpr::SetSecret { .. }
448            | QueryExpr::DeleteSecret { .. }
449            | QueryExpr::ShowSecrets { .. }
450            | QueryExpr::SetTenant(_)
451            | QueryExpr::ShowTenant
452            | QueryExpr::CreateTimeSeries(_)
453            | QueryExpr::CreateMetric(_)
454            | QueryExpr::AlterMetric(_)
455            | QueryExpr::CreateSlo(_)
456            | QueryExpr::DropTimeSeries(_)
457            | QueryExpr::CreateQueue(_)
458            | QueryExpr::AlterQueue(_)
459            | QueryExpr::DropQueue(_)
460            | QueryExpr::QueueSelect(_)
461            | QueryExpr::QueueCommand(_)
462            | QueryExpr::KvCommand(_)
463            | QueryExpr::ConfigCommand(_)
464            | QueryExpr::CreateTree(_)
465            | QueryExpr::DropTree(_)
466            | QueryExpr::TreeCommand(_)
467            | QueryExpr::ExplainAlter(_)
468            | QueryExpr::TransactionControl(_)
469            | QueryExpr::MaintenanceCommand(_)
470            | QueryExpr::CreateSchema(_)
471            | QueryExpr::DropSchema(_)
472            | QueryExpr::CreateSequence(_)
473            | QueryExpr::DropSequence(_)
474            | QueryExpr::CopyFrom(_)
475            | QueryExpr::CreateView(_)
476            | QueryExpr::DropView(_)
477            | QueryExpr::RefreshMaterializedView(_)
478            | QueryExpr::CreatePolicy(_)
479            | QueryExpr::DropPolicy(_)
480            | QueryExpr::CreateServer(_)
481            | QueryExpr::DropServer(_)
482            | QueryExpr::CreateForeignTable(_)
483            | QueryExpr::DropForeignTable(_)
484            | QueryExpr::Grant(_)
485            | QueryExpr::Revoke(_)
486            | QueryExpr::AlterUser(_)
487            | QueryExpr::CreateUser(_)
488            | QueryExpr::CreateIamPolicy { .. }
489            | QueryExpr::DropIamPolicy { .. }
490            | QueryExpr::AttachPolicy { .. }
491            | QueryExpr::DetachPolicy { .. }
492            | QueryExpr::ShowPolicies { .. }
493            | QueryExpr::ShowEffectivePermissions { .. }
494            | QueryExpr::RankOf(_)
495            | QueryExpr::ApproxRankOf(_)
496            | QueryExpr::RankRange(_)
497            | QueryExpr::SimulatePolicy { .. }
498            | QueryExpr::LintPolicy { .. }
499            | QueryExpr::MigratePolicyMode { .. }
500            | QueryExpr::CreateMigration(_)
501            | QueryExpr::ApplyMigration(_)
502            | QueryExpr::RollbackMigration(_)
503            | QueryExpr::ExplainMigration(_)
504            | QueryExpr::EventsBackfill(_)
505            | QueryExpr::EventsBackfillStatus { .. } => Err(ExecutionError::new(
506                "DML/DDL/Command statements are not supported in UnifiedExecutor",
507            )),
508        }
509    }
510
511    /// Execute a table query
512    /// Note: Without actual table storage access, this returns empty result.
513    /// In production, this would integrate with the table storage engine.
514    fn exec_table(&self, _query: &TableQuery) -> Result<UnifiedResult, ExecutionError> {
515        // Table execution requires table storage integration
516        // For now, return empty result
517        Ok(UnifiedResult::empty())
518    }
519
520    /// Execute a graph query
521    fn exec_graph(&self, query: &GraphQuery) -> Result<UnifiedResult, ExecutionError> {
522        let mut result = UnifiedResult::empty();
523        let mut stats = QueryStats::default();
524
525        // Match the pattern
526        let matches = self.match_pattern(&query.pattern, &mut stats)?;
527
528        let effective_filter = effective_graph_filter(query);
529        let effective_projections = effective_graph_projections(query);
530
531        for matched in matches {
532            if Self::graph_limit_reached(result.records.len(), query.limit) {
533                break;
534            }
535            if !self.eval_filter_on_match(&effective_filter, &matched) {
536                continue;
537            }
538            let record = self.project_match(&matched, &effective_projections);
539            result.push(record);
540        }
541
542        result.stats = stats;
543        Ok(result)
544    }
545
546    fn graph_limit_reached(row_count: usize, limit: Option<u64>) -> bool {
547        limit.is_some_and(|limit| row_count as u64 >= limit)
548    }
549
550    /// Match a graph pattern
551    fn match_pattern(
552        &self,
553        pattern: &GraphPattern,
554        stats: &mut QueryStats,
555    ) -> Result<Vec<PatternMatch>, ExecutionError> {
556        self.match_pattern_on(self.graph.as_ref(), pattern, stats)
557    }
558
559    fn match_pattern_on(
560        &self,
561        graph: &GraphStore,
562        pattern: &GraphPattern,
563        stats: &mut QueryStats,
564    ) -> Result<Vec<PatternMatch>, ExecutionError> {
565        if pattern.nodes.is_empty() {
566            return Ok(Vec::new());
567        }
568
569        // Start with first node pattern
570        let first = &pattern.nodes[0];
571        let mut matches = self.find_matching_nodes_on(graph, first, stats)?;
572
573        // Extend matches for each edge pattern
574        for edge_pattern in &pattern.edges {
575            matches =
576                self.extend_matches_on(graph, matches, edge_pattern, &pattern.nodes, stats)?;
577        }
578
579        Ok(matches)
580    }
581
582    /// Find nodes matching a pattern
583    fn find_matching_nodes_on(
584        &self,
585        graph: &GraphStore,
586        pattern: &NodePattern,
587        stats: &mut QueryStats,
588    ) -> Result<Vec<PatternMatch>, ExecutionError> {
589        let mut matches = Vec::new();
590
591        // Iterate through all nodes
592        for node in graph.iter_nodes() {
593            stats.nodes_scanned += 1;
594
595            // Check label filter (resolved against the graph's registry).
596            if let Some(ref expected) = pattern.node_label {
597                let expected_id = graph.registry.lookup(Namespace::Node, expected);
598                match expected_id {
599                    Some(id) if id == node.label_id => {}
600                    _ => continue,
601                }
602            }
603
604            // Check property filters
605            let mut match_props = true;
606            for prop_filter in &pattern.properties {
607                if !self.eval_node_property_filter(&node, prop_filter) {
608                    match_props = false;
609                    break;
610                }
611            }
612
613            if match_props {
614                let mut pm = PatternMatch::new();
615                pm.nodes
616                    .insert(pattern.alias.clone(), self.matched_node(&node));
617                matches.push(pm);
618            }
619        }
620
621        Ok(matches)
622    }
623
624    /// Extend matches by following an edge pattern
625    fn extend_matches_on(
626        &self,
627        graph: &GraphStore,
628        matches: Vec<PatternMatch>,
629        edge_pattern: &EdgePattern,
630        node_patterns: &[NodePattern],
631        stats: &mut QueryStats,
632    ) -> Result<Vec<PatternMatch>, ExecutionError> {
633        let mut extended = Vec::new();
634
635        // Find the target node pattern
636        let target_pattern = node_patterns
637            .iter()
638            .find(|n| n.alias == edge_pattern.to)
639            .ok_or_else(|| {
640                ExecutionError::new(format!(
641                    "Node alias '{}' not found in pattern",
642                    edge_pattern.to
643                ))
644            })?;
645
646        for pm in matches {
647            // Get the source node
648            let source_node = pm.nodes.get(&edge_pattern.from).ok_or_else(|| {
649                ExecutionError::new(format!(
650                    "Source node '{}' not found in match",
651                    edge_pattern.from
652                ))
653            })?;
654
655            // Get adjacent edges. The tuple is (edge_label, peer_id, weight,
656            // is_outgoing) — we union outgoing and incoming sets and tag
657            // direction so downstream filters know which side the edge came from.
658            let edges: Vec<_> = match edge_pattern.direction {
659                EdgeDirection::Outgoing => {
660                    graph
661                        .outgoing_edges(&source_node.id)
662                        .into_iter()
663                        .map(|(et, target, w)| (et, target, w, true)) // is_outgoing = true
664                        .collect()
665                }
666                EdgeDirection::Incoming => {
667                    graph
668                        .incoming_edges(&source_node.id)
669                        .into_iter()
670                        .map(|(et, source, w)| (et, source, w, false)) // is_outgoing = false
671                        .collect()
672                }
673                EdgeDirection::Both => {
674                    let mut all: Vec<_> = graph
675                        .outgoing_edges(&source_node.id)
676                        .into_iter()
677                        .map(|(et, target, w)| (et, target, w, true))
678                        .collect();
679                    all.extend(
680                        graph
681                            .incoming_edges(&source_node.id)
682                            .into_iter()
683                            .map(|(et, source, w)| (et, source, w, false)),
684                    );
685                    all
686                }
687            };
688
689            for (etype, other_id, weight, is_outgoing) in edges {
690                stats.edges_scanned += 1;
691
692                // Check edge label filter — direct string compare against the
693                // canonical label that the storage layer hands back.
694                if let Some(ref expected) = edge_pattern.edge_label {
695                    if etype.as_str() != expected.as_str() {
696                        continue;
697                    }
698                }
699
700                // The target is the other node
701                let target_id = &other_id;
702
703                if let Some(target_node) = graph.get_node(target_id) {
704                    // Check target node label filter (registry resolution).
705                    if let Some(ref expected) = target_pattern.node_label {
706                        let expected_id = graph.registry.lookup(Namespace::Node, expected);
707                        match expected_id {
708                            Some(id) if id == target_node.label_id => {}
709                            _ => continue,
710                        }
711                    }
712
713                    // Check target property filters
714                    let mut match_props = true;
715                    for prop_filter in &target_pattern.properties {
716                        if !self.eval_node_property_filter(&target_node, prop_filter) {
717                            match_props = false;
718                            break;
719                        }
720                    }
721
722                    if match_props {
723                        let mut new_pm = pm.clone();
724                        new_pm.nodes.insert(
725                            target_pattern.alias.clone(),
726                            self.matched_node(&target_node),
727                        );
728                        if let Some(ref alias) = edge_pattern.alias {
729                            // Create edge with proper from/to direction
730                            let edge = if is_outgoing {
731                                self.matched_edge(&source_node.id, &etype, target_id, weight)
732                            } else {
733                                self.matched_edge(target_id, &etype, &source_node.id, weight)
734                            };
735                            new_pm.edges.insert(alias.clone(), edge);
736                        }
737                        extended.push(new_pm);
738                    }
739                }
740            }
741        }
742
743        Ok(extended)
744    }
745
746    /// Evaluate a property filter on a stored node
747    fn eval_node_property_filter(
748        &self,
749        node: &StoredNode,
750        filter: &crate::storage::query::ast::PropertyFilter,
751    ) -> bool {
752        let Some(value) = self.node_property_value(node, filter.name.as_str()) else {
753            return false;
754        };
755
756        self.compare_values(&value, &filter.op, &filter.value)
757    }
758
759    /// Compare two values with an operator
760    fn compare_values(&self, left: &Value, op: &CompareOp, right: &Value) -> bool {
761        match op {
762            CompareOp::Eq => left == right,
763            CompareOp::Ne => left != right,
764            CompareOp::Lt => self.value_lt(left, right),
765            CompareOp::Le => self.value_lt(left, right) || left == right,
766            CompareOp::Gt => self.value_lt(right, left),
767            CompareOp::Ge => self.value_lt(right, left) || left == right,
768        }
769    }
770
771    /// Less-than comparison for values
772    fn value_lt(&self, left: &Value, right: &Value) -> bool {
773        match (left, right) {
774            (Value::Integer(a), Value::Integer(b)) => a < b,
775            (Value::Float(a), Value::Float(b)) => a < b,
776            (Value::Integer(a), Value::Float(b)) => (*a as f64) < *b,
777            (Value::Float(a), Value::Integer(b)) => *a < (*b as f64),
778            (Value::Text(a), Value::Text(b)) => a < b,
779            (Value::Timestamp(a), Value::Timestamp(b)) => a < b,
780            _ => false,
781        }
782    }
783
784    /// Evaluate a filter on a pattern match
785    fn eval_filter_on_match(&self, filter: &Option<Filter>, matched: &PatternMatch) -> bool {
786        match filter {
787            None => true,
788            Some(f) => self.eval_filter(f, matched),
789        }
790    }
791
792    /// Evaluate a filter expression
793    fn eval_filter(&self, filter: &Filter, matched: &PatternMatch) -> bool {
794        match filter {
795            Filter::Compare { field, op, value } => {
796                let actual = self.get_field_value(field, matched);
797                match actual {
798                    Some(v) => self.compare_values(&v, op, value),
799                    None => false,
800                }
801            }
802            Filter::CompareFields { left, op, right } => {
803                let l = self.get_field_value(left, matched);
804                let r = self.get_field_value(right, matched);
805                match (l, r) {
806                    (Some(lv), Some(rv)) => self.compare_values(&lv, op, &rv),
807                    _ => false,
808                }
809            }
810            Filter::CompareExpr { .. } => {
811                // The unified graph-level executor doesn't yet carry
812                // the `UnifiedRecord` context that expr_eval needs.
813                // Return false (conservative — the predicate is
814                // treated as unmatched) until the executor is
815                // upgraded in Week 5.
816                false
817            }
818            Filter::And(left, right) => {
819                self.eval_filter(left, matched) && self.eval_filter(right, matched)
820            }
821            Filter::Or(left, right) => {
822                self.eval_filter(left, matched) || self.eval_filter(right, matched)
823            }
824            Filter::Not(inner) => !self.eval_filter(inner, matched),
825            Filter::IsNull(field) => self.get_field_value(field, matched).is_none(),
826            Filter::IsNotNull(field) => self.get_field_value(field, matched).is_some(),
827            Filter::In { field, values } => match self.get_field_value(field, matched) {
828                Some(v) => values.contains(&v),
829                None => false,
830            },
831            Filter::Between { field, low, high } => match self.get_field_value(field, matched) {
832                Some(v) => !self.value_lt(&v, low) && !self.value_lt(high, &v),
833                None => false,
834            },
835            Filter::Like { field, pattern } => match self.get_field_value(field, matched) {
836                Some(Value::Text(s)) => self.match_like(&s, pattern),
837                _ => false,
838            },
839            Filter::StartsWith { field, prefix } => match self.get_field_value(field, matched) {
840                Some(Value::Text(s)) => s.starts_with(prefix),
841                _ => false,
842            },
843            Filter::EndsWith { field, suffix } => match self.get_field_value(field, matched) {
844                Some(Value::Text(s)) => s.ends_with(suffix),
845                _ => false,
846            },
847            Filter::Contains { field, substring } => match self.get_field_value(field, matched) {
848                Some(Value::Text(s)) => s.contains(substring),
849                _ => false,
850            },
851        }
852    }
853
854    /// Simple LIKE pattern matching (% and _ wildcards)
855    fn match_like(&self, text: &str, pattern: &str) -> bool {
856        // Simple implementation: convert % to .* and _ to .
857        let regex_pattern = pattern.replace('%', ".*").replace('_', ".");
858
859        // Basic match without regex (for simplicity)
860        if pattern.starts_with('%') && pattern.ends_with('%') {
861            let inner = &pattern[1..pattern.len() - 1];
862            text.contains(inner)
863        } else if let Some(suffix) = pattern.strip_prefix('%') {
864            text.ends_with(suffix)
865        } else if let Some(prefix) = pattern.strip_suffix('%') {
866            text.starts_with(prefix)
867        } else {
868            text == pattern || regex_pattern == text
869        }
870    }
871
872    /// Get a field value from a pattern match
873    fn get_field_value(&self, field: &FieldRef, matched: &PatternMatch) -> Option<Value> {
874        match field {
875            FieldRef::NodeId { alias } => {
876                matched.nodes.get(alias).map(|n| Value::text(n.id.clone()))
877            }
878            FieldRef::NodeProperty { alias, property } => matched
879                .nodes
880                .get(alias)
881                .and_then(|n| match property.as_str() {
882                    "id" => Some(Value::text(n.id.clone())),
883                    "label" => Some(Value::text(n.label.clone())),
884                    "type" | "node_type" => Some(Value::text(n.node_label.clone())),
885                    _ => n.properties.get(property).cloned(),
886                })
887                .or_else(|| {
888                    matched
889                        .edges
890                        .get(alias)
891                        .and_then(|e| Self::edge_property_value(e, property))
892                }),
893            FieldRef::EdgeProperty { alias, property } => matched
894                .edges
895                .get(alias)
896                .and_then(|e| Self::edge_property_value(e, property)),
897            FieldRef::TableColumn { table, column } => {
898                // The shared SQL `WHERE` parser emits `n.foo` as
899                // `TableColumn { table: "n", column: "foo" }` — for
900                // graph MATCH we want to treat that as a node-property
901                // lookup against the matched alias when one exists,
902                // so `MATCH (n) WHERE n.label = 'x'` actually filters.
903                if !table.is_empty() {
904                    if let Some(n) = matched.nodes.get(table) {
905                        return match column.as_str() {
906                            "id" => Some(Value::text(n.id.clone())),
907                            "label" => Some(Value::text(n.label.clone())),
908                            "type" | "node_type" => Some(Value::text(n.node_label.clone())),
909                            other => n.properties.get(other).cloned(),
910                        };
911                    }
912                    if let Some(e) = matched.edges.get(table) {
913                        return Self::edge_property_value(e, column);
914                    }
915                }
916                None
917            }
918        }
919    }
920
921    fn edge_property_value(edge: &MatchedEdge, property: &str) -> Option<Value> {
922        match property {
923            "weight" => Some(Value::Float(edge.weight as f64)),
924            "from" | "source" => Some(Value::text(edge.from.clone())),
925            "to" | "target" => Some(Value::text(edge.to.clone())),
926            "label" | "type" | "edge_type" => Some(Value::text(edge.edge_label.clone())),
927            other => edge.properties.get(other).cloned(),
928        }
929    }
930
931    /// Get a value for join condition
932    fn get_join_value(&self, field: &FieldRef, record: &UnifiedRecord) -> Option<Value> {
933        match field {
934            FieldRef::TableColumn { column, .. } => record.get(column.as_str()).cloned(),
935            FieldRef::NodeId { alias } => record
936                .nodes
937                .get(alias)
938                .map(|node| Value::text(node.id.clone())),
939            FieldRef::NodeProperty { alias, property } => {
940                record
941                    .nodes
942                    .get(alias)
943                    .and_then(|n| match property.as_str() {
944                        "id" => Some(Value::text(n.id.clone())),
945                        "label" => Some(Value::text(n.label.clone())),
946                        "type" | "node_type" => Some(Value::text(n.node_label.clone())),
947                        _ => n.properties.get(property).cloned(),
948                    })
949            }
950            FieldRef::EdgeProperty { alias, property } => {
951                record
952                    .edges
953                    .get(alias)
954                    .and_then(|e| match property.as_str() {
955                        "weight" => Some(Value::Float(e.weight as f64)),
956                        "from" | "source" => Some(Value::text(e.from.clone())),
957                        "to" | "target" => Some(Value::text(e.to.clone())),
958                        "label" | "type" | "edge_type" => Some(Value::text(e.edge_label.clone())),
959                        other => e.properties.get(other).cloned(),
960                    })
961            }
962        }
963    }
964
965    /// Get an index-agnostic view of matched records for projections
966    fn project_match(&self, matched: &PatternMatch, projections: &[Projection]) -> UnifiedRecord {
967        let mut record = UnifiedRecord::new();
968
969        // Copy all matched nodes and edges
970        record.nodes = matched.nodes.clone();
971        record.edges = matched.edges.clone();
972
973        // Extract projected values
974        for proj in projections {
975            match proj {
976                Projection::Field(field, alias) => {
977                    // `RETURN n` (whole-entity projection) expands into
978                    // every property the match holds for that alias —
979                    // id, label, node_type, plus user properties — so
980                    // callers don't get an empty `{}` row.
981                    if let (FieldRef::NodeId { alias: node_alias }, None) = (field, alias) {
982                        if let Some(node) = matched.nodes.get(node_alias) {
983                            record.set(&format!("{}.id", node_alias), Value::text(node.id.clone()));
984                            record.set(
985                                &format!("{}.label", node_alias),
986                                Value::text(node.label.clone()),
987                            );
988                            record.set(
989                                &format!("{}.node_type", node_alias),
990                                Value::text(node.node_label.clone()),
991                            );
992                            for (k, v) in &node.properties {
993                                record.set(&format!("{}.{}", node_alias, k), v.clone());
994                            }
995                            continue;
996                        }
997                        if let Some(edge) = matched.edges.get(node_alias) {
998                            record.set(
999                                &format!("{}.from", node_alias),
1000                                Value::text(edge.from.clone()),
1001                            );
1002                            record.set(&format!("{}.to", node_alias), Value::text(edge.to.clone()));
1003                            record.set(
1004                                &format!("{}.label", node_alias),
1005                                Value::text(edge.edge_label.clone()),
1006                            );
1007                            record.set(
1008                                &format!("{}.weight", node_alias),
1009                                Value::Float(edge.weight as f64),
1010                            );
1011                            for (k, v) in &edge.properties {
1012                                record.set(&format!("{}.{}", node_alias, k), v.clone());
1013                            }
1014                            continue;
1015                        }
1016                    }
1017                    if let Some(value) = self.get_field_value(field, matched) {
1018                        let key = alias.clone().unwrap_or_else(|| self.field_to_string(field));
1019                        record.set(&key, value);
1020                    }
1021                }
1022                Projection::All => {
1023                    // For All projection, include all node basic info
1024                    for (alias, node) in &matched.nodes {
1025                        record.set(&format!("{}.id", alias), Value::text(node.id.clone()));
1026                        record.set(&format!("{}.label", alias), Value::text(node.label.clone()));
1027                    }
1028                }
1029                Projection::Column(col) => {
1030                    // Try to find a matching column in nodes
1031                    for node in matched.nodes.values() {
1032                        match col.as_str() {
1033                            "id" => record.set(col, Value::text(node.id.clone())),
1034                            "label" => record.set(col, Value::text(node.label.clone())),
1035                            _ => {}
1036                        }
1037                    }
1038                }
1039                Projection::Alias(col, alias) => {
1040                    for node in matched.nodes.values() {
1041                        match col.as_str() {
1042                            "id" => record.set(alias, Value::text(node.id.clone())),
1043                            "label" => record.set(alias, Value::text(node.label.clone())),
1044                            _ => {}
1045                        }
1046                    }
1047                }
1048                _ => {} // Function and Expression projections not supported yet
1049            }
1050        }
1051
1052        record
1053    }
1054
1055    /// Convert a field reference to a string key
1056    fn field_to_string(&self, field: &FieldRef) -> String {
1057        match field {
1058            FieldRef::NodeId { alias } => format!("{}.id", alias),
1059            FieldRef::NodeProperty { alias, property } => format!("{}.{}", alias, property),
1060            FieldRef::EdgeProperty { alias, property } => format!("{}.{}", alias, property),
1061            FieldRef::TableColumn { table, column } => {
1062                if table.is_empty() {
1063                    column.clone()
1064                } else {
1065                    format!("{}.{}", table, column)
1066                }
1067            }
1068        }
1069    }
1070
1071    /// Execute a join query
1072    fn exec_join(&self, query: &JoinQuery) -> Result<UnifiedResult, ExecutionError> {
1073        // Execute left side
1074        let left_result = self.execute(&query.left)?;
1075
1076        // Execute right side
1077        let right_result = self.execute(&query.right)?;
1078
1079        // Perform the join
1080        let mut result = UnifiedResult::empty();
1081
1082        // For each left record, find matching right records
1083        for left in &left_result.records {
1084            let left_value = self.get_join_value(&query.on.left_field, left);
1085
1086            for right in &right_result.records {
1087                let right_value = self.get_join_value(&query.on.right_field, right);
1088
1089                if left_value == right_value {
1090                    // Merge records
1091                    let mut merged = left.clone();
1092                    merged.nodes.extend(right.nodes.clone());
1093                    merged.edges.extend(right.edges.clone());
1094                    for (k, v) in right.iter_fields() {
1095                        merged.set_arc(k.clone(), v.clone());
1096                    }
1097                    result.push(merged);
1098                }
1099            }
1100
1101            // Handle outer joins
1102            if matches!(query.join_type, JoinType::LeftOuter) {
1103                // If no matches found for this left record, still include it
1104                if !right_result
1105                    .records
1106                    .iter()
1107                    .any(|r| self.get_join_value(&query.on.right_field, r) == left_value)
1108                {
1109                    result.push(left.clone());
1110                }
1111            }
1112        }
1113
1114        Ok(result)
1115    }
1116
1117    /// Execute a path query
1118    fn exec_path(&self, query: &PathQuery) -> Result<UnifiedResult, ExecutionError> {
1119        let mut result = UnifiedResult::empty();
1120        let mut stats = QueryStats::default();
1121
1122        // Find start nodes
1123        let start_nodes = self.resolve_selector(&query.from, &mut stats)?;
1124
1125        // Find target nodes
1126        let target_nodes: HashSet<String> = self
1127            .resolve_selector(&query.to, &mut stats)?
1128            .into_iter()
1129            .collect();
1130
1131        // BFS to find paths
1132        for start_id in start_nodes {
1133            let paths = self.bfs_paths(
1134                &start_id,
1135                &target_nodes,
1136                &query.via,
1137                query.max_length,
1138                &mut stats,
1139            )?;
1140
1141            for path in paths {
1142                // Apply filter if present
1143                if effective_path_filter(query).is_some() {
1144                    // Path filtering would require converting path to match
1145                    // For now, include all paths
1146                }
1147
1148                let mut record = UnifiedRecord::new();
1149                record.paths.push(path);
1150                result.push(record);
1151            }
1152        }
1153
1154        result.stats = stats;
1155        Ok(result)
1156    }
1157
1158    /// Resolve a node selector to node IDs
1159    fn resolve_selector(
1160        &self,
1161        selector: &NodeSelector,
1162        stats: &mut QueryStats,
1163    ) -> Result<Vec<String>, ExecutionError> {
1164        match selector {
1165            NodeSelector::ById(id) => Ok(vec![id.clone()]),
1166            NodeSelector::ByType { node_label, filter } => {
1167                let expected_id = self.graph.registry.lookup(Namespace::Node, node_label);
1168                let mut nodes = Vec::new();
1169                for node in self.graph.iter_nodes() {
1170                    stats.nodes_scanned += 1;
1171                    if expected_id.map(|id| node.label_id == id).unwrap_or(false) {
1172                        let matches_filter = filter
1173                            .as_ref()
1174                            .map(|f| self.eval_node_property_filter(&node, f))
1175                            .unwrap_or(true);
1176                        if matches_filter {
1177                            nodes.push(node.id.clone());
1178                        }
1179                    }
1180                }
1181                Ok(nodes)
1182            }
1183            NodeSelector::ByRow { row_id, .. } => {
1184                // Use graph-table index to find linked node
1185                // For now, try direct lookup with table_id=0
1186                if let Some(node_id) = self.index.get_node_for_row(0, *row_id) {
1187                    Ok(vec![node_id])
1188                } else {
1189                    Ok(Vec::new())
1190                }
1191            }
1192        }
1193    }
1194
1195    /// BFS to find paths between nodes
1196    fn bfs_paths(
1197        &self,
1198        start: &str,
1199        targets: &HashSet<String>,
1200        via: &[String],
1201        max_length: u32,
1202        stats: &mut QueryStats,
1203    ) -> Result<Vec<GraphPath>, ExecutionError> {
1204        let mut paths = Vec::new();
1205        let mut queue: VecDeque<GraphPath> = VecDeque::new();
1206        let mut visited: HashSet<String> = HashSet::new();
1207
1208        queue.push_back(GraphPath::start(start));
1209        visited.insert(start.to_string());
1210
1211        while let Some(current_path) = queue.pop_front() {
1212            let Some(current_node) = current_path.nodes.last() else {
1213                continue;
1214            };
1215
1216            // Check if we've reached a target
1217            if targets.contains(current_node) && !current_path.is_empty() {
1218                paths.push(current_path.clone());
1219                continue;
1220            }
1221
1222            // Don't extend beyond max length
1223            if current_path.len() >= max_length as usize {
1224                continue;
1225            }
1226
1227            // Get outgoing edges (each entry: edge_label, target_id, weight)
1228            for (edge_type, target_id, weight) in self.graph.outgoing_edges(current_node) {
1229                stats.edges_scanned += 1;
1230
1231                // Check edge label filter (string compare against canonical name).
1232                if !via.is_empty() && !via.iter().any(|v| v == edge_type.as_str()) {
1233                    continue;
1234                }
1235
1236                // Skip if already visited (prevent cycles)
1237                if visited.contains(&target_id) {
1238                    continue;
1239                }
1240
1241                let edge = MatchedEdge::from_tuple(current_node, edge_type, &target_id, weight);
1242                let new_path = current_path.extend(edge, &target_id);
1243                visited.insert(target_id.clone());
1244                queue.push_back(new_path);
1245            }
1246        }
1247
1248        Ok(paths)
1249    }
1250}
1251
1252/// Internal pattern match state
1253#[derive(Debug, Clone, Default)]
1254struct PatternMatch {
1255    nodes: HashMap<String, MatchedNode>,
1256    edges: HashMap<String, MatchedEdge>,
1257}
1258
1259impl PatternMatch {
1260    fn new() -> Self {
1261        Self::default()
1262    }
1263}