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
//! Integration tests for secondary index fast path optimization
//!
//! These tests verify that the executor correctly uses secondary index lookups
//! for queries with equality predicates on all columns of a secondary index.
//!
//! Test coverage:
//! - Single-column secondary index lookup
//! - Composite secondary index lookup (TPC-C customer-by-last-name pattern)
//! - Secondary index with ORDER BY
//! - Secondary index with projection

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 customer table similar to TPC-C
fn create_customer_db() -> Database {
    let mut db = Database::new();
    db.catalog.set_case_sensitive_identifiers(false);

    // Create table similar to TPC-C customer table
    // (c_id, c_w_id, c_d_id, c_last, c_first, c_balance)
    let mut schema = TableSchema::new(
        "customer".to_string(),
        vec![
            ColumnSchema::new("c_id".to_string(), DataType::Integer, false),
            ColumnSchema::new("c_w_id".to_string(), DataType::Integer, false),
            ColumnSchema::new("c_d_id".to_string(), DataType::Integer, false),
            ColumnSchema::new(
                "c_last".to_string(),
                DataType::Varchar { max_length: Some(16) },
                false,
            ),
            ColumnSchema::new(
                "c_first".to_string(),
                DataType::Varchar { max_length: Some(16) },
                false,
            ),
            ColumnSchema::new(
                "c_balance".to_string(),
                DataType::Numeric { precision: 12, scale: 2 },
                false,
            ),
        ],
    );

    // Set primary key on (c_w_id, c_d_id, c_id)
    schema.primary_key = Some(vec!["c_w_id".to_string(), "c_d_id".to_string(), "c_id".to_string()]);

    db.create_table(schema).unwrap();

    // Insert test data with different customers
    let customers = vec![
        (1, 1, 1, "SMITH", "Alice", 100.00),
        (2, 1, 1, "SMITH", "Bob", 200.00),
        (3, 1, 1, "JONES", "Charlie", 300.00),
        (4, 1, 2, "SMITH", "Diana", 400.00),
        (5, 2, 1, "SMITH", "Eve", 500.00),
        (6, 1, 1, "BROWN", "Frank", 600.00),
    ];

    for (c_id, c_w_id, c_d_id, c_last, c_first, c_balance) in customers {
        db.insert_row(
            "customer",
            Row::new(vec![
                SqlValue::Integer(c_id),
                SqlValue::Integer(c_w_id),
                SqlValue::Integer(c_d_id),
                SqlValue::Varchar(arcstr::ArcStr::from(c_last)),
                SqlValue::Varchar(arcstr::ArcStr::from(c_first)),
                SqlValue::Numeric(c_balance),
            ]),
        )
        .unwrap();
    }

    db
}

