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
//! Tests for HAVING clause with subqueries (Issue #366)
//!
//! SQL:1999 Section 7.8: HAVING clause
//! Tests various subquery types in HAVING: scalar, IN, EXISTS, quantified comparisons

use vibesql_executor::SelectExecutor;

/// Helper to setup test database with sales and targets tables
fn setup_test_database() -> vibesql_storage::Database {
    let mut db = vibesql_storage::Database::new();

    // Sales table
    let sales_schema = vibesql_catalog::TableSchema::new(
        "SALES".to_string(),
        vec![
            vibesql_catalog::ColumnSchema::new(
                "ID".to_string(),
                vibesql_types::DataType::Integer,
                false,
            ),
            vibesql_catalog::ColumnSchema::new(
                "DEPT".to_string(),
                vibesql_types::DataType::Integer,
                false,
            ),
            vibesql_catalog::ColumnSchema::new(
                "AMOUNT".to_string(),
                vibesql_types::DataType::Integer,
                false,
            ),
        ],
    );
    db.create_table(sales_schema).unwrap();

    // Insert sales data
    db.insert_row(
        "SALES",
        vibesql_storage::Row::new(vec![
            vibesql_types::SqlValue::Integer(1),
            vibesql_types::SqlValue::Integer(1), // dept 1
            vibesql_types::SqlValue::Integer(100),
        ]),
    )
    .unwrap();
    db.insert_row(
        "SALES",
        vibesql_storage::Row::new(vec![
            vibesql_types::SqlValue::Integer(2),
            vibesql_types::SqlValue::Integer(1), // dept 1
            vibesql_types::SqlValue::Integer(200),
        ]),
    )
    .unwrap();
    db.insert_row(
        "SALES",
        vibesql_storage::Row::new(vec![
            vibesql_types::SqlValue::Integer(3),
            vibesql_types::SqlValue::Integer(2), // dept 2
            vibesql_types::SqlValue::Integer(50),
        ]),
    )
    .unwrap();
    db.insert_row(
        "SALES",
        vibesql_storage::Row::new(vec![
            vibesql_types::SqlValue::Integer(4),
            vibesql_types::SqlValue::Integer(2), // dept 2
            vibesql_types::SqlValue::Integer(75),
        ]),
    )
    .unwrap();
    db.insert_row(
        "SALES",
        vibesql_storage::Row::new(vec![
            vibesql_types::SqlValue::Integer(5),
            vibesql_types::SqlValue::Integer(3), // dept 3
            vibesql_types::SqlValue::Integer(500),
        ]),
    )
    .unwrap();

    // Targets table for comparison
    let targets_schema = vibesql_catalog::TableSchema::new(
        "TARGETS".to_string(),
        vec![
            vibesql_catalog::ColumnSchema::new(
                "ID".to_string(),
                vibesql_types::DataType::Integer,
                false,
            ),
            vibesql_catalog::ColumnSchema::new(
                "TARGET_AMOUNT".to_string(),
                vibesql_types::DataType::Integer,
                false,
            ),
        ],
    );
    db.create_table(targets_schema).unwrap();

    // Insert target data
    db.insert_row(
        "TARGETS",
        vibesql_storage::Row::new(vec![
            vibesql_types::SqlValue::Integer(1),
            vibesql_types::SqlValue::Integer(200),
        ]),
    )
    .unwrap();

    db
}

#[test]
fn test_having_with_scalar_subquery() {
    let db = setup_test_database();
    let executor = SelectExecutor::new(&db);

    // Find departments where total sales > average of all target amounts
    // Expected: dept 1 (300 > 200), dept 3 (500 > 200)
    // Not: dept 2 (125 < 200)
    let stmt = vibesql_parser::Parser::parse_sql(
        "SELECT dept, SUM(amount) as total \
         FROM sales \
         GROUP BY dept \
         HAVING SUM(amount) > (SELECT AVG(target_amount) FROM targets) \
         ORDER BY dept",
    )
    .unwrap();

    let vibesql_ast::Statement::Select(select_stmt) = stmt else {
        panic!("Expected SELECT statement");
    };

    let rows = executor.execute(&select_stmt).unwrap();

    // Should return dept 1 (300) and dept 3 (500)
    assert_eq!(rows.len(), 2);

    // Check dept 1
    assert_eq!(rows[0].get(0), Some(&vibesql_types::SqlValue::Integer(1)));
    // SQLite's SUM() preserves integer type for integer inputs
    assert_eq!(rows[0].get(1), Some(&vibesql_types::SqlValue::Integer(300)));

    // Check dept 3
    assert_eq!(rows[1].get(0), Some(&vibesql_types::SqlValue::Integer(3)));
    // SQLite's SUM() preserves integer type for integer inputs
    assert_eq!(rows[1].get(1), Some(&vibesql_types::SqlValue::Integer(500)))
}

