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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Transform IN/EXISTS subqueries to semi/anti-joins
//!
//! Note: Some clone_on_copy lints are suppressed because the code is clearer
//! with explicit clones for operators that may not be Copy in future.

#![allow(clippy::clone_on_copy)]

//!
//! This module transforms decorrelated IN/NOT IN/EXISTS/NOT EXISTS subqueries
//! in the WHERE clause into SEMI/ANTI joins in the FROM clause, enabling
//! efficient hash-based join execution instead of row-by-row subquery evaluation.
//!
//! ## Transformation Examples
//!
//! ### IN → SEMI JOIN
//! ```sql
//! -- Before:
//! SELECT * FROM orders WHERE o_orderkey IN (SELECT l_orderkey FROM lineitem)
//!
//! -- After:
//! SELECT orders.* FROM orders SEMI JOIN lineitem ON o_orderkey = l_orderkey
//! ```
//!
//! ### NOT IN → ANTI JOIN
//! ```sql
//! -- Before:
//! SELECT * FROM orders WHERE o_orderkey NOT IN (SELECT l_orderkey FROM lineitem)
//!
//! -- After:
//! SELECT orders.* FROM orders ANTI JOIN lineitem ON o_orderkey = l_orderkey
//! ```
//!
//! ### EXISTS → SEMI JOIN
//! ```sql
//! -- Before (after decorrelation):
//! SELECT * FROM orders WHERE o_orderkey IN (SELECT DISTINCT l_orderkey FROM lineitem)
//!
//! -- After:
//! SELECT orders.* FROM orders SEMI JOIN lineitem ON o_orderkey = l_orderkey
//! ```

mod exists;
mod helpers;
mod in_clause;
mod scalar_comparison;

use exists::try_convert_exists_to_join;
use in_clause::try_convert_in_to_join;
use scalar_comparison::try_convert_scalar_comparison_to_join;
use vibesql_ast::{BinaryOperator, Expression, FromClause, SelectStmt};

/// Transform a SELECT statement by converting IN/NOT IN subqueries to semi/anti-joins
///
/// This transformation only applies to simple IN subqueries with single-column SELECT lists
/// and simple table references. Complex subqueries (joins, aggregations, etc.) are left unchanged.
///
/// The transformation is applied iteratively to handle queries with multiple subqueries
/// (e.g., Q21 with both EXISTS and NOT EXISTS clauses).
pub fn transform_subqueries_to_joins(stmt: &SelectStmt) -> SelectStmt {
    let mut result = stmt.clone();

    // First, recursively transform any subqueries in the WHERE clause
    if let Some(where_clause) = &result.where_clause {
        result.where_clause = Some(transform_subqueries_in_expression(where_clause));
    }

    // Only transform if we have a FROM clause and a WHERE clause
    if result.from.is_none() || result.where_clause.is_none() {
        return result;
    }

    // Apply transformation iteratively until no more changes
    // This handles queries with multiple IN/EXISTS subqueries
    let max_iterations = 10; // Safety limit to prevent infinite loops
    for iteration in 0..max_iterations {
        let mut made_progress = false;

        // Try to extract IN/NOT IN/EXISTS subqueries from WHERE clause and convert to joins
        if let Some(where_clause) = &result.where_clause {
            if let Some((new_from, new_where)) =
                try_extract_subqueries_to_joins(result.from.as_ref().unwrap(), where_clause)
            {
                // Debug output for subquery transformation
                if std::env::var("SUBQUERY_TRANSFORM_VERBOSE").is_ok() {
                    eprintln!(
                        "[SUBQUERY_TRANSFORM] Iteration {}: Converted subquery to join",
                        iteration + 1
                    );
                }
                result.from = Some(new_from);
                result.where_clause = new_where;
                made_progress = true;
            }
        }

        // If no transformation was applied this iteration, we're done
        if !made_progress {
            if std::env::var("SUBQUERY_TRANSFORM_VERBOSE").is_ok() && iteration > 0 {
                eprintln!("[SUBQUERY_TRANSFORM] Completed after {} iterations", iteration);
            }
            break;
        }
    }

    result
}

