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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! Integration tests for ORDER BY index optimization
//!
//! These tests verify that the executor correctly uses indexes to satisfy ORDER BY clauses
//! when appropriate indexes exist, avoiding the need for an explicit sort step.
//!
//! Coverage:
//! - Single-column ORDER BY with ASC index
//! - Single-column ORDER BY DESC with index reversal
//! - Multi-column ORDER BY with composite index
//! - ORDER BY with WHERE clause combined
//! - Partial index matches (should fall back to sort)
//! - Mixed ASC/DESC directions
//! - Primary key index usage
//! - ORDER BY with positional references
//! - ORDER BY with aliases
//! - ORDER BY with NULL values

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 products table for ORDER BY tests
fn create_products_db() -> Database {
    let mut db = Database::new();
    db.catalog.set_case_sensitive_identifiers(false);

    // Create products table with columns suitable for ORDER BY testing
    let products_schema = TableSchema::new(
        "products".to_string(),
        vec![
            ColumnSchema::new("id".to_string(), DataType::Integer, false),
            ColumnSchema::new(
                "name".to_string(),
                DataType::Varchar { max_length: Some(100) },
                false,
            ),
            ColumnSchema::new("price".to_string(), DataType::Integer, false),
            ColumnSchema::new(
                "category".to_string(),
                DataType::Varchar { max_length: Some(50) },
                false,
            ),
            ColumnSchema::new("stock".to_string(), DataType::Integer, false),
        ],
    );

    db.create_table(products_schema).unwrap();

    // Insert test data (intentionally unordered)
    db.insert_row(
        "products",
        Row::new(vec![
            SqlValue::Integer(3),
            SqlValue::Varchar(arcstr::ArcStr::from("Keyboard")),
            SqlValue::Integer(80),
            SqlValue::Varchar(arcstr::ArcStr::from("Electronics")),
            SqlValue::Integer(50),
        ]),
    )
    .unwrap();

    db.insert_row(
        "products",
        Row::new(vec![
            SqlValue::Integer(1),
            SqlValue::Varchar(arcstr::ArcStr::from("Mouse")),
            SqlValue::Integer(30),
            SqlValue::Varchar(arcstr::ArcStr::from("Electronics")),
            SqlValue::Integer(100),
        ]),
    )
    .unwrap();

    db.insert_row(
        "products",
        Row::new(vec![
            SqlValue::Integer(5),
            SqlValue::Varchar(arcstr::ArcStr::from("Monitor")),
            SqlValue::Integer(300),
            SqlValue::Varchar(arcstr::ArcStr::from("Electronics")),
            SqlValue::Integer(20),
        ]),
    )
    .unwrap();

    db.insert_row(
        "products",
        Row::new(vec![
            SqlValue::Integer(2),
            SqlValue::Varchar(arcstr::ArcStr::from("Desk")),
            SqlValue::Integer(200),
            SqlValue::Varchar(arcstr::ArcStr::from("Furniture")),
            SqlValue::Integer(15),
        ]),
    )
    .unwrap();

    db.insert_row(
        "products",
        Row::new(vec![
            SqlValue::Integer(4),
            SqlValue::Varchar(arcstr::ArcStr::from("Chair")),
            SqlValue::Integer(150),
            SqlValue::Varchar(arcstr::ArcStr::from("Furniture")),
            SqlValue::Integer(30),
        ]),
    )
    .unwrap();

    db
}

/// Create a test database with nullable columns for NULL handling tests
fn create_nullable_db() -> Database {
    let mut db = Database::new();
    db.catalog.set_case_sensitive_identifiers(false);

    let schema = TableSchema::new(
        "items".to_string(),
        vec![
            ColumnSchema::new("id".to_string(), DataType::Integer, false),
            ColumnSchema::new("value".to_string(), DataType::Integer, true), // nullable
        ],
    );

    db.create_table(schema).unwrap();

    // Insert data with NULLs
    db.insert_row("items", Row::new(vec![SqlValue::Integer(1), SqlValue::Integer(10)])).unwrap();
    db.insert_row("items", Row::new(vec![SqlValue::Integer(2), SqlValue::Null])).unwrap();
    db.insert_row("items", Row::new(vec![SqlValue::Integer(3), SqlValue::Integer(5)])).unwrap();
    db.insert_row("items", Row::new(vec![SqlValue::Integer(4), SqlValue::Null])).unwrap();
    db.insert_row("items", Row::new(vec![SqlValue::Integer(5), SqlValue::Integer(15)])).unwrap();

    db
}