#[test]
fn test_having_with_scalar_subquery_comparison() {
    let db = setup_test_database();
    let executor = SelectExecutor::new(&db);

    // Find departments where count of sales < maximum target amount
    let stmt = vibesql_parser::Parser::parse_sql(
        "SELECT dept, COUNT(*) as cnt \
         FROM sales \
         GROUP BY dept \
         HAVING COUNT(*) < (SELECT MAX(target_amount) FROM targets)",
    )
    .unwrap();

    let vibesql_ast::Statement::Select(select_stmt) = stmt else {
        panic!("Expected SELECT statement");
    };

    let rows = executor.execute(&select_stmt).unwrap();

    // All departments have count < 200: dept 1 (2), dept 2 (2), dept 3 (1)
    assert_eq!(rows.len(), 3);
}

#[test]
fn test_having_with_exists_subquery() {
    let db = setup_test_database();
    let executor = SelectExecutor::new(&db);

    // Find departments where there exists a target
    // (This will match all departments since targets table has at least one row)
    let stmt = vibesql_parser::Parser::parse_sql(
        "SELECT dept, SUM(amount) as total \
         FROM sales \
         GROUP BY dept \
         HAVING EXISTS (SELECT 1 FROM targets)",
    )
    .unwrap();

    let vibesql_ast::Statement::Select(select_stmt) = stmt else {
        panic!("Expected SELECT statement");
    };

    let rows = executor.execute(&select_stmt).unwrap();

    // All 3 departments should be returned
    assert_eq!(rows.len(), 3);
}

#[test]
fn test_having_with_not_exists_subquery() {
    let db = setup_test_database();
    let executor = SelectExecutor::new(&db);

    // Find departments where there does NOT exist a target > 1000
    let stmt = vibesql_parser::Parser::parse_sql(
        "SELECT dept, SUM(amount) as total \
         FROM sales \
         GROUP BY dept \
         HAVING NOT EXISTS (SELECT 1 FROM targets WHERE target_amount > 1000)",
    )
    .unwrap();

    let vibesql_ast::Statement::Select(select_stmt) = stmt else {
        panic!("Expected SELECT statement");
    };

    let rows = executor.execute(&select_stmt).unwrap();

    // All departments should be returned (no targets > 1000)
    assert_eq!(rows.len(), 3);
}

#[test]
fn test_having_with_in_subquery() {
    let db = setup_test_database();
    let executor = SelectExecutor::new(&db);

    // Find departments where total sales is in the targets table
    let stmt = vibesql_parser::Parser::parse_sql(
        "SELECT dept, SUM(amount) as total \
         FROM sales \
         GROUP BY dept \
         HAVING SUM(amount) IN (SELECT target_amount FROM targets)",
    )
    .unwrap();

    let vibesql_ast::Statement::Select(select_stmt) = stmt else {
        panic!("Expected SELECT statement");
    };

    let rows = executor.execute(&select_stmt).unwrap();

    // No department has total = 200 (the only target value)
    // dept 1: 300, dept 2: 125, dept 3: 500
    assert_eq!(rows.len(), 0);
}

#[test]
fn test_having_with_not_in_subquery() {
    let db = setup_test_database();
    let executor = SelectExecutor::new(&db);

    // Find departments where total sales is NOT in the targets table
    let stmt = vibesql_parser::Parser::parse_sql(
        "SELECT dept, SUM(amount) as total \
         FROM sales \
         GROUP BY dept \
         HAVING SUM(amount) NOT IN (SELECT target_amount FROM targets)",
    )
    .unwrap();

    let vibesql_ast::Statement::Select(select_stmt) = stmt else {
        panic!("Expected SELECT statement");
    };

    let rows = executor.execute(&select_stmt).unwrap();

    // All departments have totals NOT in targets
    assert_eq!(rows.len(), 3);
}