/// Transform scalar comparison subqueries within a SELECT statement (for nested subqueries)
///
/// This is a lighter-weight version of `transform_subqueries_to_joins` that ONLY handles
/// scalar comparison subqueries like `col > (SELECT SUM(...) ...)`. It does NOT convert
/// IN/EXISTS to semi/anti-joins.
///
/// This is used when recursing into IN/EXISTS subqueries to decorrelate scalar comparisons
/// without affecting the structure of nested IN/EXISTS (which would prevent the parent
/// IN/EXISTS from being transformed to a join).
fn transform_scalar_subqueries_in_stmt(stmt: &SelectStmt) -> SelectStmt {
    let mut result = stmt.clone();

    // Only transform if we have a FROM clause and a WHERE clause
    if result.from.is_none() || result.where_clause.is_none() {
        return result;
    }

    // Apply scalar comparison transformation iteratively
    let max_iterations = 5;
    for _iteration in 0..max_iterations {
        let mut made_progress = false;

        if let Some(where_clause) = &result.where_clause {
            if let Some((new_from, new_where)) =
                try_extract_scalar_comparisons_only(result.from.as_ref().unwrap(), where_clause)
            {
                result.from = Some(new_from);
                result.where_clause = new_where;
                made_progress = true;
            }
        }

        if !made_progress {
            break;
        }
    }

    result
}

/// Try to extract scalar comparison subqueries from WHERE clause and convert to LEFT JOINs
/// This does NOT handle IN/EXISTS - only scalar comparisons like `col > (SELECT ...)`
fn try_extract_scalar_comparisons_only(
    from: &FromClause,
    where_clause: &Expression,
) -> Option<(FromClause, Option<Expression>)> {
    match where_clause {
        // Scalar comparison with subquery at top level
        Expression::BinaryOp { op, left, right }
            if matches!(right.as_ref(), Expression::ScalarSubquery(_)) =>
        {
            if let Some(result) = try_convert_scalar_comparison_to_join(from, op, left, right) {
                return Some((result.from, Some(result.replacement_expr)));
            }
            None
        }

        // AND with potential scalar comparison
        Expression::BinaryOp { op: BinaryOperator::And, left, right } => {
            // Try left side
            if let Expression::BinaryOp { op, left: inner_left, right: inner_right } = left.as_ref()
            {
                if matches!(inner_right.as_ref(), Expression::ScalarSubquery(_)) {
                    if let Some(result) =
                        try_convert_scalar_comparison_to_join(from, op, inner_left, inner_right)
                    {
                        let new_where = Expression::BinaryOp {
                            op: BinaryOperator::And,
                            left: Box::new(result.replacement_expr),
                            right: right.clone(),
                        };
                        return Some((result.from, Some(new_where)));
                    }
                }
            }

            // Try right side
            if let Expression::BinaryOp { op, left: inner_left, right: inner_right } =
                right.as_ref()
            {
                if matches!(inner_right.as_ref(), Expression::ScalarSubquery(_)) {
                    if let Some(result) =
                        try_convert_scalar_comparison_to_join(from, op, inner_left, inner_right)
                    {
                        let new_where = Expression::BinaryOp {
                            op: BinaryOperator::And,
                            left: left.clone(),
                            right: Box::new(result.replacement_expr),
                        };
                        return Some((result.from, Some(new_where)));
                    }
                }
            }

            None
        }

        // Conjunction (flattened AND chain)
        Expression::Conjunction(children) => {
            for (i, child) in children.iter().enumerate() {
                if let Expression::BinaryOp { op, left, right } = child {
                    if matches!(right.as_ref(), Expression::ScalarSubquery(_)) {
                        if let Some(result) =
                            try_convert_scalar_comparison_to_join(from, op, left, right)
                        {
                            let mut remaining: Vec<_> = children
                                .iter()
                                .enumerate()
                                .filter(|(j, _)| *j != i)
                                .map(|(_, c)| c.clone())
                                .collect();
                            remaining.push(result.replacement_expr);
                            let new_where = match remaining.len() {
                                0 => None,
                                1 => Some(remaining.into_iter().next().unwrap()),
                                _ => Some(Expression::Conjunction(remaining)),
                            };
                            return Some((result.from, new_where));
                        }
                    }
                }
            }
            None
        }

        _ => None,
    }
}

