vibesql-executor 0.2.0

Query execution engine for vibesql SQL database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Unified Execution Strategy Selection
//!
//! This module provides a comprehensive `ExecutionStrategy` enum that encapsulates
//! all execution path selection logic in a single decision point. This replaces the
//! previous scattered eligibility checks across multiple execution methods.
//!
//! ## Execution Strategies
//!
//! - **NativeColumnar**: Zero-copy SIMD execution directly from columnar storage
//! - **StandardColumnar**: SIMD execution with row-to-batch conversion
//! - **RowOriented**: Traditional row-by-row execution (with or without aggregation)
//! - **ExpressionOnly**: SELECT without FROM clause
//!
//! ## Benefits
//!
//! - Single decision point for observability and debugging
//! - Clear reasoning captured in `StrategyScore`
//! - Extensible for future strategies (JIT, GPU, distributed)
//! - Preserves existing hint mechanism

use std::collections::HashMap;

use vibesql_ast::{FromClause, SelectStmt};

use super::{
    patterns::has_analytical_pattern,
    query::{has_aggregate_functions, has_group_by, is_single_table},
};
use crate::select::cte::CteResult;

/// Comprehensive execution strategy selection
///
/// Each variant represents a distinct execution path with its selection rationale.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecutionStrategy {
    /// Zero-copy SIMD execution directly from columnar storage (fastest for eligible queries)
    ///
    /// Requirements:
    /// - Single table scan (no JOINs)
    /// - No CTEs or set operations
    /// - Analytical pattern detected
    /// - native-columnar feature enabled or VIBESQL_NATIVE_COLUMNAR env var set
    NativeColumnar {
        /// Table name for columnar access
        table: String,
        /// Explains why this strategy was chosen
        score: StrategyScore,
    },

    /// SIMD execution with row-to-batch conversion
    ///
    /// Requirements:
    /// - No GROUP BY (handled by NativeColumnar path)
    /// - No CTEs or set operations
    /// - Has FROM clause
    /// - Analytical pattern detected
    StandardColumnar {
        /// Explains why this strategy was chosen
        score: StrategyScore,
    },

    /// Traditional row-oriented execution
    ///
    /// Used when:
    /// - Query doesn't benefit from columnar execution
    /// - Has features not yet supported by columnar paths
    /// - Explicit ROW_ORIENTED hint
    RowOriented {
        /// Whether the query has aggregation
        has_aggregation: bool,
        /// Whether the query has GROUP BY
        has_group_by: bool,
        /// Explains why this strategy was chosen
        score: StrategyScore,
    },

    /// SELECT without FROM clause (expression evaluation only)
    ///
    /// For queries like: SELECT 1 + 1, CURRENT_DATE
    ExpressionOnly {
        /// Explains why this strategy was chosen
        score: StrategyScore,
    },
}

impl ExecutionStrategy {
    /// Get the strategy score for debugging/observability
    pub fn score(&self) -> &StrategyScore {
        match self {
            ExecutionStrategy::NativeColumnar { score, .. } => score,
            ExecutionStrategy::StandardColumnar { score } => score,
            ExecutionStrategy::RowOriented { score, .. } => score,
            ExecutionStrategy::ExpressionOnly { score } => score,
        }
    }

    /// Get a human-readable name for the strategy
    pub fn name(&self) -> &'static str {
        match self {
            ExecutionStrategy::NativeColumnar { .. } => "NativeColumnar",
            ExecutionStrategy::StandardColumnar { .. } => "StandardColumnar",
            ExecutionStrategy::RowOriented { .. } => "RowOriented",
            ExecutionStrategy::ExpressionOnly { .. } => "ExpressionOnly",
        }
    }
}

/// Explains why a strategy was chosen
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StrategyScore {
    /// Primary reason for the strategy selection
    pub reason: StrategyReason,
    /// Additional context for debugging
    pub details: Option<String>,
}

impl StrategyScore {
    /// Create a new strategy score
    pub fn new(reason: StrategyReason) -> Self {
        Self { reason, details: None }
    }

    /// Add details to the score
    pub fn with_details(mut self, details: impl Into<String>) -> Self {
        self.details = Some(details.into());
        self
    }
}