#[test]
fn test_secondary_index_single_column_lookup() {
    let mut db = create_customer_db();

    // Create secondary index on c_last
    db.create_index(
        "idx_customer_last".to_string(),
        "customer".to_string(),
        false, // not unique
        vec![IndexColumn::Column {
            column_name: "c_last".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

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

    // Query using secondary index on c_last
    let query = "SELECT c_id, c_first FROM customer WHERE c_last = 'SMITH'";
    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 all SMITH customers (ids 1, 2, 4, 5)
        assert_eq!(result.len(), 4);

        let ids: Vec<i64> = result
            .iter()
            .filter_map(|r| if let SqlValue::Integer(id) = r.values[0] { Some(id) } else { None })
            .collect();
        assert!(ids.contains(&1));
        assert!(ids.contains(&2));
        assert!(ids.contains(&4));
        assert!(ids.contains(&5));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_secondary_index_composite_lookup() {
    let mut db = create_customer_db();

    // Create composite secondary index on (c_w_id, c_d_id, c_last) - TPC-C pattern
    db.create_index(
        "idx_customer_name".to_string(),
        "customer".to_string(),
        false, // not unique
        vec![
            IndexColumn::Column {
                column_name: "c_w_id".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
            IndexColumn::Column {
                column_name: "c_d_id".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
            IndexColumn::Column {
                column_name: "c_last".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
        ],
    )
    .unwrap();

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

    // Query using composite secondary index (TPC-C customer-by-last-name pattern)
    let query = "SELECT c_id, c_first, c_balance FROM customer WHERE c_w_id = 1 AND c_d_id = 1 AND c_last = 'SMITH'";
    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 SMITH customers in warehouse 1, district 1 (ids 1, 2)
        assert_eq!(result.len(), 2);

        let ids: Vec<i64> = result
            .iter()
            .filter_map(|r| if let SqlValue::Integer(id) = r.values[0] { Some(id) } else { None })
            .collect();
        assert!(ids.contains(&1));
        assert!(ids.contains(&2));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_secondary_index_with_order_by() {
    let mut db = create_customer_db();

    // Create secondary index on (c_w_id, c_d_id, c_last)
    db.create_index(
        "idx_customer_name".to_string(),
        "customer".to_string(),
        false,
        vec![
            IndexColumn::Column {
                column_name: "c_w_id".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
            IndexColumn::Column {
                column_name: "c_d_id".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
            IndexColumn::Column {
                column_name: "c_last".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
        ],
    )
    .unwrap();

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

    // Query with ORDER BY on non-indexed column
    let query = "SELECT c_id, c_first, c_balance FROM customer WHERE c_w_id = 1 AND c_d_id = 1 AND c_last = 'SMITH' ORDER BY c_first";
    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 SMITH customers ordered by first name (Alice, Bob)
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].values[1], SqlValue::Varchar(arcstr::ArcStr::from("Alice")));
        assert_eq!(result[1].values[1], SqlValue::Varchar(arcstr::ArcStr::from("Bob")));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_secondary_index_select_star() {
    let mut db = create_customer_db();

    // Create secondary index on c_last
    db.create_index(
        "idx_customer_last".to_string(),
        "customer".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "c_last".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

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

    // Query with SELECT *
    let query = "SELECT * FROM customer WHERE c_last = 'BROWN'";
    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 one row (Frank Brown)
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].values[0], SqlValue::Integer(6)); // c_id
        assert_eq!(result[0].values[3], SqlValue::Varchar(arcstr::ArcStr::from("BROWN"))); // c_last
        assert_eq!(result[0].values[4], SqlValue::Varchar(arcstr::ArcStr::from("Frank")));
    // c_first
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_secondary_index_no_match() {
    let mut db = create_customer_db();

    // Create secondary index on c_last
    db.create_index(
        "idx_customer_last".to_string(),
        "customer".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "c_last".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

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

    // Query for non-existent value
    let query = "SELECT c_id FROM customer WHERE c_last = 'NOTEXIST'";
    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 empty result
        assert_eq!(result.len(), 0);
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_secondary_index_with_limit() {
    let mut db = create_customer_db();

    // Create secondary index on c_last
    db.create_index(
        "idx_customer_last".to_string(),
        "customer".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "c_last".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

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

    // Query with LIMIT
    let query =
        "SELECT c_id, c_first FROM customer WHERE c_last = 'SMITH' ORDER BY c_first LIMIT 2";
    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 only 2 rows
        assert_eq!(result.len(), 2);
    } else {
        panic!("Expected SELECT statement");
    }
}

/// Regression test for issue #3354: Secondary index fast path must apply residual predicates
///
/// When using a secondary index for lookup, any predicates NOT covered by the index
/// (i.e., non-equality predicates or predicates on columns not in the index) must still
/// be applied as a filter.
///
/// Bug: Query `WHERE col3 = 81814 AND col0 < 1013` with index on col3 would:
/// 1. Use index to find rows where col3 = 81814
/// 2. Return rows WITHOUT checking `col0 < 1013`
///
/// This test verifies that residual predicates are correctly applied.
#[test]
fn test_secondary_index_residual_predicate_filter() {
    let mut db = Database::new();
    db.catalog.set_case_sensitive_identifiers(false);

    // Create simple table with pk, col0, col3
    let schema = TableSchema::new(
        "tab1".to_string(),
        vec![
            ColumnSchema::new("pk".to_string(), DataType::Integer, false),
            ColumnSchema::new("col0".to_string(), DataType::Integer, false),
            ColumnSchema::new("col3".to_string(), DataType::Integer, false),
        ],
    );
    db.create_table(schema).unwrap();

    // Create secondary index on col3 only
    db.create_index(
        "idx_tab1_3".to_string(),
        "tab1".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "col3".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

    // Insert row: pk=881, col0=20123, col3=81814
    // Note: col0=20123 does NOT satisfy col0 < 1013
    db.insert_row(
        "tab1",
        Row::new(vec![SqlValue::Integer(881), SqlValue::Integer(20123), SqlValue::Integer(81814)]),
    )
    .unwrap();

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

    // Query: col3 = 81814 (uses index) AND col0 < 1013 (residual filter)
    // The row has col0=20123 which does NOT satisfy col0 < 1013, so should return 0 rows
    let query = "SELECT pk, col0, col3 FROM tab1 WHERE col3 = 81814 AND col0 < 1013";
    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 0 rows because col0=20123 does NOT satisfy col0 < 1013
        assert_eq!(result.len(), 0, "Residual predicate col0 < 1013 should filter out the row");
    } else {
        panic!("Expected SELECT statement");
    }
}

/// Test that rows matching both index predicate AND residual predicate are returned
#[test]
fn test_secondary_index_residual_predicate_match() {
    let mut db = Database::new();
    db.catalog.set_case_sensitive_identifiers(false);

    // Create simple table with pk, col0, col3
    let schema = TableSchema::new(
        "tab1".to_string(),
        vec![
            ColumnSchema::new("pk".to_string(), DataType::Integer, false),
            ColumnSchema::new("col0".to_string(), DataType::Integer, false),
            ColumnSchema::new("col3".to_string(), DataType::Integer, false),
        ],
    );
    db.create_table(schema).unwrap();

    // Create secondary index on col3 only
    db.create_index(
        "idx_tab1_3".to_string(),
        "tab1".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "col3".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

    // Insert two rows with same col3 value but different col0 values
    // Row 881: col0=20123 (does NOT satisfy col0 < 1013)
    // Row 882: col0=500 (DOES satisfy col0 < 1013)
    db.insert_row(
        "tab1",
        Row::new(vec![SqlValue::Integer(881), SqlValue::Integer(20123), SqlValue::Integer(81814)]),
    )
    .unwrap();

    db.insert_row(
        "tab1",
        Row::new(vec![SqlValue::Integer(882), SqlValue::Integer(500), SqlValue::Integer(81814)]),
    )
    .unwrap();

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

    // Query: col3 = 81814 (uses index, finds both rows) AND col0 < 1013 (residual filter)
    // Only row 882 should be returned (col0=500 < 1013)
    let query = "SELECT pk, col0, col3 FROM tab1 WHERE col3 = 81814 AND col0 < 1013";
    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 only 1 row (pk=882)
        assert_eq!(result.len(), 1, "Should return only the row matching residual predicate");
        assert_eq!(result[0].values[0], SqlValue::Integer(882), "Should return pk=882");
        assert_eq!(result[0].values[1], SqlValue::Integer(500), "Should return col0=500");
    } else {
        panic!("Expected SELECT statement");
    }
}