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
//! Integration tests for index optimization scenarios
//!
//! These tests verify that the executor correctly handles edge cases in index optimization
//! that previously caused failures in sqllogictest suite (issue #1807).
//!
//! Test coverage:
//! - BETWEEN with mixed numeric types (Integer, Real, Numeric, Double)
//! - IN operator with large value sets (100+ values)
//! - Commuted comparison operators (col > 5 vs 5 < col)
//! - Numeric type normalization in index range scans

use vibesql_ast::{IndexColumn, OrderDirection};
use vibesql_catalog::{ColumnSchema, TableSchema};
use vibesql_parser::Parser;
use vibesql_storage::{Database, Row};
use vibesql_types::{DataType, SqlValue};

use crate::select::SelectExecutor;

/// Create a test database with a table containing various numeric types
fn create_numeric_types_db() -> Database {
    let mut db = Database::new();
    db.catalog.set_case_sensitive_identifiers(false);

    // Create table with columns of different numeric types
    let schema = TableSchema::new(
        "measurements".to_string(),
        vec![
            ColumnSchema::new("id".to_string(), DataType::Integer, false),
            ColumnSchema::new("int_value".to_string(), DataType::Integer, false),
            ColumnSchema::new("real_value".to_string(), DataType::Real, false),
            ColumnSchema::new("double_value".to_string(), DataType::DoublePrecision, false),
            ColumnSchema::new(
                "numeric_value".to_string(),
                DataType::Numeric { precision: 10, scale: 2 },
                false,
            ),
        ],
    );

    db.create_table(schema).unwrap();

    // Insert test data with various numeric values
    // Values chosen to test range scans and type normalization
    db.insert_row(
        "measurements",
        Row::new(vec![
            SqlValue::Integer(1),
            SqlValue::Integer(10),
            SqlValue::Real(10.5),
            SqlValue::Double(10.75),
            SqlValue::Numeric(10.9),
        ]),
    )
    .unwrap();

    db.insert_row(
        "measurements",
        Row::new(vec![
            SqlValue::Integer(2),
            SqlValue::Integer(20),
            SqlValue::Real(20.5),
            SqlValue::Double(20.75),
            SqlValue::Numeric(20.9),
        ]),
    )
    .unwrap();

    db.insert_row(
        "measurements",
        Row::new(vec![
            SqlValue::Integer(3),
            SqlValue::Integer(30),
            SqlValue::Real(30.5),
            SqlValue::Double(30.75),
            SqlValue::Numeric(30.9),
        ]),
    )
    .unwrap();

    db.insert_row(
        "measurements",
        Row::new(vec![
            SqlValue::Integer(4),
            SqlValue::Integer(40),
            SqlValue::Real(40.5),
            SqlValue::Double(40.75),
            SqlValue::Numeric(40.9),
        ]),
    )
    .unwrap();

    db.insert_row(
        "measurements",
        Row::new(vec![
            SqlValue::Integer(5),
            SqlValue::Integer(50),
            SqlValue::Real(50.5),
            SqlValue::Double(50.75),
            SqlValue::Numeric(50.9),
        ]),
    )
    .unwrap();

    db
}

