Skip to main content

grafeo_core/execution/operators/
mod.rs

1//! Physical operators that actually execute queries.
2//!
3//! These are the building blocks of query execution. The optimizer picks which
4//! operators to use and how to wire them together.
5//!
6//! **Graph operators:**
7//! - [`ScanOperator`] - Read nodes/edges from storage
8//! - [`ExpandOperator`] - Traverse edges (the core of graph queries)
9//! - [`VariableLengthExpandOperator`] - Paths of variable length
10//! - [`ShortestPathOperator`] - Find shortest paths
11//!
12//! **Relational operators:**
13//! - [`FilterOperator`] - Apply predicates
14//! - [`ProjectOperator`] - Select/transform columns
15//! - [`HashJoinOperator`] - Efficient equi-joins
16//! - [`HashAggregateOperator`] - Group by with aggregation
17//! - [`SortOperator`] - Order results
18//! - [`LimitOperator`] - SKIP and LIMIT
19//!
20//! The [`push`] submodule has push-based variants for pipeline execution.
21
22pub mod accumulator;
23mod aggregate;
24mod apply;
25mod distinct;
26mod expand;
27mod factorized_aggregate;
28mod factorized_expand;
29mod factorized_filter;
30mod filter;
31mod horizontal_aggregate;
32mod join;
33mod leapfrog_join;
34mod limit;
35mod load_data;
36mod map_collect;
37mod merge;
38mod mutation;
39mod parameter_scan;
40mod project;
41pub mod push;
42mod scan;
43mod scan_vector;
44mod set_ops;
45mod shortest_path;
46pub mod single_row;
47mod sort;
48mod union;
49mod unwind;
50pub mod value_utils;
51mod variable_length_expand;
52mod vector_join;
53
54pub use accumulator::{AggregateExpr, AggregateFunction, HashableValue};
55pub use aggregate::{HashAggregateOperator, SimpleAggregateOperator};
56pub use apply::ApplyOperator;
57pub use distinct::DistinctOperator;
58pub use expand::ExpandOperator;
59pub use factorized_aggregate::{
60    FactorizedAggregate, FactorizedAggregateOperator, FactorizedOperator,
61};
62pub use factorized_expand::{
63    ExpandStep, FactorizedExpandChain, FactorizedExpandOperator, FactorizedResult,
64    LazyFactorizedChainOperator,
65};
66pub use factorized_filter::{
67    AndPredicate, ColumnPredicate, CompareOp as FactorizedCompareOp, FactorizedFilterOperator,
68    FactorizedPredicate, OrPredicate, PropertyPredicate,
69};
70pub use filter::{
71    BinaryFilterOp, ExpressionPredicate, FilterExpression, FilterOperator, LazyValue,
72    ListPredicateKind, Predicate, SessionContext, UnaryFilterOp,
73};
74pub use horizontal_aggregate::{EntityKind, HorizontalAggregateOperator};
75pub use join::{
76    EqualityCondition, HashJoinOperator, HashKey, JoinCondition, JoinType, NestedLoopJoinOperator,
77};
78pub use leapfrog_join::LeapfrogJoinOperator;
79pub use limit::{LimitOperator, LimitSkipOperator, SkipOperator};
80pub use load_data::{LoadDataFormat, LoadDataOperator};
81pub use map_collect::MapCollectOperator;
82pub use merge::{MergeConfig, MergeOperator, MergeRelationshipConfig, MergeRelationshipOperator};
83pub use mutation::{
84    AddLabelOperator, ConstraintValidator, CreateEdgeOperator, CreateNodeOperator,
85    DeleteEdgeOperator, DeleteNodeOperator, PropertySource, RemoveLabelOperator,
86    SetPropertyOperator,
87};
88pub use parameter_scan::{ParameterScanOperator, ParameterState};
89pub use project::{ProjectExpr, ProjectOperator};
90pub use push::{
91    AggregatePushOperator, DistinctMaterializingOperator, DistinctPushOperator, FilterPushOperator,
92    LimitPushOperator, ProjectPushOperator, SkipLimitPushOperator, SkipPushOperator,
93    SortPushOperator,
94};
95#[cfg(feature = "spill")]
96pub use push::{SpillableAggregatePushOperator, SpillableSortPushOperator};
97pub use scan::ScanOperator;
98pub use scan_vector::VectorScanOperator;
99pub use set_ops::{ExceptOperator, IntersectOperator, OtherwiseOperator};
100pub use shortest_path::ShortestPathOperator;
101pub use single_row::{EmptyOperator, NodeListOperator, SingleRowOperator};
102pub use sort::{NullOrder, SortDirection, SortKey, SortOperator};
103pub use union::UnionOperator;
104pub use unwind::UnwindOperator;
105pub use variable_length_expand::{PathMode as ExecutionPathMode, VariableLengthExpandOperator};
106pub use vector_join::VectorJoinOperator;
107
108use std::sync::Arc;
109
110use grafeo_common::types::{EdgeId, NodeId, TransactionId};
111use thiserror::Error;
112
113use super::DataChunk;
114use super::chunk_state::ChunkState;
115use super::factorized_chunk::FactorizedChunk;
116
117/// Trait for recording write operations during query execution.
118///
119/// This bridges `grafeo-core` mutation operators (which perform writes) with
120/// `grafeo-engine`'s `TransactionManager` (which tracks write sets for conflict
121/// detection). The trait lives in `grafeo-core` to avoid circular dependencies.
122pub trait WriteTracker: Send + Sync {
123    /// Records that a node was written (created, deleted, or modified).
124    ///
125    /// Returns an error if a write-write conflict is detected (first-writer-wins).
126    fn record_node_write(
127        &self,
128        transaction_id: TransactionId,
129        node_id: NodeId,
130    ) -> Result<(), OperatorError>;
131
132    /// Records that an edge was written (created, deleted, or modified).
133    ///
134    /// Returns an error if a write-write conflict is detected (first-writer-wins).
135    fn record_edge_write(
136        &self,
137        transaction_id: TransactionId,
138        edge_id: EdgeId,
139    ) -> Result<(), OperatorError>;
140}
141
142/// Type alias for a shared write tracker.
143pub type SharedWriteTracker = Arc<dyn WriteTracker>;
144
145/// Result of executing an operator.
146pub type OperatorResult = Result<Option<DataChunk>, OperatorError>;
147
148// ============================================================================
149// Factorized Data Traits
150// ============================================================================
151
152/// Trait for data that can be in factorized or flat form.
153///
154/// This provides a common interface for operators that need to handle both
155/// representations without caring which is used. Inspired by LadybugDB's
156/// unified data model.
157///
158/// # Example
159///
160/// ```rust
161/// use grafeo_core::execution::operators::FactorizedData;
162///
163/// fn process_data(data: &dyn FactorizedData) {
164///     if data.is_factorized() {
165///         // Handle factorized path
166///         let chunk = data.as_factorized().unwrap();
167///         // ... use factorized chunk directly
168///     } else {
169///         // Handle flat path
170///         let chunk = data.flatten();
171///         // ... process flat chunk
172///     }
173/// }
174/// ```
175pub trait FactorizedData: Send + Sync {
176    /// Returns the chunk state (factorization status, cached data).
177    fn chunk_state(&self) -> &ChunkState;
178
179    /// Returns the logical row count (considering selection).
180    fn logical_row_count(&self) -> usize;
181
182    /// Returns the physical size (actual stored values).
183    fn physical_size(&self) -> usize;
184
185    /// Returns true if this data is factorized (multi-level).
186    fn is_factorized(&self) -> bool;
187
188    /// Flattens to a DataChunk (materializes if factorized).
189    fn flatten(&self) -> DataChunk;
190
191    /// Returns as FactorizedChunk if factorized, None if flat.
192    fn as_factorized(&self) -> Option<&FactorizedChunk>;
193
194    /// Returns as DataChunk if flat, None if factorized.
195    fn as_flat(&self) -> Option<&DataChunk>;
196}
197
198/// Wrapper to treat a flat DataChunk as FactorizedData.
199///
200/// This enables uniform handling of flat and factorized data in operators.
201pub struct FlatDataWrapper {
202    chunk: DataChunk,
203    state: ChunkState,
204}
205
206impl FlatDataWrapper {
207    /// Creates a new wrapper around a flat DataChunk.
208    #[must_use]
209    pub fn new(chunk: DataChunk) -> Self {
210        let state = ChunkState::flat(chunk.row_count());
211        Self { chunk, state }
212    }
213
214    /// Returns the underlying DataChunk.
215    #[must_use]
216    pub fn into_inner(self) -> DataChunk {
217        self.chunk
218    }
219}
220
221impl FactorizedData for FlatDataWrapper {
222    fn chunk_state(&self) -> &ChunkState {
223        &self.state
224    }
225
226    fn logical_row_count(&self) -> usize {
227        self.chunk.row_count()
228    }
229
230    fn physical_size(&self) -> usize {
231        self.chunk.row_count() * self.chunk.column_count()
232    }
233
234    fn is_factorized(&self) -> bool {
235        false
236    }
237
238    fn flatten(&self) -> DataChunk {
239        self.chunk.clone()
240    }
241
242    fn as_factorized(&self) -> Option<&FactorizedChunk> {
243        None
244    }
245
246    fn as_flat(&self) -> Option<&DataChunk> {
247        Some(&self.chunk)
248    }
249}
250
251/// Error during operator execution.
252#[derive(Error, Debug, Clone)]
253pub enum OperatorError {
254    /// Type mismatch during execution.
255    #[error("type mismatch: expected {expected}, found {found}")]
256    TypeMismatch {
257        /// Expected type name.
258        expected: String,
259        /// Found type name.
260        found: String,
261    },
262    /// Column not found.
263    #[error("column not found: {0}")]
264    ColumnNotFound(String),
265    /// Execution error.
266    #[error("execution error: {0}")]
267    Execution(String),
268    /// Schema constraint violation during a write operation.
269    #[error("constraint violation: {0}")]
270    ConstraintViolation(String),
271    /// Write-write conflict detected (first-writer-wins).
272    #[error("write conflict: {0}")]
273    WriteConflict(String),
274}
275
276/// The core trait for pull-based operators.
277///
278/// Call [`next()`](Self::next) repeatedly until it returns `None`. Each call
279/// returns a batch of rows (a DataChunk) or an error.
280pub trait Operator: Send + Sync {
281    /// Pulls the next batch of data. Returns `None` when exhausted.
282    fn next(&mut self) -> OperatorResult;
283
284    /// Resets to initial state so you can iterate again.
285    fn reset(&mut self);
286
287    /// Returns a name for debugging/explain output.
288    fn name(&self) -> &'static str;
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294    use crate::execution::vector::ValueVector;
295    use grafeo_common::types::LogicalType;
296
297    fn create_test_chunk() -> DataChunk {
298        let mut col = ValueVector::with_type(LogicalType::Int64);
299        col.push_int64(1);
300        col.push_int64(2);
301        col.push_int64(3);
302        DataChunk::new(vec![col])
303    }
304
305    #[test]
306    fn test_flat_data_wrapper_new() {
307        let chunk = create_test_chunk();
308        let wrapper = FlatDataWrapper::new(chunk);
309
310        assert!(!wrapper.is_factorized());
311        assert_eq!(wrapper.logical_row_count(), 3);
312    }
313
314    #[test]
315    fn test_flat_data_wrapper_into_inner() {
316        let chunk = create_test_chunk();
317        let wrapper = FlatDataWrapper::new(chunk);
318
319        let inner = wrapper.into_inner();
320        assert_eq!(inner.row_count(), 3);
321    }
322
323    #[test]
324    fn test_flat_data_wrapper_chunk_state() {
325        let chunk = create_test_chunk();
326        let wrapper = FlatDataWrapper::new(chunk);
327
328        let state = wrapper.chunk_state();
329        assert!(state.is_flat());
330        assert_eq!(state.logical_row_count(), 3);
331    }
332
333    #[test]
334    fn test_flat_data_wrapper_physical_size() {
335        let mut col1 = ValueVector::with_type(LogicalType::Int64);
336        col1.push_int64(1);
337        col1.push_int64(2);
338
339        let mut col2 = ValueVector::with_type(LogicalType::String);
340        col2.push_string("a");
341        col2.push_string("b");
342
343        let chunk = DataChunk::new(vec![col1, col2]);
344        let wrapper = FlatDataWrapper::new(chunk);
345
346        // 2 rows * 2 columns = 4
347        assert_eq!(wrapper.physical_size(), 4);
348    }
349
350    #[test]
351    fn test_flat_data_wrapper_flatten() {
352        let chunk = create_test_chunk();
353        let wrapper = FlatDataWrapper::new(chunk);
354
355        let flattened = wrapper.flatten();
356        assert_eq!(flattened.row_count(), 3);
357        assert_eq!(flattened.column(0).unwrap().get_int64(0), Some(1));
358    }
359
360    #[test]
361    fn test_flat_data_wrapper_as_factorized() {
362        let chunk = create_test_chunk();
363        let wrapper = FlatDataWrapper::new(chunk);
364
365        assert!(wrapper.as_factorized().is_none());
366    }
367
368    #[test]
369    fn test_flat_data_wrapper_as_flat() {
370        let chunk = create_test_chunk();
371        let wrapper = FlatDataWrapper::new(chunk);
372
373        let flat = wrapper.as_flat();
374        assert!(flat.is_some());
375        assert_eq!(flat.unwrap().row_count(), 3);
376    }
377
378    #[test]
379    fn test_operator_error_type_mismatch() {
380        let err = OperatorError::TypeMismatch {
381            expected: "Int64".to_string(),
382            found: "String".to_string(),
383        };
384
385        let msg = format!("{err}");
386        assert!(msg.contains("type mismatch"));
387        assert!(msg.contains("Int64"));
388        assert!(msg.contains("String"));
389    }
390
391    #[test]
392    fn test_operator_error_column_not_found() {
393        let err = OperatorError::ColumnNotFound("missing_col".to_string());
394
395        let msg = format!("{err}");
396        assert!(msg.contains("column not found"));
397        assert!(msg.contains("missing_col"));
398    }
399
400    #[test]
401    fn test_operator_error_execution() {
402        let err = OperatorError::Execution("something went wrong".to_string());
403
404        let msg = format!("{err}");
405        assert!(msg.contains("execution error"));
406        assert!(msg.contains("something went wrong"));
407    }
408
409    #[test]
410    fn test_operator_error_debug() {
411        let err = OperatorError::TypeMismatch {
412            expected: "Int64".to_string(),
413            found: "String".to_string(),
414        };
415
416        let debug = format!("{err:?}");
417        assert!(debug.contains("TypeMismatch"));
418    }
419
420    #[test]
421    fn test_operator_error_clone() {
422        let err1 = OperatorError::ColumnNotFound("col".to_string());
423        let err2 = err1.clone();
424
425        assert_eq!(format!("{err1}"), format!("{err2}"));
426    }
427}