/// Recursively transform subqueries within an expression
///
/// This applies scalar comparison decorrelation to SELECT statements nested within
/// IN and EXISTS subquery expressions (like Q20's pattern: `ps_availqty > (SELECT SUM(...) ...)`).
///
/// IMPORTANT: We only decorrelate scalar comparisons, NOT IN/EXISTS to semi/anti-joins.
/// Converting nested IN/EXISTS would change their FROM clause structure, which would then
/// prevent the PARENT IN/EXISTS from being converted to a join (because the parent
/// transformation expects a simple table in the subquery's FROM clause).
fn transform_subqueries_in_expression(expr: &Expression) -> Expression {
    match expr {
        Expression::In { expr: inner_expr, subquery, negated } => {
            // Transform the inner expression
            let transformed_inner = transform_subqueries_in_expression(inner_expr);
            // Only apply scalar comparison decorrelation, NOT IN/EXISTS transformation
            // This preserves the subquery's FROM clause structure for parent transformation
            let transformed_subquery = transform_scalar_subqueries_in_stmt(subquery);
            Expression::In {
                expr: Box::new(transformed_inner),
                subquery: Box::new(transformed_subquery),
                negated: *negated,
            }
        }
        Expression::Exists { subquery, negated } => {
            // Only apply scalar comparison decorrelation, NOT IN/EXISTS transformation
            let transformed_subquery = transform_scalar_subqueries_in_stmt(subquery);
            Expression::Exists { subquery: Box::new(transformed_subquery), negated: *negated }
        }
        Expression::ScalarSubquery(subquery) => {
            let transformed_subquery = transform_subqueries_to_joins(subquery);
            Expression::ScalarSubquery(Box::new(transformed_subquery))
        }
        Expression::BinaryOp { op, left, right } => Expression::BinaryOp {
            op: op.clone(),
            left: Box::new(transform_subqueries_in_expression(left)),
            right: Box::new(transform_subqueries_in_expression(right)),
        },
        Expression::Conjunction(children) => Expression::Conjunction(
            children.iter().map(transform_subqueries_in_expression).collect(),
        ),
        Expression::Disjunction(children) => Expression::Disjunction(
            children.iter().map(transform_subqueries_in_expression).collect(),
        ),
        Expression::UnaryOp { op, expr: inner } => Expression::UnaryOp {
            op: op.clone(),
            expr: Box::new(transform_subqueries_in_expression(inner)),
        },
        Expression::IsNull { expr: inner, negated } => Expression::IsNull {
            expr: Box::new(transform_subqueries_in_expression(inner)),
            negated: *negated,
        },
        Expression::Between { expr: inner, low, high, negated, symmetric } => Expression::Between {
            expr: Box::new(transform_subqueries_in_expression(inner)),
            low: Box::new(transform_subqueries_in_expression(low)),
            high: Box::new(transform_subqueries_in_expression(high)),
            negated: *negated,
            symmetric: *symmetric,
        },
        Expression::Case { operand, when_clauses, else_result } => Expression::Case {
            operand: operand.as_ref().map(|o| Box::new(transform_subqueries_in_expression(o))),
            when_clauses: when_clauses
                .iter()
                .map(|w| vibesql_ast::CaseWhen {
                    conditions: w
                        .conditions
                        .iter()
                        .map(transform_subqueries_in_expression)
                        .collect(),
                    result: transform_subqueries_in_expression(&w.result),
                })
                .collect(),
            else_result: else_result
                .as_ref()
                .map(|e| Box::new(transform_subqueries_in_expression(e))),
        },
        // For other expression types, just return as-is
        _ => expr.clone(),
    }
}