/// Primary reason for strategy selection
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(dead_code)] // Some variants are for future use (query hints, etc.)
pub enum StrategyReason {
    /// User override via query hint (/* COLUMNAR */, /* ROW_ORIENTED */)
    QueryHint(String),
    /// Table has columnar storage available
    ColumnarStorageAvailable,
    /// Query matches analytical pattern (aggregates, arithmetic, selective projection)
    AnalyticalPattern,
    /// Simple single-table scan detected
    SingleTableScan,
    /// No FROM clause - expression-only query
    NoFromClause,
    /// Feature not supported by columnar paths
    UnsupportedFeature(String),
    /// Default fallback when no specific reason applies
    Fallback,
}

impl std::fmt::Display for StrategyReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StrategyReason::QueryHint(hint) => write!(f, "Query hint: {}", hint),
            StrategyReason::ColumnarStorageAvailable => write!(f, "Columnar storage available"),
            StrategyReason::AnalyticalPattern => write!(f, "Analytical pattern detected"),
            StrategyReason::SingleTableScan => write!(f, "Single table scan"),
            StrategyReason::NoFromClause => write!(f, "No FROM clause"),
            StrategyReason::UnsupportedFeature(feature) => {
                write!(f, "Unsupported feature: {}", feature)
            }
            StrategyReason::Fallback => write!(f, "Default fallback"),
        }
    }
}

/// Context required for strategy selection
///
/// This bundles all the information needed to make an execution strategy decision.
pub struct StrategyContext<'a> {
    /// The SELECT statement to analyze
    pub stmt: &'a SelectStmt,
    /// CTE results from outer query (if any)
    pub cte_results: &'a HashMap<String, CteResult>,
    /// Whether native-columnar feature is enabled
    pub native_columnar_enabled: bool,
}

impl<'a> StrategyContext<'a> {
    /// Create a new strategy context
    pub fn new(
        stmt: &'a SelectStmt,
        cte_results: &'a HashMap<String, CteResult>,
        native_columnar_enabled: bool,
    ) -> Self {
        Self { stmt, cte_results, native_columnar_enabled }
    }
}

/// Choose the optimal execution strategy for a query
///
/// This is the single decision point for execution path selection. It encapsulates
/// all eligibility checks that were previously scattered across multiple methods.
///
/// # Arguments
/// * `ctx` - The strategy context containing the query and execution environment
///
/// # Returns
/// The recommended execution strategy with its selection rationale
///
/// # Example
///
/// ```text
/// let ctx = StrategyContext::new(&stmt, &cte_results, true);
/// let strategy = choose_execution_strategy(&ctx);
///
/// match strategy {
///     ExecutionStrategy::NativeColumnar { table, .. } => {
///         // Execute using zero-copy columnar path
///     }
///     ExecutionStrategy::StandardColumnar { .. } => {
///         // Execute using row-to-batch columnar path
///     }
///     ExecutionStrategy::RowOriented { has_aggregation, .. } => {
///         // Execute using traditional row-by-row path
///     }
///     ExecutionStrategy::ExpressionOnly { .. } => {
///         // Evaluate expressions without FROM
///     }
/// }
/// ```
pub fn choose_execution_strategy(ctx: &StrategyContext<'_>) -> ExecutionStrategy {
    let stmt = ctx.stmt;

    // Check 1: No FROM clause → ExpressionOnly
    if stmt.from.is_none() {
        return ExecutionStrategy::ExpressionOnly {
            score: StrategyScore::new(StrategyReason::NoFromClause),
        };
    }

    // Check 2: Has CTEs or set operations → Row-oriented (columnar paths don't support these yet)
    if !ctx.cte_results.is_empty() || stmt.set_operation.is_some() {
        let reason = if !ctx.cte_results.is_empty() { "CTEs" } else { "set operations" };
        return make_row_oriented(stmt, StrategyReason::UnsupportedFeature(reason.to_string()));
    }

    // Check 3: Try NativeColumnar (highest priority columnar path)
    if let Some(strategy) = try_native_columnar_strategy(ctx) {
        return strategy;
    }

    // Check 4: Try StandardColumnar (lower priority, has more restrictions)
    if let Some(strategy) = try_standard_columnar_strategy(ctx) {
        return strategy;
    }

    // Check 5: Default to row-oriented
    make_row_oriented(stmt, StrategyReason::Fallback)
}

