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
//! Tests for nested loop join implementations.

use vibesql_catalog::{ColumnSchema, TableSchema};
use vibesql_storage::{Database, Row};
use vibesql_types::{DataType, SqlValue};

use super::{sequential::execute_nested_loop_classic, *};
use crate::schema::CombinedSchema;

/// Create a CombinedSchema for testing
fn create_combined_schema(
    left_table: &str,
    left_cols: Vec<(&str, DataType)>,
    right_table: &str,
    right_cols: Vec<(&str, DataType)>,
) -> CombinedSchema {
    let left_schema = TableSchema::new(
        left_table.to_string(),
        left_cols
            .iter()
            .map(|(name, dtype)| ColumnSchema::new(name.to_string(), dtype.clone(), true))
            .collect(),
    );

    let right_schema = TableSchema::new(
        right_table.to_string(),
        right_cols
            .iter()
            .map(|(name, dtype)| ColumnSchema::new(name.to_string(), dtype.clone(), true))
            .collect(),
    );

    CombinedSchema::combine(
        CombinedSchema::from_table(left_table.to_string(), left_schema),
        right_table.to_string(),
        right_schema,
    )
}

// ===== Tests for execute_nested_loop_classic (sequential path) =====

#[test]
fn test_nested_loop_classic_simple_condition() {
    // Test basic nested loop join with a simple equality condition
    let left_rows: Vec<Row> = vec![
        Row::new(vec![SqlValue::Integer(1), SqlValue::Varchar(arcstr::ArcStr::from("Alice"))]),
        Row::new(vec![SqlValue::Integer(2), SqlValue::Varchar(arcstr::ArcStr::from("Bob"))]),
        Row::new(vec![SqlValue::Integer(3), SqlValue::Varchar(arcstr::ArcStr::from("Charlie"))]),
    ];

    let right_rows: Vec<Row> = vec![
        Row::new(vec![SqlValue::Integer(1), SqlValue::Integer(100)]),
        Row::new(vec![SqlValue::Integer(2), SqlValue::Integer(200)]),
        Row::new(vec![SqlValue::Integer(1), SqlValue::Integer(150)]),
    ];

    let schema = create_combined_schema(
        "users",
        vec![("id", DataType::Integer), ("name", DataType::Varchar { max_length: Some(50) })],
        "orders",
        vec![("user_id", DataType::Integer), ("amount", DataType::Integer)],
    );

    let db = Database::default();
    let timeout_ctx = crate::timeout::TimeoutContext::new_default();

    // Condition: users.id = orders.user_id (column 0 = column 2 in combined row)
    let condition = vibesql_ast::Expression::BinaryOp {
        left: Box::new(vibesql_ast::Expression::ColumnRef(
            vibesql_ast::ColumnIdentifier::qualified("users", false, "id", false),
        )),
        op: vibesql_ast::BinaryOperator::Equal,
        right: Box::new(vibesql_ast::Expression::ColumnRef(
            vibesql_ast::ColumnIdentifier::qualified("orders", false, "user_id", false),
        )),
    };

    let result = execute_nested_loop_classic(
        &left_rows,
        &right_rows,
        &Some(condition),
        &schema,
        &db,
        &timeout_ctx,
        &["users".to_string()],
        &["orders".to_string()],
        None, // outer_row - not used in this test
        None, // outer_schema - not used in this test
    )
    .unwrap();

    // Should have 3 matches: Alice (1) x 2 orders, Bob (1) x 1 order
    assert_eq!(result.len(), 3);

    // Verify Alice appears twice (2 orders with user_id=1)
    let alice_count = result.iter().filter(|r| r.values[0] == SqlValue::Integer(1)).count();
    assert_eq!(alice_count, 2);

    // Verify Bob appears once
    let bob_count = result.iter().filter(|r| r.values[0] == SqlValue::Integer(2)).count();
    assert_eq!(bob_count, 1);

    // Verify Charlie doesn't appear (no orders)
    let charlie_count = result.iter().filter(|r| r.values[0] == SqlValue::Integer(3)).count();
    assert_eq!(charlie_count, 0);
}