#[test]
fn test_having_with_complex_boolean_expression() {
    let db = setup_test_database();
    let executor = SelectExecutor::new(&db);

    // Complex HAVING with subquery and boolean operators
    let stmt = vibesql_parser::Parser::parse_sql(
        "SELECT dept, SUM(amount) as total \
         FROM sales \
         GROUP BY dept \
         HAVING SUM(amount) > (SELECT AVG(target_amount) FROM targets) \
            AND COUNT(*) >= 1",
    )
    .unwrap();

    let vibesql_ast::Statement::Select(select_stmt) = stmt else {
        panic!("Expected SELECT statement");
    };

    let rows = executor.execute(&select_stmt).unwrap();

    // dept 1 (300) and dept 3 (500) both > 200 and have count >= 1
    assert_eq!(rows.len(), 2);
}

#[test]
fn test_having_without_group_by_with_subquery() {
    let db = setup_test_database();
    let executor = SelectExecutor::new(&db);

    // HAVING without GROUP BY treats entire table as one group
    let stmt = vibesql_parser::Parser::parse_sql(
        "SELECT COUNT(*) as cnt \
         FROM sales \
         HAVING COUNT(*) > (SELECT COUNT(*) FROM targets)",
    )
    .unwrap();

    let vibesql_ast::Statement::Select(select_stmt) = stmt else {
        panic!("Expected SELECT statement");
    };

    let rows = executor.execute(&select_stmt).unwrap();

    // sales has 5 rows, targets has 1 row, so 5 > 1 is true
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].get(0), Some(&vibesql_types::SqlValue::Integer(5)));
}

#[test]
fn test_having_with_quantified_all() {
    let db = setup_test_database();
    let executor = SelectExecutor::new(&db);

    // Find departments where total sales > ALL target amounts
    let stmt = vibesql_parser::Parser::parse_sql(
        "SELECT dept, SUM(amount) as total \
         FROM sales \
         GROUP BY dept \
         HAVING SUM(amount) > ALL (SELECT target_amount FROM targets)",
    )
    .unwrap();

    let vibesql_ast::Statement::Select(select_stmt) = stmt else {
        panic!("Expected SELECT statement");
    };

    let rows = executor.execute(&select_stmt).unwrap();

    // dept 1 (300 > 200), dept 3 (500 > 200) should match
    // dept 2 (125 < 200) should not match
    assert_eq!(rows.len(), 2);
}

#[test]
fn test_having_with_quantified_any() {
    let db = setup_test_database();
    let executor = SelectExecutor::new(&db);

    // Find departments where total sales < ANY target amounts
    let stmt = vibesql_parser::Parser::parse_sql(
        "SELECT dept, SUM(amount) as total \
         FROM sales \
         GROUP BY dept \
         HAVING SUM(amount) < ANY (SELECT target_amount FROM targets)",
    )
    .unwrap();

    let vibesql_ast::Statement::Select(select_stmt) = stmt else {
        panic!("Expected SELECT statement");
    };

    let rows = executor.execute(&select_stmt).unwrap();

    // Only dept 2 (125) is < 200
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].get(0), Some(&vibesql_types::SqlValue::Integer(2)));
}

#[test]
fn test_having_subquery_returns_empty() {
    let db = setup_test_database();
    let executor = SelectExecutor::new(&db);

    // Subquery returns no rows - scalar subquery should return NULL
    let stmt = vibesql_parser::Parser::parse_sql(
        "SELECT dept, SUM(amount) as total \
         FROM sales \
         GROUP BY dept \
         HAVING SUM(amount) > (SELECT target_amount FROM targets WHERE target_amount > 1000)",
    )
    .unwrap();

    let vibesql_ast::Statement::Select(select_stmt) = stmt else {
        panic!("Expected SELECT statement");
    };

    let rows = executor.execute(&select_stmt).unwrap();

    // Comparison with NULL returns NULL, HAVING filters out non-TRUE results
    assert_eq!(rows.len(), 0);
}

#[test]
fn test_having_with_multiple_aggregates_and_subquery() {
    let db = setup_test_database();
    let executor = SelectExecutor::new(&db);

    // Multiple aggregates in HAVING with subquery
    let stmt = vibesql_parser::Parser::parse_sql(
        "SELECT dept, SUM(amount) as total, AVG(amount) as avg_amt \
         FROM sales \
         GROUP BY dept \
         HAVING SUM(amount) > (SELECT AVG(target_amount) FROM targets) \
            AND AVG(amount) > 100",
    )
    .unwrap();

    let vibesql_ast::Statement::Select(select_stmt) = stmt else {
        panic!("Expected SELECT statement");
    };

    let rows = executor.execute(&select_stmt).unwrap();

    // dept 1: sum=300 (>200), avg=150 (>100) ✓
    // dept 2: sum=125 (<200) ✗
    // dept 3: sum=500 (>200), avg=500 (>100) ✓
    assert_eq!(rows.len(), 2);
}