#[test]
fn test_order_by_single_column_asc_with_index() {
    let mut db = create_products_db();

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

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

    // Query with ORDER BY that should use the index
    let query = "SELECT name, price FROM products ORDER BY price ASC";
    let stmt = Parser::parse_sql(query).unwrap();

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

        // Verify results are ordered by price ascending
        assert_eq!(result.len(), 5);
        assert_eq!(result[0].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Mouse")));
        assert_eq!(result[1].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Keyboard")));
        assert_eq!(result[2].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Chair")));
        assert_eq!(result[3].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Desk")));
        assert_eq!(result[4].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Monitor")));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_order_by_single_column_desc_with_index() {
    let mut db = create_products_db();

    // Create index on price column (ASC) - should be usable for DESC via reversal
    db.create_index(
        "idx_products_price".to_string(),
        "products".to_string(),
        false,
        vec![IndexColumn::Column {
            column_name: "price".to_string(),
            prefix_length: None,
            direction: OrderDirection::Asc,
        }],
    )
    .unwrap();

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

    // Query with ORDER BY DESC - should use index with reversal
    let query = "SELECT name, price FROM products ORDER BY price DESC";
    let stmt = Parser::parse_sql(query).unwrap();

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

        // Verify results are ordered by price descending
        assert_eq!(result.len(), 5);
        assert_eq!(result[0].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Monitor")));
        assert_eq!(result[1].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Desk")));
        assert_eq!(result[2].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Chair")));
        assert_eq!(result[3].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Keyboard")));
        assert_eq!(result[4].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Mouse")));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_order_by_multi_column_with_composite_index() {
    let mut db = create_products_db();

    // Create composite index on (category, price)
    db.create_index(
        "idx_products_category_price".to_string(),
        "products".to_string(),
        false,
        vec![
            IndexColumn::Column {
                column_name: "category".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
            IndexColumn::Column {
                column_name: "price".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
        ],
    )
    .unwrap();

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

    // Query with multi-column ORDER BY matching the index
    let query = "SELECT name, category, price FROM products ORDER BY category, price";
    let stmt = Parser::parse_sql(query).unwrap();

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

        // Verify results are ordered by category, then price
        assert_eq!(result.len(), 5);

        // Electronics products (sorted by price)
        assert_eq!(result[0].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Mouse")));
        assert_eq!(result[0].values[1], SqlValue::Varchar(arcstr::ArcStr::from("Electronics")));

        assert_eq!(result[1].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Keyboard")));
        assert_eq!(result[1].values[1], SqlValue::Varchar(arcstr::ArcStr::from("Electronics")));

        assert_eq!(result[2].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Monitor")));
        assert_eq!(result[2].values[1], SqlValue::Varchar(arcstr::ArcStr::from("Electronics")));

        // Furniture products (sorted by price)
        assert_eq!(result[3].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Chair")));
        assert_eq!(result[3].values[1], SqlValue::Varchar(arcstr::ArcStr::from("Furniture")));

        assert_eq!(result[4].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Desk")));
        assert_eq!(result[4].values[1], SqlValue::Varchar(arcstr::ArcStr::from("Furniture")));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_order_by_with_where_clause() {
    let mut db = create_products_db();

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

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

    // Query with WHERE and ORDER BY - index should still be used for ordering
    let query = "SELECT name, price FROM products WHERE category = 'Electronics' ORDER BY price";
    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 Electronics products, ordered by price
        assert_eq!(result.len(), 3);
        assert_eq!(result[0].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Mouse")));
        assert_eq!(result[1].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Keyboard")));
        assert_eq!(result[2].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Monitor")));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_order_by_partial_index_match_falls_back_to_sort() {
    let mut db = create_products_db();

    // Create composite index on (category, price)
    db.create_index(
        "idx_products_category_price".to_string(),
        "products".to_string(),
        false,
        vec![
            IndexColumn::Column {
                column_name: "category".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
            IndexColumn::Column {
                column_name: "price".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
        ],
    )
    .unwrap();

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

    // Query with ORDER BY that doesn't match index prefix - should fall back to sort
    let query = "SELECT name, price, category FROM products ORDER BY price, category";
    let stmt = Parser::parse_sql(query).unwrap();

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

        // Should still work correctly (via sort), ordered by price then category
        assert_eq!(result.len(), 5);
        assert_eq!(result[0].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Mouse")));
        assert_eq!(result[4].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Monitor")));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_order_by_without_index_uses_sort() {
    let db = create_products_db();
    // Note: No index created - should use sort

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

    // Query with ORDER BY but no suitable index
    let query = "SELECT name, stock FROM products ORDER BY stock";
    let stmt = Parser::parse_sql(query).unwrap();

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

        // Should work correctly via sort
        assert_eq!(result.len(), 5);

        // Verify ordering by stock
        let stocks: Vec<i64> = result
            .iter()
            .map(|row| match &row.values[1] {
                SqlValue::Integer(s) => *s,
                _ => panic!("Expected integer stock"),
            })
            .collect();

        assert_eq!(stocks, vec![15, 20, 30, 50, 100]);
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_order_by_primary_key_implicit_index() {
    let db = create_products_db();

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

    // Query with ORDER BY on id (assuming it's the primary key or has implicit index)
    let query = "SELECT id, name FROM products ORDER BY id";
    let stmt = Parser::parse_sql(query).unwrap();

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

        // Should be ordered by id
        assert_eq!(result.len(), 5);

        let ids: Vec<i64> = result
            .iter()
            .map(|row| match &row.values[0] {
                SqlValue::Integer(id) => *id,
                _ => panic!("Expected integer id"),
            })
            .collect();

        assert_eq!(ids, vec![1, 2, 3, 4, 5]);
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_order_by_mixed_asc_desc_no_index() {
    let mut db = create_products_db();

    // Create index on (category ASC, price ASC)
    db.create_index(
        "idx_products_category_price".to_string(),
        "products".to_string(),
        false,
        vec![
            IndexColumn::Column {
                column_name: "category".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
            IndexColumn::Column {
                column_name: "price".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
        ],
    )
    .unwrap();

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

    // Query with mixed ASC/DESC that doesn't match index - should fall back to sort
    let query = "SELECT name, category, price FROM products ORDER BY category ASC, price DESC";
    let stmt = Parser::parse_sql(query).unwrap();

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

        // Should work correctly via sort
        assert_eq!(result.len(), 5);

        // Electronics products (sorted by price DESC)
        assert_eq!(result[0].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Monitor")));
        assert_eq!(result[1].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Keyboard")));
        assert_eq!(result[2].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Mouse")));

        // Furniture products (sorted by price DESC)
        assert_eq!(result[3].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Desk")));
        assert_eq!(result[4].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Chair")));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_order_by_positional_reference() {
    let mut db = create_products_db();

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

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

    // Query with ORDER BY using positional reference (2 = price column)
    let query = "SELECT name, price FROM products ORDER BY 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 be ordered by price (second column)
        assert_eq!(result.len(), 5);
        assert_eq!(result[0].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Mouse")));
        assert_eq!(result[4].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Monitor")));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_order_by_alias() {
    let mut db = create_products_db();

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

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

    // Query with ORDER BY using alias
    let query = "SELECT name, price AS cost FROM products ORDER BY cost";
    let stmt = Parser::parse_sql(query).unwrap();

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

        // Should be ordered by price (aliased as cost)
        assert_eq!(result.len(), 5);
        assert_eq!(result[0].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Mouse")));
        assert_eq!(result[4].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Monitor")));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_order_by_with_nulls_asc() {
    let mut db = create_nullable_db();

    // 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);

    // Query with ORDER BY on nullable column
    // SQLite semantics: NULL is smallest, so NULLs come first in ASC order
    let query = "SELECT id, value FROM items ORDER BY value ASC";
    let stmt = Parser::parse_sql(query).unwrap();

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

        assert_eq!(result.len(), 5);

        // SQLite: NULL is smallest, so ASC order is: NULL, NULL, 5, 10, 15
        let values: Vec<Option<i64>> = result
            .iter()
            .map(|row| match &row.values[1] {
                SqlValue::Integer(v) => Some(*v),
                SqlValue::Null => None,
                _ => panic!("Expected integer or null"),
            })
            .collect();

        assert_eq!(values[0], None); // NULL (smallest)
        assert_eq!(values[1], None); // NULL (smallest)
        assert_eq!(values[2], Some(5));
        assert_eq!(values[3], Some(10));
        assert_eq!(values[4], Some(15));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_order_by_with_nulls_desc() {
    let mut db = create_nullable_db();

    // 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);

    // Query with ORDER BY DESC - NULLs should still come last
    let query = "SELECT id, value FROM items ORDER BY value DESC";
    let stmt = Parser::parse_sql(query).unwrap();

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

        assert_eq!(result.len(), 5);

        // Values should be ordered: 15, 10, 5, NULL, NULL
        let values: Vec<Option<i64>> = result
            .iter()
            .map(|row| match &row.values[1] {
                SqlValue::Integer(v) => Some(*v),
                SqlValue::Null => None,
                _ => panic!("Expected integer or null"),
            })
            .collect();

        assert_eq!(values[0], Some(15));
        assert_eq!(values[1], Some(10));
        assert_eq!(values[2], Some(5));
        assert_eq!(values[3], None); // NULL
        assert_eq!(values[4], None); // NULL
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_order_by_multi_column_desc_with_index_reversal() {
    let mut db = create_products_db();

    // Create composite index on (category ASC, price ASC)
    db.create_index(
        "idx_products_category_price".to_string(),
        "products".to_string(),
        false,
        vec![
            IndexColumn::Column {
                column_name: "category".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
            IndexColumn::Column {
                column_name: "price".to_string(),
                prefix_length: None,
                direction: OrderDirection::Asc,
            },
        ],
    )
    .unwrap();

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

    // Query with ORDER BY that's the complete opposite - should use index with reversal
    let query = "SELECT name, category, price FROM products ORDER BY category DESC, price DESC";
    let stmt = Parser::parse_sql(query).unwrap();

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

        assert_eq!(result.len(), 5);

        // Furniture products first (sorted by price DESC)
        assert_eq!(result[0].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Desk")));
        assert_eq!(result[0].values[1], SqlValue::Varchar(arcstr::ArcStr::from("Furniture")));

        assert_eq!(result[1].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Chair")));
        assert_eq!(result[1].values[1], SqlValue::Varchar(arcstr::ArcStr::from("Furniture")));

        // Electronics products second (sorted by price DESC)
        assert_eq!(result[2].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Monitor")));
        assert_eq!(result[2].values[1], SqlValue::Varchar(arcstr::ArcStr::from("Electronics")));

        assert_eq!(result[3].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Keyboard")));
        assert_eq!(result[3].values[1], SqlValue::Varchar(arcstr::ArcStr::from("Electronics")));

        assert_eq!(result[4].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Mouse")));
        assert_eq!(result[4].values[1], SqlValue::Varchar(arcstr::ArcStr::from("Electronics")));
    } else {
        panic!("Expected SELECT statement");
    }
}

#[test]
fn test_order_by_limit_with_index() {
    let mut db = create_products_db();

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

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

    // Query with ORDER BY and LIMIT - index should still be used
    let query = "SELECT name, price FROM products ORDER BY price LIMIT 3";
    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 first 3 products ordered by price
        assert_eq!(result.len(), 3);
        assert_eq!(result[0].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Mouse")));
        assert_eq!(result[1].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Keyboard")));
        assert_eq!(result[2].values[0], SqlValue::Varchar(arcstr::ArcStr::from("Chair")));
    } else {
        panic!("Expected SELECT statement");
    }
}