#[test]
fn test_nested_loop_classic_no_condition() {
    // Test cross product (no condition)
    let left_rows: Vec<Row> =
        vec![Row::new(vec![SqlValue::Integer(1)]), Row::new(vec![SqlValue::Integer(2)])];

    let right_rows: Vec<Row> = vec![
        Row::new(vec![SqlValue::Integer(10)]),
        Row::new(vec![SqlValue::Integer(20)]),
        Row::new(vec![SqlValue::Integer(30)]),
    ];

    let schema = create_combined_schema(
        "left",
        vec![("a", DataType::Integer)],
        "right",
        vec![("b", DataType::Integer)],
    );

    let db = Database::default();
    let timeout_ctx = crate::timeout::TimeoutContext::new_default();

    let result = execute_nested_loop_classic(
        &left_rows,
        &right_rows,
        &None,
        &schema,
        &db,
        &timeout_ctx,
        &["left".to_string()],
        &["right".to_string()],
        None, // outer_row - not used in this test
        None, // outer_schema - not used in this test
    )
    .unwrap();

    // Cross product: 2 x 3 = 6 rows
    assert_eq!(result.len(), 6);
}

#[test]
fn test_nested_loop_classic_empty_input() {
    let left_rows: Vec<Row> = vec![];
    let right_rows: Vec<Row> = vec![Row::new(vec![SqlValue::Integer(1)])];

    let schema = create_combined_schema(
        "left",
        vec![("a", DataType::Integer)],
        "right",
        vec![("b", DataType::Integer)],
    );

    let db = Database::default();
    let timeout_ctx = crate::timeout::TimeoutContext::new_default();

    let result = execute_nested_loop_classic(
        &left_rows,
        &right_rows,
        &None,
        &schema,
        &db,
        &timeout_ctx,
        &["left".to_string()],
        &["right".to_string()],
        None, // outer_row - not used in this test
        None, // outer_schema - not used in this test
    )
    .unwrap();

    assert_eq!(result.len(), 0);
}

// ===== Tests for parallel nested loop join (when feature = "parallel") =====

#[cfg(feature = "parallel")]
mod parallel_tests {
    use super::*;
    use crate::evaluator::CombinedExpressionEvaluator;

    #[test]
    fn test_parallel_nested_loop_simple() {
        // Test parallel nested loop with a simple condition
        let left_rows: Vec<Row> = (0..100)
            .map(|i| {
                Row::new(vec![
                    SqlValue::Integer(i % 10), // id (0-9, repeating)
                    SqlValue::Varchar(arcstr::ArcStr::from(format!("left{}", i))),
                ])
            })
            .collect();

        let right_rows: Vec<Row> = (0..50)
            .map(|i| {
                Row::new(vec![
                    SqlValue::Integer(i % 10), // user_id (0-9, repeating)
                    SqlValue::Integer(i * 100),
                ])
            })
            .collect();

        let schema = create_combined_schema(
            "users",
            vec![("id", DataType::Integer), ("name", DataType::Varchar { max_length: Some(50) })],
            "orders",
            vec![("user_id", DataType::Integer), ("amount", DataType::Integer)],
        );

        let db = Database::default();
        let timeout_ctx = crate::timeout::TimeoutContext::new_default();

        // Condition: users.id = orders.user_id
        let condition = vibesql_ast::Expression::BinaryOp {
            left: Box::new(vibesql_ast::Expression::ColumnRef(
                vibesql_ast::ColumnIdentifier::qualified("users", false, "id", false),
            )),
            op: vibesql_ast::BinaryOperator::Equal,
            right: Box::new(vibesql_ast::Expression::ColumnRef(
                vibesql_ast::ColumnIdentifier::qualified("orders", false, "user_id", false),
            )),
        };

        let result = super::super::parallel::execute_nested_loop_parallel(
            &left_rows,
            &right_rows,
            &Some(condition),
            &schema,
            &db,
            &timeout_ctx,
        )
        .unwrap();

        // Each of 10 keys appears 10 times in left (100/10) and 5 times in right (50/10)
        // So expected result: 10 keys * 10 left_matches * 5 right_matches = 500
        assert_eq!(result.len(), 500);
    }