#[test]
fn test_index_range_scan_between_numeric_types() {
    let mut db = create_numeric_types_db();

    // Create index on int_value column
    // Create all indexes first
    db.create_index(
        "idx_int_value".to_string(),
        "measurements".to_string(),
        false, // not unique
        vec![IndexColumn::Column {
            column_name: "int_value".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

    db.create_index(
        "idx_real_value".to_string(),
        "measurements".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "real_value".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

    db.create_index(
        "idx_double_value".to_string(),
        "measurements".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "double_value".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

    // Now create executor after all indexes are created
    let executor = SelectExecutor::new(&db);

    // Test BETWEEN on integer column with index
    let query = "SELECT id, int_value FROM measurements WHERE int_value BETWEEN 15 AND 35";
    let stmt = Parser::parse_sql(query).unwrap();

    if let vibesql_ast::Statement::Select(select_stmt) = stmt {
        let result = executor.execute(&select_stmt).unwrap();

        // Should return rows with int_value 20 and 30 (ids 2 and 3)
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].values[0], SqlValue::Integer(2));
        assert_eq!(result[0].values[1], SqlValue::Integer(20));
        assert_eq!(result[1].values[0], SqlValue::Integer(3));
        assert_eq!(result[1].values[1], SqlValue::Integer(30));
    } else {
        panic!("Expected SELECT statement");
    }

    // Test BETWEEN on Real column with index
    let query = "SELECT id, real_value FROM measurements WHERE real_value BETWEEN 15.0 AND 35.0";
    let stmt = Parser::parse_sql(query).unwrap();

    if let vibesql_ast::Statement::Select(select_stmt) = stmt {
        let result = executor.execute(&select_stmt).unwrap();

        // Should return rows with real_value 20.5 and 30.5 (ids 2 and 3)
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].values[0], SqlValue::Integer(2));
        assert_eq!(result[1].values[0], SqlValue::Integer(3));
    } else {
        panic!("Expected SELECT statement");
    }

    // Test BETWEEN on Double column with index
    let query =
        "SELECT id, double_value FROM measurements WHERE double_value BETWEEN 15.0 AND 35.0";
    let stmt = Parser::parse_sql(query).unwrap();

    if let vibesql_ast::Statement::Select(select_stmt) = stmt {
        let result = executor.execute(&select_stmt).unwrap();

        // Should return rows with double_value 20.75 and 30.75 (ids 2 and 3)
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].values[0], SqlValue::Integer(2));
        assert_eq!(result[1].values[0], SqlValue::Integer(3));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_index_multi_lookup_large_value_set() {
    let mut db = Database::new();
    db.catalog.set_case_sensitive_identifiers(false);

    // Create table with many rows
    let schema = TableSchema::new(
        "items".to_string(),
        vec![
            ColumnSchema::new("id".to_string(), DataType::Integer, false),
            ColumnSchema::new("value".to_string(), DataType::Integer, false),
        ],
    );
    db.create_table(schema).unwrap();

    // Insert 150 rows
    for i in 0..150 {
        db.insert_row("items", Row::new(vec![SqlValue::Integer(i), SqlValue::Integer(i * 10)]))
            .unwrap();
    }

    // Create index on value column
    db.create_index(
        "idx_items_value".to_string(),
        "items".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "value".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

    let executor = SelectExecutor::new(&db);

    // Test IN operator with 100+ values
    // This tests index multi-lookup optimization
    let mut in_values = Vec::new();
    for i in (0..100).step_by(2) {
        // Even values from 0 to 98
        in_values.push(i * 10);
    }
    let in_list = in_values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(",");

    let query = format!("SELECT id FROM items WHERE value IN ({}) ORDER BY id", in_list);
    let stmt = Parser::parse_sql(&query).unwrap();

    if let vibesql_ast::Statement::Select(select_stmt) = stmt {
        let result = executor.execute(&select_stmt).unwrap();

        // Should return 50 rows (even numbers from 0 to 98)
        assert_eq!(result.len(), 50);

        // Verify first few results
        assert_eq!(result[0].values[0], SqlValue::Integer(0));
        assert_eq!(result[1].values[0], SqlValue::Integer(2));
        assert_eq!(result[2].values[0], SqlValue::Integer(4));

        // Verify last result
        assert_eq!(result[49].values[0], SqlValue::Integer(98));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_index_commuted_comparisons() {
    let mut db = Database::new();
    db.catalog.set_case_sensitive_identifiers(false);

    // Create simple table
    let schema = TableSchema::new(
        "numbers".to_string(),
        vec![
            ColumnSchema::new("id".to_string(), DataType::Integer, false),
            ColumnSchema::new("value".to_string(), DataType::Integer, false),
        ],
    );
    db.create_table(schema).unwrap();

    // Insert test data
    for i in 1..=10 {
        db.insert_row("numbers", Row::new(vec![SqlValue::Integer(i), SqlValue::Integer(i * 10)]))
            .unwrap();
    }

    // Create index on value column
    db.create_index(
        "idx_numbers_value".to_string(),
        "numbers".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "value".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

    let executor = SelectExecutor::new(&db);

    // Test: value > 50 (normal form)
    let query1 = "SELECT id FROM numbers WHERE value > 50 ORDER BY id";
    let stmt1 = Parser::parse_sql(query1).unwrap();

    let result1 = if let vibesql_ast::Statement::Select(select_stmt) = stmt1 {
        executor.execute(&select_stmt).unwrap()
    } else {
        panic!("Expected SELECT statement");
    };

    // Test: 50 < value (commuted form)
    let query2 = "SELECT id FROM numbers WHERE 50 < value ORDER BY id";
    let stmt2 = Parser::parse_sql(query2).unwrap();

    let result2 = if let vibesql_ast::Statement::Select(select_stmt) = stmt2 {
        executor.execute(&select_stmt).unwrap()
    } else {
        panic!("Expected SELECT statement");
    };

    // Both queries should return identical results
    assert_eq!(result1.len(), result2.len());
    assert_eq!(result1.len(), 5); // ids 6, 7, 8, 9, 10

    for i in 0..result1.len() {
        assert_eq!(result1[i].values[0], result2[i].values[0]);
    }

    // Verify actual values
    assert_eq!(result1[0].values[0], SqlValue::Integer(6));
    assert_eq!(result1[4].values[0], SqlValue::Integer(10));

    // Test >= and <= commutation
    let query3 = "SELECT id FROM numbers WHERE value >= 60 ORDER BY id";
    let stmt3 = Parser::parse_sql(query3).unwrap();

    let result3 = if let vibesql_ast::Statement::Select(select_stmt) = stmt3 {
        executor.execute(&select_stmt).unwrap()
    } else {
        panic!("Expected SELECT statement");
    };

    let query4 = "SELECT id FROM numbers WHERE 60 <= value ORDER BY id";
    let stmt4 = Parser::parse_sql(query4).unwrap();

    let result4 = if let vibesql_ast::Statement::Select(select_stmt) = stmt4 {
        executor.execute(&select_stmt).unwrap()
    } else {
        panic!("Expected SELECT statement");
    };

    // Both queries should return identical results
    assert_eq!(result3.len(), result4.len());
    assert_eq!(result3.len(), 5); // ids 6, 7, 8, 9, 10

    for i in 0..result3.len() {
        assert_eq!(result3[i].values[0], result4[i].values[0]);
    }
}

#[test]
fn test_index_numeric_type_normalization() {
    let mut db = create_numeric_types_db();

    // Create all indexes first
    db.create_index(
        "idx_int".to_string(),
        "measurements".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "int_value".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

    db.create_index(
        "idx_real".to_string(),
        "measurements".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "real_value".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

    db.create_index(
        "idx_double".to_string(),
        "measurements".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "double_value".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

    db.create_index(
        "idx_numeric".to_string(),
        "measurements".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "numeric_value".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

    // Now create executor after all indexes are created
    let executor = SelectExecutor::new(&db);

    // Test that Integer column can be compared with Real literal using index
    // This tests normalize_for_comparison() in index_operations.rs:20
    let query = "SELECT id, int_value FROM measurements WHERE int_value > 25.0";
    let stmt = Parser::parse_sql(query).unwrap();

    if let vibesql_ast::Statement::Select(select_stmt) = stmt {
        let result = executor.execute(&select_stmt).unwrap();

        // Should return rows with int_value 30, 40, 50 (ids 3, 4, 5)
        assert_eq!(result.len(), 3);
        assert_eq!(result[0].values[0], SqlValue::Integer(3));
        assert_eq!(result[1].values[0], SqlValue::Integer(4));
        assert_eq!(result[2].values[0], SqlValue::Integer(5));
    } else {
        panic!("Expected SELECT statement");
    }

    // Test that Real column can be compared with Integer literal using index
    let query = "SELECT id, real_value FROM measurements WHERE real_value < 25";
    let stmt = Parser::parse_sql(query).unwrap();

    if let vibesql_ast::Statement::Select(select_stmt) = stmt {
        let result = executor.execute(&select_stmt).unwrap();

        // Should return rows with real_value 10.5 and 20.5 (ids 1 and 2)
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].values[0], SqlValue::Integer(1));
        assert_eq!(result[1].values[0], SqlValue::Integer(2));
    } else {
        panic!("Expected SELECT statement");
    }

    // Test that Double column works with Numeric comparison
    let query = "SELECT id FROM measurements WHERE double_value >= 30.75 AND double_value <= 40.75";
    let stmt = Parser::parse_sql(query).unwrap();

    if let vibesql_ast::Statement::Select(select_stmt) = stmt {
        let result = executor.execute(&select_stmt).unwrap();

        // Should return rows with double_value 30.75 and 40.75 (ids 3 and 4)
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].values[0], SqlValue::Integer(3));
        assert_eq!(result[1].values[0], SqlValue::Integer(4));
    } else {
        panic!("Expected SELECT statement");
    }

    // Test range scan on Numeric column
    let query = "SELECT id FROM measurements WHERE numeric_value BETWEEN 20.0 AND 40.0";
    let stmt = Parser::parse_sql(query).unwrap();

    if let vibesql_ast::Statement::Select(select_stmt) = stmt {
        let result = executor.execute(&select_stmt).unwrap();

        // Should return rows with numeric_value 20.9 and 30.9 (ids 2 and 3)
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].values[0], SqlValue::Integer(2));
        assert_eq!(result[1].values[0], SqlValue::Integer(3));
    } else {
        panic!("Expected SELECT statement");
    }
}