Skip to main content

grafeo_engine/query/executor/
mod.rs

1//! Query executor.
2//!
3//! Executes physical plans and produces results.
4
5use crate::config::AdaptiveConfig;
6use crate::database::QueryResult;
7use grafeo_common::types::{LogicalType, Value};
8use grafeo_common::utils::error::{Error, Result};
9use grafeo_core::execution::operators::{Operator, OperatorError};
10use grafeo_core::execution::{
11    AdaptiveContext, AdaptiveSummary, CardinalityTrackingWrapper, DataChunk, SharedAdaptiveContext,
12};
13
14/// Executes a physical operator tree and collects results.
15pub struct Executor {
16    /// Column names for the result.
17    columns: Vec<String>,
18    /// Column types for the result.
19    column_types: Vec<LogicalType>,
20}
21
22impl Executor {
23    /// Creates a new executor.
24    #[must_use]
25    pub fn new() -> Self {
26        Self {
27            columns: Vec::new(),
28            column_types: Vec::new(),
29        }
30    }
31
32    /// Creates an executor with specified column names.
33    #[must_use]
34    pub fn with_columns(columns: Vec<String>) -> Self {
35        let len = columns.len();
36        Self {
37            columns,
38            column_types: vec![LogicalType::Any; len],
39        }
40    }
41
42    /// Creates an executor with specified column names and types.
43    #[must_use]
44    pub fn with_columns_and_types(columns: Vec<String>, column_types: Vec<LogicalType>) -> Self {
45        Self {
46            columns,
47            column_types,
48        }
49    }
50
51    /// Executes a physical operator and collects all results.
52    ///
53    /// # Errors
54    ///
55    /// Returns an error if operator execution fails.
56    pub fn execute(&self, operator: &mut dyn Operator) -> Result<QueryResult> {
57        let mut result = QueryResult::with_types(self.columns.clone(), self.column_types.clone());
58        let mut types_captured = !result.column_types.iter().all(|t| *t == LogicalType::Any);
59
60        loop {
61            match operator.next() {
62                Ok(Some(chunk)) => {
63                    // Capture column types from first non-empty chunk
64                    if !types_captured && chunk.column_count() > 0 {
65                        self.capture_column_types(&chunk, &mut result);
66                        types_captured = true;
67                    }
68                    self.collect_chunk(&chunk, &mut result)?;
69                }
70                Ok(None) => break,
71                Err(err) => return Err(convert_operator_error(err)),
72            }
73        }
74
75        Ok(result)
76    }
77
78    /// Executes and returns at most `limit` rows.
79    ///
80    /// # Errors
81    ///
82    /// Returns an error if operator execution fails.
83    pub fn execute_with_limit(
84        &self,
85        operator: &mut dyn Operator,
86        limit: usize,
87    ) -> Result<QueryResult> {
88        let mut result = QueryResult::with_types(self.columns.clone(), self.column_types.clone());
89        let mut collected = 0;
90        let mut types_captured = !result.column_types.iter().all(|t| *t == LogicalType::Any);
91
92        loop {
93            if collected >= limit {
94                break;
95            }
96
97            match operator.next() {
98                Ok(Some(chunk)) => {
99                    // Capture column types from first non-empty chunk
100                    if !types_captured && chunk.column_count() > 0 {
101                        self.capture_column_types(&chunk, &mut result);
102                        types_captured = true;
103                    }
104                    let remaining = limit - collected;
105                    collected += self.collect_chunk_limited(&chunk, &mut result, remaining)?;
106                }
107                Ok(None) => break,
108                Err(err) => return Err(convert_operator_error(err)),
109            }
110        }
111
112        Ok(result)
113    }
114
115    /// Captures column types from a DataChunk.
116    fn capture_column_types(&self, chunk: &DataChunk, result: &mut QueryResult) {
117        let col_count = chunk.column_count();
118        result.column_types = Vec::with_capacity(col_count);
119        for col_idx in 0..col_count {
120            let col_type = chunk
121                .column(col_idx)
122                .map(|col| col.data_type().clone())
123                .unwrap_or(LogicalType::Any);
124            result.column_types.push(col_type);
125        }
126    }
127
128    /// Collects all rows from a DataChunk into the result.
129    fn collect_chunk(&self, chunk: &DataChunk, result: &mut QueryResult) -> Result<usize> {
130        let row_count = chunk.row_count();
131        let col_count = chunk.column_count();
132
133        for row_idx in 0..row_count {
134            let mut row = Vec::with_capacity(col_count);
135            for col_idx in 0..col_count {
136                let value = chunk
137                    .column(col_idx)
138                    .and_then(|col| col.get_value(row_idx))
139                    .unwrap_or(Value::Null);
140                row.push(value);
141            }
142            result.rows.push(row);
143        }
144
145        Ok(row_count)
146    }
147
148    /// Collects up to `limit` rows from a DataChunk.
149    fn collect_chunk_limited(
150        &self,
151        chunk: &DataChunk,
152        result: &mut QueryResult,
153        limit: usize,
154    ) -> Result<usize> {
155        let row_count = chunk.row_count().min(limit);
156        let col_count = chunk.column_count();
157
158        for row_idx in 0..row_count {
159            let mut row = Vec::with_capacity(col_count);
160            for col_idx in 0..col_count {
161                let value = chunk
162                    .column(col_idx)
163                    .and_then(|col| col.get_value(row_idx))
164                    .unwrap_or(Value::Null);
165                row.push(value);
166            }
167            result.rows.push(row);
168        }
169
170        Ok(row_count)
171    }
172
173    /// Executes a physical operator with adaptive cardinality tracking.
174    ///
175    /// This wraps the operator in a cardinality tracking layer and monitors
176    /// deviation from estimates during execution. The adaptive summary is
177    /// returned alongside the query result.
178    ///
179    /// # Arguments
180    ///
181    /// * `operator` - The root physical operator to execute
182    /// * `adaptive_context` - Context with cardinality estimates from planning
183    /// * `config` - Adaptive execution configuration
184    ///
185    /// # Errors
186    ///
187    /// Returns an error if operator execution fails.
188    pub fn execute_adaptive(
189        &self,
190        operator: Box<dyn Operator>,
191        adaptive_context: Option<AdaptiveContext>,
192        config: &AdaptiveConfig,
193    ) -> Result<(QueryResult, Option<AdaptiveSummary>)> {
194        // If adaptive is disabled or no context, fall back to normal execution
195        if !config.enabled {
196            let mut op = operator;
197            let result = self.execute(op.as_mut())?;
198            return Ok((result, None));
199        }
200
201        let ctx = match adaptive_context {
202            Some(ctx) => ctx,
203            None => {
204                let mut op = operator;
205                let result = self.execute(op.as_mut())?;
206                return Ok((result, None));
207            }
208        };
209
210        // Create shared context for tracking
211        let shared_ctx = SharedAdaptiveContext::from_context(AdaptiveContext::with_thresholds(
212            config.threshold,
213            config.min_rows,
214        ));
215
216        // Copy estimates from the planning context to the shared tracking context
217        for (op_id, checkpoint) in ctx.all_checkpoints() {
218            if let Some(mut inner) = shared_ctx.snapshot() {
219                inner.set_estimate(op_id, checkpoint.estimated);
220            }
221        }
222
223        // Wrap operator with tracking
224        let mut wrapped = CardinalityTrackingWrapper::new(operator, "root", shared_ctx.clone());
225
226        // Execute with tracking
227        let mut result = QueryResult::with_types(self.columns.clone(), self.column_types.clone());
228        let mut types_captured = !result.column_types.iter().all(|t| *t == LogicalType::Any);
229        let mut total_rows: u64 = 0;
230        let check_interval = config.min_rows;
231
232        loop {
233            match wrapped.next() {
234                Ok(Some(chunk)) => {
235                    let chunk_rows = chunk.row_count();
236                    total_rows += chunk_rows as u64;
237
238                    // Capture column types from first non-empty chunk
239                    if !types_captured && chunk.column_count() > 0 {
240                        self.capture_column_types(&chunk, &mut result);
241                        types_captured = true;
242                    }
243                    self.collect_chunk(&chunk, &mut result)?;
244
245                    // Periodically check for significant deviation
246                    if total_rows >= check_interval && total_rows.is_multiple_of(check_interval) {
247                        if shared_ctx.should_reoptimize() {
248                            // For now, just log/note that re-optimization would trigger
249                            // Full re-optimization would require plan regeneration
250                            // which is a more invasive change
251                        }
252                    }
253                }
254                Ok(None) => break,
255                Err(err) => return Err(convert_operator_error(err)),
256            }
257        }
258
259        // Get final summary
260        let summary = shared_ctx.snapshot().map(|ctx| ctx.summary());
261
262        Ok((result, summary))
263    }
264}
265
266impl Default for Executor {
267    fn default() -> Self {
268        Self::new()
269    }
270}
271
272/// Converts an operator error to a common error.
273fn convert_operator_error(err: OperatorError) -> Error {
274    match err {
275        OperatorError::TypeMismatch { expected, found } => Error::TypeMismatch { expected, found },
276        OperatorError::ColumnNotFound(name) => {
277            Error::InvalidValue(format!("Column not found: {name}"))
278        }
279        OperatorError::Execution(msg) => Error::Internal(msg),
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286    use grafeo_common::types::LogicalType;
287    use grafeo_core::execution::DataChunk;
288
289    /// A mock operator that generates chunks with integer data on demand.
290    struct MockIntOperator {
291        values: Vec<i64>,
292        position: usize,
293        chunk_size: usize,
294    }
295
296    impl MockIntOperator {
297        fn new(values: Vec<i64>, chunk_size: usize) -> Self {
298            Self {
299                values,
300                position: 0,
301                chunk_size,
302            }
303        }
304    }
305
306    impl Operator for MockIntOperator {
307        fn next(&mut self) -> grafeo_core::execution::operators::OperatorResult {
308            if self.position >= self.values.len() {
309                return Ok(None);
310            }
311
312            let end = (self.position + self.chunk_size).min(self.values.len());
313            let mut chunk = DataChunk::with_capacity(&[LogicalType::Int64], self.chunk_size);
314
315            {
316                let col = chunk.column_mut(0).unwrap();
317                for i in self.position..end {
318                    col.push_int64(self.values[i]);
319                }
320            }
321            chunk.set_count(end - self.position);
322            self.position = end;
323
324            Ok(Some(chunk))
325        }
326
327        fn reset(&mut self) {
328            self.position = 0;
329        }
330
331        fn name(&self) -> &'static str {
332            "MockInt"
333        }
334    }
335
336    /// Empty mock operator for testing empty results.
337    struct EmptyOperator;
338
339    impl Operator for EmptyOperator {
340        fn next(&mut self) -> grafeo_core::execution::operators::OperatorResult {
341            Ok(None)
342        }
343
344        fn reset(&mut self) {}
345
346        fn name(&self) -> &'static str {
347            "Empty"
348        }
349    }
350
351    #[test]
352    fn test_executor_empty() {
353        let executor = Executor::with_columns(vec!["a".to_string()]);
354        let mut op = EmptyOperator;
355
356        let result = executor.execute(&mut op).unwrap();
357        assert!(result.is_empty());
358        assert_eq!(result.column_count(), 1);
359    }
360
361    #[test]
362    fn test_executor_single_chunk() {
363        let executor = Executor::with_columns(vec!["value".to_string()]);
364        let mut op = MockIntOperator::new(vec![1, 2, 3], 10);
365
366        let result = executor.execute(&mut op).unwrap();
367        assert_eq!(result.row_count(), 3);
368        assert_eq!(result.rows[0][0], Value::Int64(1));
369        assert_eq!(result.rows[1][0], Value::Int64(2));
370        assert_eq!(result.rows[2][0], Value::Int64(3));
371    }
372
373    #[test]
374    fn test_executor_with_limit() {
375        let executor = Executor::with_columns(vec!["value".to_string()]);
376        let mut op = MockIntOperator::new((0..10).collect(), 100);
377
378        let result = executor.execute_with_limit(&mut op, 5).unwrap();
379        assert_eq!(result.row_count(), 5);
380    }
381}