    #[test]
    fn test_parallel_nested_loop_cross_product() {
        // Test parallel cross product (no condition)
        let left_rows: Vec<Row> = (0..100).map(|i| Row::new(vec![SqlValue::Integer(i)])).collect();

        let right_rows: Vec<Row> = (0..50).map(|i| Row::new(vec![SqlValue::Integer(i)])).collect();

        let schema = create_combined_schema(
            "left",
            vec![("a", DataType::Integer)],
            "right",
            vec![("b", DataType::Integer)],
        );

        let db = Database::default();
        let timeout_ctx = crate::timeout::TimeoutContext::new_default();

        let result = super::super::parallel::execute_nested_loop_parallel(
            &left_rows,
            &right_rows,
            &None,
            &schema,
            &db,
            &timeout_ctx,
        )
        .unwrap();

        // Cross product: 100 x 50 = 5000
        assert_eq!(result.len(), 5000);
    }

    #[test]
    fn test_parallel_nested_loop_empty_input() {
        let left_rows: Vec<Row> = vec![];
        let right_rows: Vec<Row> = (0..50).map(|i| Row::new(vec![SqlValue::Integer(i)])).collect();

        let schema = create_combined_schema(
            "left",
            vec![("a", DataType::Integer)],
            "right",
            vec![("b", DataType::Integer)],
        );

        let db = Database::default();
        let timeout_ctx = crate::timeout::TimeoutContext::new_default();

        let result = super::super::parallel::execute_nested_loop_parallel(
            &left_rows,
            &right_rows,
            &None,
            &schema,
            &db,
            &timeout_ctx,
        )
        .unwrap();

        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_parallel_nested_loop_no_matches() {
        // Test with condition that produces no matches
        let left_rows: Vec<Row> =
            (0..100).map(|i| Row::new(vec![SqlValue::Integer(i), SqlValue::Integer(1)])).collect();

        let right_rows: Vec<Row> = (100..150)
            .map(|i| Row::new(vec![SqlValue::Integer(i), SqlValue::Integer(2)]))
            .collect();

        let schema = create_combined_schema(
            "left",
            vec![("a", DataType::Integer), ("x", DataType::Integer)],
            "right",
            vec![("b", DataType::Integer), ("y", DataType::Integer)],
        );

        let db = Database::default();
        let timeout_ctx = crate::timeout::TimeoutContext::new_default();

        // Condition: left.a = right.b (no matches since ranges don't overlap)
        let condition = vibesql_ast::Expression::BinaryOp {
            left: Box::new(vibesql_ast::Expression::ColumnRef(
                vibesql_ast::ColumnIdentifier::qualified("left", false, "a", false),
            )),
            op: vibesql_ast::BinaryOperator::Equal,
            right: Box::new(vibesql_ast::Expression::ColumnRef(
                vibesql_ast::ColumnIdentifier::qualified("right", false, "b", false),
            )),
        };

        let result = super::super::parallel::execute_nested_loop_parallel(
            &left_rows,
            &right_rows,
            &Some(condition),
            &schema,
            &db,
            &timeout_ctx,
        )
        .unwrap();

        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_parallel_sequential_equivalence() {
        // Verify that parallel and sequential produce the same results
        let left_rows: Vec<Row> = (0..50)
            .map(|i| {
                Row::new(vec![
                    SqlValue::Integer(i % 5),
                    SqlValue::Varchar(arcstr::ArcStr::from(format!("L{}", i))),
                ])
            })
            .collect();

        let right_rows: Vec<Row> = (0..30)
            .map(|i| {
                Row::new(vec![
                    SqlValue::Integer(i % 5),
                    SqlValue::Varchar(arcstr::ArcStr::from(format!("R{}", i))),
                ])
            })
            .collect();

        let schema = create_combined_schema(
            "left",
            vec![("id", DataType::Integer), ("data", DataType::Varchar { max_length: Some(50) })],
            "right",
            vec![("id", DataType::Integer), ("info", DataType::Varchar { max_length: Some(50) })],
        );

        let db = Database::default();
        let timeout_ctx = crate::timeout::TimeoutContext::new_default();

        // Condition: left.id = right.id
        let condition = vibesql_ast::Expression::BinaryOp {
            left: Box::new(vibesql_ast::Expression::ColumnRef(
                vibesql_ast::ColumnIdentifier::qualified("left", false, "id", false),
            )),
            op: vibesql_ast::BinaryOperator::Equal,
            right: Box::new(vibesql_ast::Expression::ColumnRef(
                vibesql_ast::ColumnIdentifier::qualified("right", false, "id", false),
            )),
        };

        // Sequential result
        let seq_result = {
            let evaluator = CombinedExpressionEvaluator::with_database(&schema, &db);
            let mut result = Vec::new();
            for left_row in &left_rows {
                for right_row in &right_rows {
                    let combined = combine_rows(left_row, right_row);
                    evaluator.clear_cse_cache();
                    if let Ok(SqlValue::Boolean(true)) = evaluator.eval(&condition, &combined) {
                        result.push(combined);
                    }
                }
            }
            result
        };

        // Parallel result
        let par_result = super::super::parallel::execute_nested_loop_parallel(
            &left_rows,
            &right_rows,
            &Some(condition.clone()),
            &schema,
            &db,
            &timeout_ctx,
        )
        .unwrap();

        // Should have same number of results
        assert_eq!(
            seq_result.len(),
            par_result.len(),
            "Sequential and parallel should produce same result count"
        );

        // Both should be 50/5 * 30/5 * 5 = 10 * 6 * 5 = 300
        assert_eq!(seq_result.len(), 300);
    }

    #[test]
    fn test_parallel_nested_loop_large_dataset() {
        // Test with a larger dataset to ensure parallel execution is triggered
        let left_rows: Vec<Row> = (0..10000)
            .map(|i| Row::new(vec![SqlValue::Integer(i % 100), SqlValue::Integer(i)]))
            .collect();

        let right_rows: Vec<Row> = (0..1000)
            .map(|i| Row::new(vec![SqlValue::Integer(i % 100), SqlValue::Integer(i)]))
            .collect();

        let schema = create_combined_schema(
            "left",
            vec![("key", DataType::Integer), ("id", DataType::Integer)],
            "right",
            vec![("key", DataType::Integer), ("id", DataType::Integer)],
        );

        let db = Database::default();
        let timeout_ctx = crate::timeout::TimeoutContext::new_default();

        // Condition: left.key = right.key
        let condition = vibesql_ast::Expression::BinaryOp {
            left: Box::new(vibesql_ast::Expression::ColumnRef(
                vibesql_ast::ColumnIdentifier::qualified("left", false, "key", false),
            )),
            op: vibesql_ast::BinaryOperator::Equal,
            right: Box::new(vibesql_ast::Expression::ColumnRef(
                vibesql_ast::ColumnIdentifier::qualified("right", false, "key", false),
            )),
        };

        let result = super::super::parallel::execute_nested_loop_parallel(
            &left_rows,
            &right_rows,
            &Some(condition),
            &schema,
            &db,
            &timeout_ctx,
        )
        .unwrap();

        // Each key (0-99) appears 100 times in left and 10 times in right
        // Expected: 100 keys * 100 * 10 = 100,000
        assert_eq!(result.len(), 100_000);
    }
}