/// Try to select NativeColumnar strategy
///
/// Requirements:
/// - native-columnar feature enabled
/// - Single table (no JOINs)
/// - Analytical pattern detected
fn try_native_columnar_strategy(ctx: &StrategyContext<'_>) -> Option<ExecutionStrategy> {
    // Native columnar must be enabled
    if !ctx.native_columnar_enabled {
        return None;
    }

    // Must be a single table scan
    if !is_single_table(ctx.stmt) {
        return None;
    }

    // Must have analytical pattern
    if !has_analytical_pattern(ctx.stmt) {
        return None;
    }

    // Extract table name
    let table_name = match &ctx.stmt.from {
        Some(FromClause::Table { name, .. }) => name.clone(),
        _ => return None,
    };

    Some(ExecutionStrategy::NativeColumnar {
        table: table_name,
        score: StrategyScore::new(StrategyReason::ColumnarStorageAvailable)
            .with_details("Zero-copy SIMD execution from columnar storage"),
    })
}

/// Try to select StandardColumnar strategy
///
/// Requirements:
/// - No GROUP BY (GROUP BY goes through NativeColumnar or RowOriented)
/// - Single table (no JOINs)
/// - Analytical pattern detected
fn try_standard_columnar_strategy(ctx: &StrategyContext<'_>) -> Option<ExecutionStrategy> {
    // GROUP BY is NOT supported in StandardColumnar path
    // It should use NativeColumnar or fall back to RowOriented
    if ctx.stmt.group_by.is_some() {
        return None;
    }

    // Must be a single table scan
    if !is_single_table(ctx.stmt) {
        return None;
    }

    // Must have analytical pattern
    if !has_analytical_pattern(ctx.stmt) {
        return None;
    }

    Some(ExecutionStrategy::StandardColumnar {
        score: StrategyScore::new(StrategyReason::AnalyticalPattern)
            .with_details("SIMD execution with row-to-batch conversion"),
    })
}

/// Create a RowOriented strategy with the given reason
fn make_row_oriented(stmt: &SelectStmt, reason: StrategyReason) -> ExecutionStrategy {
    let has_agg = has_aggregate_functions(stmt) || stmt.having.is_some();
    let has_gb = has_group_by(stmt);

    ExecutionStrategy::RowOriented {
        has_aggregation: has_agg,
        has_group_by: has_gb,
        score: StrategyScore::new(reason),
    }
}

#[cfg(test)]
mod tests {
    use vibesql_ast::{BinaryOperator, Expression, GroupByClause, SelectItem};
    use vibesql_types::SqlValue;

    use super::*;

    fn make_simple_table_query(table: &str) -> SelectStmt {
        SelectStmt {
            with_clause: None,
            distinct: false,
            select_list: vec![SelectItem::Wildcard { alias: None }],
            into_table: None,
            into_variables: None,
            from: Some(FromClause::Table {
                index_hint: None,
                name: table.to_string(),
                alias: None,
                column_aliases: None,
                quoted: false,
            }),
            where_clause: None,
            group_by: None,
            having: None,
            window_definitions: None,
            order_by: None,
            limit: None,
            offset: None,
            set_operation: None,
            values: None,
        }
    }

    fn make_aggregate_query(table: &str) -> SelectStmt {
        SelectStmt {
            with_clause: None,
            distinct: false,
            select_list: vec![SelectItem::Expression {
                expr: Expression::AggregateFunction {
                    name: vibesql_ast::FunctionIdentifier::new("SUM"),
                    distinct: false,
                    args: vec![Expression::BinaryOp {
                        left: Box::new(Expression::ColumnRef(
                            vibesql_ast::ColumnIdentifier::simple("price", false),
                        )),
                        op: BinaryOperator::Multiply,
                        right: Box::new(Expression::ColumnRef(
                            vibesql_ast::ColumnIdentifier::simple("quantity", false),
                        )),
                    }],
                    order_by: None,
                    filter: None,
                },
                alias: None,
                source_text: None,
            }],
            into_table: None,
            into_variables: None,
            from: Some(FromClause::Table {
                index_hint: None,
                name: table.to_string(),
                alias: None,
                column_aliases: None,
                quoted: false,
            }),
            where_clause: None,
            group_by: None,
            having: None,
            window_definitions: None,
            order_by: None,
            limit: None,
            offset: None,
            set_operation: None,
            values: None,
        }
    }

