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