/// Try to extract IN/NOT IN subqueries from WHERE clause and convert to semi/anti-joins
fn try_extract_subqueries_to_joins(
    from: &FromClause,
    where_clause: &Expression,
) -> Option<(FromClause, Option<Expression>)> {
    // Look for IN subquery at the top level or in AND branches
    match where_clause {
        // Single IN subquery
        Expression::In { expr, subquery, negated } => {
            if let Some(result) = try_convert_in_to_join(from, expr, subquery, *negated) {
                return Some((result.from, None)); // Removed WHERE clause entirely
            }
            None
        }

        // AND with potential IN/EXISTS/scalar comparison subqueries
        Expression::BinaryOp { op: BinaryOperator::And, left, right } => {
            // Try left side first - check IN, EXISTS, and scalar comparison
            match left.as_ref() {
                Expression::In { expr, subquery, negated } => {
                    if let Some(result) = try_convert_in_to_join(from, expr, subquery, *negated) {
                        // Successfully converted left IN side, keep right side as WHERE clause
                        // Note: We no longer qualify remaining WHERE clause columns because it
                        // incorrectly qualifies columns from OTHER tables (not the self-join
                        // table). The subquery's columns have already been
                        // rewritten to use the new alias,
                        // so column resolution will work correctly during execution.
                        return Some((result.from, Some((**right).clone())));
                    }
                }
                Expression::Exists { subquery, negated } => {
                    if let Some((join, _)) = try_convert_exists_to_join(from, subquery, *negated) {
                        // Successfully converted left EXISTS side, keep right side as WHERE clause
                        return Some((join, Some((**right).clone())));
                    }
                }
                Expression::BinaryOp { op, left: inner_left, right: inner_right }
                    if matches!(inner_right.as_ref(), Expression::ScalarSubquery(_)) =>
                {
                    if let Some(result) =
                        try_convert_scalar_comparison_to_join(from, op, inner_left, inner_right)
                    {
                        // Replace the scalar comparison with the new expression
                        let new_where = Expression::BinaryOp {
                            op: BinaryOperator::And,
                            left: Box::new(result.replacement_expr),
                            right: right.clone(),
                        };
                        return Some((result.from, Some(new_where)));
                    }
                }
                _ => {}
            }

            // Try right side - check IN, EXISTS, and scalar comparison
            match right.as_ref() {
                Expression::In { expr, subquery, negated } => {
                    if let Some(result) = try_convert_in_to_join(from, expr, subquery, *negated) {
                        // Successfully converted right IN side, keep left side as WHERE clause
                        // Note: We no longer qualify remaining WHERE clause columns because it
                        // incorrectly qualifies columns from OTHER tables (not the self-join
                        // table).
                        return Some((result.from, Some((**left).clone())));
                    }
                }
                Expression::Exists { subquery, negated } => {
                    if let Some((join, _)) = try_convert_exists_to_join(from, subquery, *negated) {
                        // Successfully converted right EXISTS side, keep left side as WHERE clause
                        return Some((join, Some((**left).clone())));
                    }
                }
                Expression::BinaryOp { op, left: inner_left, right: inner_right }
                    if matches!(inner_right.as_ref(), Expression::ScalarSubquery(_)) =>
                {
                    if let Some(result) =
                        try_convert_scalar_comparison_to_join(from, op, inner_left, inner_right)
                    {
                        // Replace the scalar comparison with the new expression
                        let new_where = Expression::BinaryOp {
                            op: BinaryOperator::And,
                            left: left.clone(),
                            right: Box::new(result.replacement_expr),
                        };
                        return Some((result.from, Some(new_where)));
                    }
                }
                _ => {}
            }

            // Try recursively on left side
            if let Some((new_left_from, new_left_where)) =
                try_extract_subqueries_to_joins(from, left)
            {
                let combined_where = match new_left_where {
                    Some(new_left) => Some(Expression::BinaryOp {
                        op: BinaryOperator::And,
                        left: Box::new(new_left),
                        right: right.clone(),
                    }),
                    None => Some((**right).clone()),
                };
                return Some((new_left_from, combined_where));
            }

            // Try recursively on right side
            if let Some((new_right_from, new_right_where)) =
                try_extract_subqueries_to_joins(from, right)
            {
                let combined_where = match new_right_where {
                    Some(new_right) => Some(Expression::BinaryOp {
                        op: BinaryOperator::And,
                        left: left.clone(),
                        right: Box::new(new_right),
                    }),
                    None => Some((**left).clone()),
                };
                return Some((new_right_from, combined_where));
            }

            None
        }

        // EXISTS can also be converted (after decorrelation it becomes IN, but handle it directly
        // too)
        Expression::Exists { subquery, negated } => {
            // Try to convert EXISTS to a semi-join by extracting correlation
            try_convert_exists_to_join(from, subquery, *negated)
        }

        // Scalar comparison with subquery (e.g., ps_availqty > (SELECT SUM(...) ...))
        Expression::BinaryOp { op, left, right }
            if matches!(right.as_ref(), Expression::ScalarSubquery(_)) =>
        {
            if let Some(result) = try_convert_scalar_comparison_to_join(from, op, left, right) {
                return Some((result.from, Some(result.replacement_expr)));
            }
            None
        }

        // Conjunction (flattened AND chain) - produced by arena parser
        // Handle IN/EXISTS/scalar comparison subqueries within the conjunction children
        Expression::Conjunction(children) => {
            // Look for IN, EXISTS, or scalar comparison subqueries among children
            for (i, child) in children.iter().enumerate() {
                match child {
                    Expression::In { expr, subquery, negated } => {
                        if let Some(result) = try_convert_in_to_join(from, expr, subquery, *negated)
                        {
                            // Build remaining WHERE from other children
                            let remaining: Vec<_> = children
                                .iter()
                                .enumerate()
                                .filter(|(j, _)| *j != i)
                                .map(|(_, c)| c.clone())
                                .collect();
                            let new_where = match remaining.len() {
                                0 => None,
                                1 => Some(remaining.into_iter().next().unwrap()),
                                _ => Some(Expression::Conjunction(remaining)),
                            };
                            return Some((result.from, new_where));
                        }
                    }
                    Expression::Exists { subquery, negated } => {
                        if let Some((join, _)) =
                            try_convert_exists_to_join(from, subquery, *negated)
                        {
                            // Build remaining WHERE from other children
                            let remaining: Vec<_> = children
                                .iter()
                                .enumerate()
                                .filter(|(j, _)| *j != i)
                                .map(|(_, c)| c.clone())
                                .collect();
                            let new_where = match remaining.len() {
                                0 => None,
                                1 => Some(remaining.into_iter().next().unwrap()),
                                _ => Some(Expression::Conjunction(remaining)),
                            };
                            return Some((join, new_where));
                        }
                    }
                    Expression::BinaryOp { op, left, right }
                        if matches!(right.as_ref(), Expression::ScalarSubquery(_)) =>
                    {
                        if let Some(result) =
                            try_convert_scalar_comparison_to_join(from, op, left, right)
                        {
                            // Build remaining WHERE from other children, replacing this child
                            // with the replacement expression
                            let mut remaining: Vec<_> = children
                                .iter()
                                .enumerate()
                                .filter(|(j, _)| *j != i)
                                .map(|(_, c)| c.clone())
                                .collect();
                            remaining.push(result.replacement_expr);
                            let new_where = match remaining.len() {
                                0 => None,
                                1 => Some(remaining.into_iter().next().unwrap()),
                                _ => Some(Expression::Conjunction(remaining)),
                            };
                            return Some((result.from, new_where));
                        }
                    }
                    _ => {}
                }
            }

            // Try recursively on each child (for nested expressions)
            for (i, child) in children.iter().enumerate() {
                if let Some((new_from, new_child_where)) =
                    try_extract_subqueries_to_joins(from, child)
                {
                    let mut new_children: Vec<_> = children
                        .iter()
                        .enumerate()
                        .filter(|(j, _)| *j != i)
                        .map(|(_, c)| c.clone())
                        .collect();
                    if let Some(residual) = new_child_where {
                        new_children.push(residual);
                    }
                    let combined_where = match new_children.len() {
                        0 => None,
                        1 => Some(new_children.into_iter().next().unwrap()),
                        _ => Some(Expression::Conjunction(new_children)),
                    };
                    return Some((new_from, combined_where));
                }
            }

            None
        }

        _ => None,
    }
}

#[cfg(test)]
mod tests;