    #[test]
    fn test_expression_only_for_no_from() {
        let stmt = SelectStmt {
            with_clause: None,
            distinct: false,
            select_list: vec![SelectItem::Expression {
                expr: Expression::Literal(SqlValue::Integer(42)),
                alias: None,
                source_text: None,
            }],
            into_table: None,
            into_variables: None,
            from: None,
            where_clause: None,
            group_by: None,
            having: None,
            window_definitions: None,
            order_by: None,
            limit: None,
            offset: None,
            set_operation: None,
            values: None,
        };

        let cte_results = HashMap::new();
        let ctx = StrategyContext::new(&stmt, &cte_results, true);
        let strategy = choose_execution_strategy(&ctx);

        assert!(matches!(strategy, ExecutionStrategy::ExpressionOnly { .. }));
    }

    #[test]
    fn test_row_oriented_for_simple_select() {
        let stmt = make_simple_table_query("users");
        let cte_results = HashMap::new();
        let ctx = StrategyContext::new(&stmt, &cte_results, true);
        let strategy = choose_execution_strategy(&ctx);

        assert!(matches!(strategy, ExecutionStrategy::RowOriented { .. }));
    }

    #[test]
    fn test_native_columnar_for_aggregate_when_enabled() {
        let stmt = make_aggregate_query("orders");
        let cte_results = HashMap::new();
        let ctx = StrategyContext::new(&stmt, &cte_results, true);
        let strategy = choose_execution_strategy(&ctx);

        // Should choose NativeColumnar when feature is enabled and query has analytical pattern
        assert!(matches!(strategy, ExecutionStrategy::NativeColumnar { .. }));
    }

    #[test]
    fn test_standard_columnar_for_aggregate_when_native_disabled() {
        let stmt = make_aggregate_query("orders");
        let cte_results = HashMap::new();
        let ctx = StrategyContext::new(&stmt, &cte_results, false);
        let strategy = choose_execution_strategy(&ctx);

        // Should choose StandardColumnar when native is disabled but query has analytical pattern
        assert!(matches!(strategy, ExecutionStrategy::StandardColumnar { .. }));
    }

    #[test]
    fn test_row_oriented_for_group_by_when_native_disabled() {
        let mut stmt = make_aggregate_query("orders");
        stmt.group_by = Some(GroupByClause::Simple(vec![Expression::ColumnRef(
            vibesql_ast::ColumnIdentifier::simple("region", false),
        )]));

        // With native disabled, GROUP BY queries fall back to row-oriented
        // (StandardColumnar doesn't support GROUP BY)
        let cte_results = HashMap::new();
        let ctx = StrategyContext::new(&stmt, &cte_results, false);
        let strategy = choose_execution_strategy(&ctx);

        assert!(matches!(strategy, ExecutionStrategy::RowOriented { .. }));
    }

    #[test]
    fn test_native_columnar_for_group_by_when_enabled() {
        let mut stmt = make_aggregate_query("orders");
        stmt.group_by = Some(GroupByClause::Simple(vec![Expression::ColumnRef(
            vibesql_ast::ColumnIdentifier::simple("region", false),
        )]));

        // With native enabled, GROUP BY queries can use NativeColumnar
        let cte_results = HashMap::new();
        let ctx = StrategyContext::new(&stmt, &cte_results, true);
        let strategy = choose_execution_strategy(&ctx);

        assert!(matches!(strategy, ExecutionStrategy::NativeColumnar { .. }));
    }

    #[test]
    fn test_strategy_name() {
        let native = ExecutionStrategy::NativeColumnar {
            table: "test".to_string(),
            score: StrategyScore::new(StrategyReason::ColumnarStorageAvailable),
        };
        assert_eq!(native.name(), "NativeColumnar");

        let standard = ExecutionStrategy::StandardColumnar {
            score: StrategyScore::new(StrategyReason::AnalyticalPattern),
        };
        assert_eq!(standard.name(), "StandardColumnar");

        let row = ExecutionStrategy::RowOriented {
            has_aggregation: true,
            has_group_by: false,
            score: StrategyScore::new(StrategyReason::Fallback),
        };
        assert_eq!(row.name(), "RowOriented");

        let expr = ExecutionStrategy::ExpressionOnly {
            score: StrategyScore::new(StrategyReason::NoFromClause),
        };
        assert_eq!(expr.name(), "ExpressionOnly");
    }
}