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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
//! SQLite Schema Virtual Table
//!
//! Implements `sqlite_master` (and its alias `sqlite_schema`) for SQLite compatibility.
//! These virtual tables return metadata about database objects in the standard SQLite format.
//!
//! Schema:
//! ```sql
//! CREATE TABLE sqlite_master (
//!   type TEXT,      -- 'table', 'index', 'view', 'trigger'
//!   name TEXT,      -- name of the object
//!   tbl_name TEXT,  -- table the object is associated with
//!   rootpage INT,   -- internal (always 0 for VibeSQL)
//!   sql TEXT        -- CREATE statement that created the object
//! );
//! ```
//!
//! Reference: https://www.sqlite.org/schematab.html

use vibesql_ast::pretty_print::ToSql;
use vibesql_catalog::{ColumnSchema, ReferentialAction, SortOrder, TableSchema};
use vibesql_storage::Row;
use vibesql_types::{DataType, SqlValue};

use crate::{errors::ExecutorError, select::SelectResult};

/// Check if a table reference is sqlite_master or sqlite_schema
pub fn is_sqlite_schema_table(table_name: &str) -> bool {
    let normalized = table_name.to_lowercase();
    matches!(normalized.as_str(), "sqlite_master" | "sqlite_schema")
}

/// Check whether an object name is reserved for internal use.
///
/// SQLite reserves the `sqlite_` prefix for its own schema objects
/// (`sqlite_master`, `sqlite_sequence`, `sqlite_autoindex_*`, …) and rejects any
/// *user* `CREATE TABLE`/`CREATE INDEX` whose name begins with that prefix:
///
/// ```text
/// sqlite> CREATE TABLE sqlite_foo(x);
/// Error: object name reserved for internal use: sqlite_foo
/// ```
///
/// The match is case-insensitive (issue #5553 identifier folding); `SQLITE_foo`
/// is rejected just like `sqlite_foo`. This guard applies ONLY to user-issued
/// DDL — VibeSQL's own internal schema objects (sqlite_master, the
/// `sqlite_autoindex_*` auto-indexes, etc.) are created through dedicated
/// catalog APIs that never route through the user-facing executors, so they are
/// unaffected.
pub fn is_reserved_object_name(name: &str) -> bool {
    name.len() >= "sqlite_".len()
        && name.as_bytes()[.."sqlite_".len()].eq_ignore_ascii_case(b"sqlite_")
}

/// Check if a table reference is sqlite_temp_master or sqlite_temp_schema.
///
/// These are the temp-schema introspection views: they list objects that live
/// in the session temp schema (temp tables, and indexes on temp tables), and
/// are the temp-schema counterpart to `sqlite_master`. See issue #5513.
pub fn is_sqlite_temp_schema_table(table_name: &str) -> bool {
    let normalized = table_name.to_lowercase();
    matches!(normalized.as_str(), "sqlite_temp_master" | "sqlite_temp_schema")
}

/// Get the schema for sqlite_master/sqlite_schema
pub fn get_sqlite_schema_table_schema() -> TableSchema {
    TableSchema::new(
        "sqlite_master".to_string(),
        vec![
            ColumnSchema::new("type".to_string(), DataType::Varchar { max_length: None }, false),
            ColumnSchema::new("name".to_string(), DataType::Varchar { max_length: None }, false),
            ColumnSchema::new(
                "tbl_name".to_string(),
                DataType::Varchar { max_length: None },
                false,
            ),
            ColumnSchema::new("rootpage".to_string(), DataType::Integer, false),
            ColumnSchema::new("sql".to_string(), DataType::Varchar { max_length: None }, true),
        ],
    )
}

/// Build a single sqlite_master-format row.
fn schema_row(obj_type: &str, name: &str, tbl_name: &str, sql: String) -> Row {
    Row::new(vec![
        SqlValue::Varchar(arcstr::ArcStr::from(obj_type)),
        SqlValue::Varchar(arcstr::ArcStr::from(name)),
        SqlValue::Varchar(arcstr::ArcStr::from(tbl_name)),
        SqlValue::Integer(0), // rootpage - always 0 for VibeSQL
        SqlValue::Varchar(arcstr::ArcStr::from(sql)),
    ])
}

/// Execute a `sqlite_master` / `sqlite_schema` query.
///
/// Lists **main-schema** objects only. Temp-schema objects (temp tables and
/// indexes on temp tables) are reported by `sqlite_temp_master`, matching
/// SQLite 3.51.0 where a temp-table index appears in `sqlite_temp_master` and
/// never in `sqlite_master`. See issue #5513.
pub fn execute_sqlite_schema_query(
    catalog: &vibesql_catalog::Catalog,
) -> Result<SelectResult, ExecutorError> {
    let schema = get_sqlite_schema_table_schema();
    let column_names: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
    let mut rows = Vec::new();

    // Add tables. `list_tables()` returns the current (main) schema only, so
    // temp tables are already excluded here.
    for table_name in catalog.list_tables() {
        if let Some(table) = catalog.get_table(&table_name) {
            let sql = generate_create_table_sql(table);
            // SQLite echoes the *original* declared case in sqlite_master, even
            // though lookups are case-folded (issue #5553). `table.name` retains
            // the original spelling; `table_name` is the lowercase catalog key.
            rows.push(schema_row("table", &table.name, &table.name, sql));
        }
    }

    // Add indexes owned by the main schema. Temp-table indexes are tagged with
    // their temp schema (#5513) and surface only via sqlite_temp_master.
    for index in catalog.get_schema_indexes(vibesql_catalog::DEFAULT_SCHEMA) {
        let sql = generate_create_index_sql(index);
        rows.push(schema_row("index", &index.name, &index.table_name, sql));
    }

    // Add views. Temp views are tagged with the `temp` schema (#5541) and
    // surface only via sqlite_temp_master, so skip them here.
    for view_name in catalog.list_views() {
        if let Some(view) = catalog.get_view(&view_name) {
            if view.is_temp() {
                continue;
            }
            let sql = generate_create_view_sql(view);
            // tbl_name is same as name for views
            rows.push(schema_row("view", &view.name, &view.name, sql));
        }
    }

    // Add triggers. Temp triggers are tagged with the `temp` schema (#5532)
    // and surface only via sqlite_temp_master, so skip them here.
    for trigger_name in catalog.list_triggers() {
        if let Some(trigger) = catalog.get_trigger(&trigger_name) {
            if trigger.is_temp() {
                continue;
            }
            let sql = generate_create_trigger_sql(trigger);
            rows.push(schema_row("trigger", &trigger.name, &trigger.table_name, sql));
        }
    }

    Ok(SelectResult { columns: column_names, rows })
}

/// Execute a `sqlite_temp_master` / `sqlite_temp_schema` query.
///
/// Lists the session's **temp-schema** objects: temp tables, indexes on temp
/// tables, temp views, and temp triggers. Mirrors SQLite 3.51.0, where:
///   CREATE TEMP TABLE t(a); CREATE INDEX i ON t(a);
///   CREATE TEMP VIEW v AS SELECT 1; CREATE TEMP TRIGGER tr AFTER INSERT ON t ...;
///   SELECT name,type FROM sqlite_temp_master;  -- lists t, i, v and tr
/// while `sqlite_master` lists none of them. Temp tables/indexes were added in
/// #5513 (PR #5539); temp views/triggers in #5541.
pub fn execute_sqlite_temp_schema_query(
    catalog: &vibesql_catalog::Catalog,
) -> Result<SelectResult, ExecutorError> {
    let schema = get_sqlite_schema_table_schema();
    let column_names: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
    let mut rows = Vec::new();

    let temp_schema = catalog.temp_schema_name();

    // Add temp tables (objects living in the session temp schema).
    for table_name in catalog.list_tables_in_schema(temp_schema) {
        // Look up via the temp-qualified name so we read the temp copy even when
        // a same-named main table shadows it for unqualified lookups.
        let qualified = format!("{}.{}", temp_schema, table_name);
        if let Some(table) = catalog.get_table(&qualified) {
            let sql = generate_create_table_sql(table);
            // Echo the original declared case (issue #5553); `table_name` is the
            // lowercase catalog key.
            rows.push(schema_row("table", &table.name, &table.name, sql));
        }
    }

    // Add indexes owned by the temp schema.
    for index in catalog.get_schema_indexes(temp_schema) {
        let sql = generate_create_index_sql(index);
        rows.push(schema_row("index", &index.name, &index.table_name, sql));
    }

    // Add temp views. Views are stored flat in the catalog (not partitioned by
    // schema), so filter on the per-view `temp` tag set at CREATE TEMP VIEW
    // time (#5541).
    for view_name in catalog.list_views() {
        if let Some(view) = catalog.get_view(&view_name) {
            if !view.is_temp() {
                continue;
            }
            let sql = generate_create_view_sql(view);
            rows.push(schema_row("view", &view.name, &view.name, sql));
        }
    }

    // Add temp triggers. Triggers are also stored flat; filter on the `temp`
    // schema tag from CREATE TEMP TRIGGER (#5532).
    for trigger_name in catalog.list_triggers() {
        if let Some(trigger) = catalog.get_trigger(&trigger_name) {
            if !trigger.is_temp() {
                continue;
            }
            let sql = generate_create_trigger_sql(trigger);
            rows.push(schema_row("trigger", &trigger.name, &trigger.table_name, sql));
        }
    }

    Ok(SelectResult { columns: column_names, rows })
}

/// Generate CREATE TABLE SQL statement for a table
fn generate_create_table_sql(table: &TableSchema) -> String {
    // SQLite stores the original CREATE TABLE statement byte-verbatim in
    // sqlite_master.sql (whitespace and formatting preserved). When we captured
    // the original source text at CREATE time (issue #5619), return it as-is
    // rather than reconstructing a normalized form from the parsed schema. We
    // only reconstruct when the verbatim text is unavailable (e.g. schemas built
    // programmatically, or after ALTER TABLE invalidated the stale source).
    if let Some(ref src) = table.sql_source {
        return src.clone();
    }

    let mut sql = format!("CREATE TABLE {} (\n", table.name);
    let mut definitions: Vec<String> = Vec::new();

    // Add column definitions
    for col in &table.columns {
        let mut col_def = format!("  {} {}", col.name, format_data_type(&col.data_type));

        // Handle generated columns (AS expression syntax)
        if let Some(ref generated_expr) = col.generated_expr {
            col_def.push_str(&format!(" AS ({})", format_expression(generated_expr)));
        } else {
            // Only non-generated columns can have NOT NULL and DEFAULT
            if !col.nullable {
                col_def.push_str(" NOT NULL");
            }

            if let Some(ref default) = col.default_value {
                col_def.push_str(&format!(" DEFAULT {}", format_expression(default)));
            }
        }

        definitions.push(col_def);
    }

    // Add PRIMARY KEY constraint
    if let Some(ref pk_cols) = table.primary_key {
        definitions.push(format!("  PRIMARY KEY ({})", pk_cols.join(", ")));
    }

    // Add UNIQUE constraints
    for unique_cols in &table.unique_constraints {
        definitions.push(format!("  UNIQUE ({})", unique_cols.join(", ")));
    }

    // Add FOREIGN KEY constraints
    for fk in &table.foreign_keys {
        let mut fk_def = format!(
            "  FOREIGN KEY ({}) REFERENCES {} ({})",
            fk.column_names.join(", "),
            fk.parent_table,
            fk.parent_column_names.join(", ")
        );

        // Add ON DELETE action if not NO ACTION
        if fk.on_delete != ReferentialAction::NoAction {
            fk_def.push_str(&format!(" ON DELETE {}", format_referential_action(&fk.on_delete)));
        }

        // Add ON UPDATE action if not NO ACTION
        if fk.on_update != ReferentialAction::NoAction {
            fk_def.push_str(&format!(" ON UPDATE {}", format_referential_action(&fk.on_update)));
        }

        // Emit DEFERRABLE clause when non-default. Matches SQLite's
        // sqlite_master format and the `introspection.rs` SHOW CREATE
        // TABLE wiring landed in Phase C3 of #5085.
        if fk.is_deferrable {
            if fk.initially_deferred {
                fk_def.push_str(" DEFERRABLE INITIALLY DEFERRED");
            } else {
                fk_def.push_str(" DEFERRABLE INITIALLY IMMEDIATE");
            }
        }

        definitions.push(fk_def);
    }

    // Add CHECK constraints
    for (name, expr) in &table.check_constraints {
        definitions.push(format!("  CONSTRAINT {} CHECK ({})", name, format_expression(expr)));
    }

    sql.push_str(&definitions.join(",\n"));
    sql.push_str("\n)");

    sql
}

/// Generate CREATE INDEX SQL statement for an index
fn generate_create_index_sql(index: &vibesql_catalog::IndexMetadata) -> String {
    let unique_str = if index.is_unique { "UNIQUE " } else { "" };

    let columns: Vec<String> = index
        .columns
        .iter()
        .map(|col| {
            let order_str = match col.order() {
                SortOrder::Ascending => "",
                SortOrder::Descending => " DESC",
            };
            match col {
                vibesql_catalog::IndexedColumn::Column { column_name, prefix_length, .. } => {
                    let prefix_str = prefix_length.map(|l| format!("({})", l)).unwrap_or_default();
                    format!("{}{}{}", column_name, prefix_str, order_str)
                }
                vibesql_catalog::IndexedColumn::Expression { expr, .. } => {
                    // For expression indexes, wrap the expression in parentheses
                    format!("({}){}", expr.to_sql(), order_str)
                }
            }
        })
        .collect();

    format!(
        "CREATE {}INDEX {} ON {}({})",
        unique_str,
        index.name,
        index.table_name,
        columns.join(", ")
    )
}

/// Generate CREATE VIEW SQL statement for a view
fn generate_create_view_sql(view: &vibesql_catalog::ViewDefinition) -> String {
    // Use stored SQL definition if available
    if let Some(ref sql) = view.sql_definition {
        return sql.clone();
    }

    // Otherwise generate from the view definition
    let columns_str =
        view.columns.as_ref().map(|cols| format!(" ({})", cols.join(", "))).unwrap_or_default();

    // Use the ToSql trait to generate valid SQL from the AST
    use vibesql_ast::pretty_print::ToSql;
    format!("CREATE VIEW {}{} AS {}", view.name, columns_str, view.query.to_sql())
}

/// Generate CREATE TRIGGER SQL statement for a trigger
fn generate_create_trigger_sql(trigger: &vibesql_catalog::TriggerDefinition) -> String {
    use vibesql_ast::{TriggerAction, TriggerEvent, TriggerGranularity, TriggerTiming};

    // Prefer the original SQL text when available so `sqlite_master.sql` matches
    // SQLite's verbatim form (no injected BEFORE/FOR EACH ROW, original spacing
    // and quoting preserved). This mirrors `generate_create_view_sql` and is the
    // form kept consistent by `crate::trigger_rename` across ALTER TABLE RENAME.
    // SQLite stores the statement text without the trailing `;`, so strip one if
    // present.
    if let Some(ref sql) = trigger.sql_definition {
        let trimmed = sql.trim_end();
        let trimmed = trimmed.strip_suffix(';').unwrap_or(trimmed);
        return trimmed.trim_end().to_string();
    }

    let timing = match trigger.timing {
        TriggerTiming::Before => "BEFORE",
        TriggerTiming::After => "AFTER",
        TriggerTiming::InsteadOf => "INSTEAD OF",
    };

    let granularity = match trigger.granularity {
        TriggerGranularity::Row => "ROW",
        TriggerGranularity::Statement => "STATEMENT",
    };

    let event = match &trigger.event {
        TriggerEvent::Insert => "INSERT".to_string(),
        TriggerEvent::Update(None) => "UPDATE".to_string(),
        TriggerEvent::Update(Some(cols)) => format!("UPDATE OF {}", cols.join(", ")),
        TriggerEvent::Delete => "DELETE".to_string(),
    };

    // Include WHEN clause if present
    let when_clause = trigger
        .when_condition
        .as_ref()
        .map(|expr| format!(" WHEN ({})", format_expression(expr)))
        .unwrap_or_default();

    // Include trigger body from TriggerAction
    let body = match &trigger.triggered_action {
        TriggerAction::RawSql(sql) => sql.clone(),
    };

    format!(
        "CREATE TRIGGER {} {} {} ON {} FOR EACH {}{}{}",
        trigger.name, timing, event, trigger.table_name, granularity, when_clause, body
    )
}

/// Format a DataType as a SQL string
fn format_data_type(dt: &DataType) -> String {
    match dt {
        DataType::Integer => "INTEGER".to_string(),
        DataType::Smallint => "SMALLINT".to_string(),
        DataType::Bigint => "BIGINT".to_string(),
        DataType::Unsigned => "UNSIGNED BIGINT".to_string(),
        DataType::Real => "REAL".to_string(),
        DataType::Float { precision } => format!("FLOAT({})", precision),
        DataType::DoublePrecision => "DOUBLE PRECISION".to_string(),
        DataType::Numeric { precision, scale } => format!("NUMERIC({}, {})", precision, scale),
        DataType::Decimal { precision, scale } => format!("DECIMAL({}, {})", precision, scale),
        DataType::Varchar { max_length } => {
            if let Some(len) = max_length {
                format!("VARCHAR({})", len)
            } else {
                "TEXT".to_string()
            }
        }
        DataType::Character { length } => format!("CHAR({})", length),
        DataType::CharacterLargeObject => "TEXT".to_string(),
        DataType::Name => "TEXT".to_string(),
        DataType::Boolean => "BOOLEAN".to_string(),
        DataType::Date => "DATE".to_string(),
        DataType::Time { with_timezone } => {
            if *with_timezone {
                "TIME WITH TIME ZONE".to_string()
            } else {
                "TIME".to_string()
            }
        }
        DataType::Timestamp { with_timezone } => {
            if *with_timezone {
                "TIMESTAMP WITH TIME ZONE".to_string()
            } else {
                "TIMESTAMP".to_string()
            }
        }
        DataType::Interval { start_field, end_field } => {
            if let Some(end) = end_field {
                format!("INTERVAL {:?} TO {:?}", start_field, end)
            } else {
                format!("INTERVAL {:?}", start_field)
            }
        }
        DataType::BinaryLargeObject => "BLOB".to_string(),
        DataType::Bit { length } => {
            if let Some(len) = length {
                format!("BIT({})", len)
            } else {
                "BIT".to_string()
            }
        }
        DataType::UserDefined { type_name } => type_name.clone(),
        DataType::Vector { dimensions } => format!("VECTOR({})", dimensions),
        DataType::Null => "NULL".to_string(),
    }
}

/// Format a referential action as a SQL string
fn format_referential_action(action: &ReferentialAction) -> &'static str {
    match action {
        ReferentialAction::NoAction => "NO ACTION",
        ReferentialAction::Restrict => "RESTRICT",
        ReferentialAction::Cascade => "CASCADE",
        ReferentialAction::SetNull => "SET NULL",
        ReferentialAction::SetDefault => "SET DEFAULT",
    }
}

/// Format an expression for SQL output
fn format_expression(expr: &vibesql_ast::Expression) -> String {
    use vibesql_ast::pretty_print::ToSql;
    expr.to_sql()
}

#[cfg(test)]
mod tests {
    use vibesql_catalog::{Catalog, IndexMetadata, IndexType, IndexedColumn};

    use super::*;

    #[test]
    fn test_is_sqlite_schema_table() {
        assert!(is_sqlite_schema_table("sqlite_master"));
        assert!(is_sqlite_schema_table("sqlite_schema"));
        assert!(is_sqlite_schema_table("SQLITE_MASTER"));
        assert!(is_sqlite_schema_table("SQLITE_SCHEMA"));
        assert!(is_sqlite_schema_table("Sqlite_Master"));
        assert!(!is_sqlite_schema_table("users"));
        assert!(!is_sqlite_schema_table("sqlite_stat1"));
        assert!(!is_sqlite_schema_table("information_schema.tables"));
        // sqlite_temp_master is a distinct view, not sqlite_master.
        assert!(!is_sqlite_schema_table("sqlite_temp_master"));
    }

    #[test]
    fn test_is_sqlite_temp_schema_table() {
        assert!(is_sqlite_temp_schema_table("sqlite_temp_master"));
        assert!(is_sqlite_temp_schema_table("sqlite_temp_schema"));
        assert!(is_sqlite_temp_schema_table("SQLITE_TEMP_MASTER"));
        assert!(is_sqlite_temp_schema_table("Sqlite_Temp_Schema"));
        assert!(!is_sqlite_temp_schema_table("sqlite_master"));
        assert!(!is_sqlite_temp_schema_table("users"));
    }

    #[test]
    fn test_temp_index_separated_from_main_in_schema_views() {
        // #5513: a temp-schema index appears in sqlite_temp_master and is
        // excluded from sqlite_master; a main index is the reverse.
        let mut catalog = Catalog::new();

        // main.t with a main index.
        let main_table = TableSchema::new(
            "t".to_string(),
            vec![ColumnSchema::new("a".to_string(), DataType::Integer, true)],
        );
        catalog.create_table(main_table).unwrap();
        catalog
            .add_index(IndexMetadata::new(
                "main_i".to_string(),
                "t".to_string(),
                IndexType::BTree,
                vec![IndexedColumn::new_column("a".to_string(), SortOrder::Ascending)],
                false,
            ))
            .unwrap();

        // temp.tt with a temp index.
        let temp_schema = catalog.temp_schema_name().to_string();
        let temp_table = TableSchema::new(
            "tt".to_string(),
            vec![ColumnSchema::new("a".to_string(), DataType::Integer, true)],
        );
        catalog.create_table_in_schema(&temp_schema, temp_table).unwrap();
        catalog
            .add_index(
                IndexMetadata::new(
                    "temp_i".to_string(),
                    "tt".to_string(),
                    IndexType::BTree,
                    vec![IndexedColumn::new_column("a".to_string(), SortOrder::Ascending)],
                    false,
                )
                .with_schema(temp_schema.clone()),
            )
            .unwrap();

        let master = execute_sqlite_schema_query(&catalog).unwrap();
        let master_names: Vec<String> = master
            .rows
            .iter()
            .map(|r| match &r.values[1] {
                SqlValue::Varchar(s) => s.to_string(),
                _ => String::new(),
            })
            .collect();
        assert!(master_names.contains(&"main_i".to_string()), "master should list main index");
        assert!(!master_names.contains(&"temp_i".to_string()), "master must exclude temp index");

        let temp_master = execute_sqlite_temp_schema_query(&catalog).unwrap();
        let temp_names: Vec<String> = temp_master
            .rows
            .iter()
            .map(|r| match &r.values[1] {
                SqlValue::Varchar(s) => s.to_string(),
                _ => String::new(),
            })
            .collect();
        assert!(temp_names.contains(&"temp_i".to_string()), "temp_master should list temp index");
        assert!(temp_names.contains(&"tt".to_string()), "temp_master should list temp table");
        assert!(!temp_names.contains(&"main_i".to_string()), "temp_master must exclude main index");
    }

    #[test]
    fn test_temp_view_and_trigger_separated_from_main_in_schema_views() {
        // #5541: temp views/triggers appear in sqlite_temp_master and are
        // excluded from sqlite_master; main views/triggers are the reverse.
        use vibesql_ast::{TriggerAction, TriggerEvent, TriggerGranularity, TriggerTiming};
        use vibesql_catalog::{TriggerDefinition, ViewDefinition};

        let mut catalog = Catalog::new();

        // A base table for the triggers to target.
        let base = TableSchema::new(
            "t".to_string(),
            vec![ColumnSchema::new("a".to_string(), DataType::Integer, true)],
        );
        catalog.create_table(base).unwrap();

        // main view + temp view.
        catalog
            .create_view(ViewDefinition::new(
                "main_v".to_string(),
                None,
                create_minimal_select_stmt(),
                false,
            ))
            .unwrap();
        catalog
            .create_view(
                ViewDefinition::new("temp_v".to_string(), None, create_minimal_select_stmt(), false)
                    .with_schema(Some("temp".to_string())),
            )
            .unwrap();

        // main trigger + temp trigger.
        let mk_trigger = |name: &str| {
            TriggerDefinition::new(
                name.to_string(),
                TriggerTiming::After,
                TriggerEvent::Insert,
                "t".to_string(),
                TriggerGranularity::Row,
                None,
                TriggerAction::RawSql("SELECT 1".to_string()),
            )
        };
        catalog.create_trigger(mk_trigger("main_tr")).unwrap();
        catalog
            .create_trigger(mk_trigger("temp_tr").with_schema(Some("temp".to_string())))
            .unwrap();

        let names = |result: &SelectResult| -> Vec<String> {
            result
                .rows
                .iter()
                .map(|r| match &r.values[1] {
                    SqlValue::Varchar(s) => s.to_string(),
                    _ => String::new(),
                })
                .collect()
        };

        let master = execute_sqlite_schema_query(&catalog).unwrap();
        let master_names = names(&master);
        assert!(master_names.contains(&"main_v".to_string()), "master should list main view");
        assert!(master_names.contains(&"main_tr".to_string()), "master should list main trigger");
        assert!(!master_names.contains(&"temp_v".to_string()), "master must exclude temp view");
        assert!(
            !master_names.contains(&"temp_tr".to_string()),
            "master must exclude temp trigger"
        );

        let temp_master = execute_sqlite_temp_schema_query(&catalog).unwrap();
        let temp_names = names(&temp_master);
        assert!(temp_names.contains(&"temp_v".to_string()), "temp_master should list temp view");
        assert!(
            temp_names.contains(&"temp_tr".to_string()),
            "temp_master should list temp trigger"
        );
        assert!(!temp_names.contains(&"main_v".to_string()), "temp_master must exclude main view");
        assert!(
            !temp_names.contains(&"main_tr".to_string()),
            "temp_master must exclude main trigger"
        );
    }

    #[test]
    fn test_sqlite_schema_empty_db() {
        let catalog = Catalog::new();
        let result = execute_sqlite_schema_query(&catalog).unwrap();

        assert_eq!(result.columns, vec!["type", "name", "tbl_name", "rootpage", "sql"]);
        assert!(result.rows.is_empty());
    }

    #[test]
    fn test_get_sqlite_schema_table_schema() {
        let schema = get_sqlite_schema_table_schema();

        assert_eq!(schema.name, "sqlite_master");
        assert_eq!(schema.columns.len(), 5);
        assert_eq!(schema.columns[0].name, "type");
        assert_eq!(schema.columns[1].name, "name");
        assert_eq!(schema.columns[2].name, "tbl_name");
        assert_eq!(schema.columns[3].name, "rootpage");
        assert_eq!(schema.columns[4].name, "sql");
    }

    #[test]
    fn test_format_data_type() {
        assert_eq!(format_data_type(&DataType::Integer), "INTEGER");
        assert_eq!(format_data_type(&DataType::Varchar { max_length: Some(255) }), "VARCHAR(255)");
        assert_eq!(format_data_type(&DataType::Varchar { max_length: None }), "TEXT");
        assert_eq!(format_data_type(&DataType::Boolean), "BOOLEAN");
        assert_eq!(
            format_data_type(&DataType::Numeric { precision: 10, scale: 2 }),
            "NUMERIC(10, 2)"
        );
    }

    #[test]
    fn test_sqlite_schema_with_table() {
        let mut catalog = Catalog::new();

        // Create a simple table
        let columns = vec![
            ColumnSchema::new("id".to_string(), DataType::Integer, false),
            ColumnSchema::new(
                "name".to_string(),
                DataType::Varchar { max_length: Some(100) },
                true,
            ),
        ];
        let table =
            TableSchema::with_primary_key("users".to_string(), columns, vec!["id".to_string()]);
        catalog.create_table(table).unwrap();

        let result = execute_sqlite_schema_query(&catalog).unwrap();

        // Should have one row for the table
        assert_eq!(result.rows.len(), 1);

        // Check the type column
        let type_val = &result.rows[0].values[0];
        assert_eq!(type_val, &SqlValue::Varchar(arcstr::ArcStr::from("table")));

        // Check the name column
        let name_val = &result.rows[0].values[1];
        assert_eq!(name_val, &SqlValue::Varchar(arcstr::ArcStr::from("users")));

        // Check the tbl_name column (same as name for tables)
        let tbl_name_val = &result.rows[0].values[2];
        assert_eq!(tbl_name_val, &SqlValue::Varchar(arcstr::ArcStr::from("users")));

        // Check the rootpage column (always 0)
        let rootpage_val = &result.rows[0].values[3];
        assert_eq!(rootpage_val, &SqlValue::Integer(0));

        // Check the sql column contains CREATE TABLE
        let sql_val = &result.rows[0].values[4];
        if let SqlValue::Varchar(sql) = sql_val {
            assert!(sql.contains("CREATE TABLE users"));
            assert!(sql.contains("id INTEGER"));
            assert!(sql.contains("name VARCHAR(100)"));
            assert!(sql.contains("PRIMARY KEY"));
        } else {
            panic!("Expected VARCHAR for sql column");
        }
    }

    #[test]
    fn test_sqlite_schema_with_index() {
        let mut catalog = Catalog::new();

        // Create a table first
        let columns = vec![
            ColumnSchema::new("id".to_string(), DataType::Integer, false),
            ColumnSchema::new(
                "email".to_string(),
                DataType::Varchar { max_length: Some(255) },
                false,
            ),
        ];
        let table =
            TableSchema::with_primary_key("users".to_string(), columns, vec!["id".to_string()]);
        catalog.create_table(table).unwrap();

        // Create an index
        let index = IndexMetadata::new(
            "idx_email".to_string(),
            "users".to_string(),
            IndexType::BTree,
            vec![IndexedColumn::new_column("email".to_string(), SortOrder::Ascending)],
            true, // unique
        );
        catalog.add_index(index).unwrap();

        let result = execute_sqlite_schema_query(&catalog).unwrap();

        // Should have two rows: one for table, one for index
        assert_eq!(result.rows.len(), 2);

        // Find the index row
        let index_row = result
            .rows
            .iter()
            .find(|r| matches!(&r.values[0], SqlValue::Varchar(s) if s.as_str() == "index"))
            .expect("Should have an index row");

        // Check index name
        assert_eq!(index_row.values[1], SqlValue::Varchar(arcstr::ArcStr::from("idx_email")));

        // Check tbl_name for index
        assert_eq!(index_row.values[2], SqlValue::Varchar(arcstr::ArcStr::from("users")));

        // Check sql contains CREATE INDEX
        if let SqlValue::Varchar(sql) = &index_row.values[4] {
            assert!(sql.contains("CREATE UNIQUE INDEX idx_email ON users"));
        } else {
            panic!("Expected VARCHAR for sql column");
        }
    }

    #[test]
    fn test_generate_create_index_sql() {
        let index = IndexMetadata::new(
            "idx_name".to_string(),
            "users".to_string(),
            IndexType::BTree,
            vec![
                IndexedColumn::new_column("last_name".to_string(), SortOrder::Ascending),
                IndexedColumn::Column {
                    column_name: "first_name".to_string(),
                    order: SortOrder::Descending,
                    prefix_length: None,
                },
            ],
            false, // not unique
        );

        let sql = generate_create_index_sql(&index);
        assert_eq!(sql, "CREATE INDEX idx_name ON users(last_name, first_name DESC)");
    }

    #[test]
    fn test_generate_create_index_sql_with_prefix() {
        let index = IndexMetadata::new(
            "idx_email".to_string(),
            "users".to_string(),
            IndexType::BTree,
            vec![IndexedColumn::new_column_with_prefix(
                "email".to_string(),
                SortOrder::Ascending,
                50,
            )],
            true, // unique
        );

        let sql = generate_create_index_sql(&index);
        assert_eq!(sql, "CREATE UNIQUE INDEX idx_email ON users(email(50))");
    }

    /// Regression test for #5579: `sqlite_master` must report the index name and
    /// SQL with their original case (the case the user typed in `CREATE INDEX`),
    /// matching sqlite3 3.51.0. The catalog stores the original-case name, so
    /// both the `name` column and the generated `sql` column preserve it.
    #[test]
    fn test_sqlite_schema_index_preserves_name_case() {
        let mut catalog = Catalog::new();
        catalog.set_case_sensitive_identifiers(false);

        let columns = vec![ColumnSchema::new("a".to_string(), DataType::Integer, false)];
        let table = TableSchema::new("t".to_string(), columns);
        catalog.create_table(table).unwrap();

        let index = IndexMetadata::new(
            "MyIdx".to_string(),
            "t".to_string(),
            IndexType::BTree,
            vec![IndexedColumn::new_column("a".to_string(), SortOrder::Ascending)],
            false,
        );
        catalog.add_index(index).unwrap();

        let result = execute_sqlite_schema_query(&catalog).unwrap();
        let index_row = result
            .rows
            .iter()
            .find(|r| matches!(&r.values[0], SqlValue::Varchar(s) if s.as_str() == "index"))
            .expect("Should have an index row");

        // `name` column preserves original case (not "myidx").
        assert_eq!(index_row.values[1], SqlValue::Varchar(arcstr::ArcStr::from("MyIdx")));

        // `sql` column preserves original case.
        if let SqlValue::Varchar(sql) = &index_row.values[4] {
            assert!(
                sql.contains("CREATE INDEX MyIdx ON t"),
                "sqlite_master.sql must preserve original index-name case, got: {sql}"
            );
            assert!(!sql.contains("myidx"), "index name must not be lowercased, got: {sql}");
        } else {
            panic!("Expected VARCHAR for sql column");
        }
    }

    #[test]
    fn test_generate_create_trigger_sql_basic() {
        use vibesql_ast::{TriggerAction, TriggerEvent, TriggerGranularity, TriggerTiming};
        use vibesql_catalog::TriggerDefinition;

        let trigger = TriggerDefinition {
            name: "audit_insert".to_string(),
            schema: None,
            table_name: "users".to_string(),
            timing: TriggerTiming::After,
            event: TriggerEvent::Insert,
            granularity: TriggerGranularity::Row,
            when_condition: None,
            triggered_action: TriggerAction::RawSql(
                " BEGIN INSERT INTO audit VALUES (NEW.id); END".to_string(),
            ),
            enabled: true,
            sql_definition: None,
        };

        let sql = generate_create_trigger_sql(&trigger);
        assert_eq!(
            sql,
            "CREATE TRIGGER audit_insert AFTER INSERT ON users FOR EACH ROW BEGIN INSERT INTO audit VALUES (NEW.id); END"
        );
    }

    #[test]
    fn test_generate_create_trigger_sql_with_update_of() {
        use vibesql_ast::{TriggerAction, TriggerEvent, TriggerGranularity, TriggerTiming};
        use vibesql_catalog::TriggerDefinition;

        let trigger = TriggerDefinition {
            name: "track_status_change".to_string(),
            schema: None,
            table_name: "orders".to_string(),
            timing: TriggerTiming::Before,
            event: TriggerEvent::Update(Some(vec!["status".to_string(), "updated_at".to_string()])),
            granularity: TriggerGranularity::Row,
            when_condition: None,
            triggered_action: TriggerAction::RawSql(" BEGIN SELECT 1; END".to_string()),
            enabled: true,
            sql_definition: None,
        };

        let sql = generate_create_trigger_sql(&trigger);
        assert!(sql.contains("UPDATE OF status, updated_at"));
        assert!(sql.contains("CREATE TRIGGER track_status_change BEFORE UPDATE OF"));
    }

    #[test]
    fn test_generate_create_trigger_sql_instead_of() {
        use vibesql_ast::{TriggerAction, TriggerEvent, TriggerGranularity, TriggerTiming};
        use vibesql_catalog::TriggerDefinition;

        let trigger = TriggerDefinition {
            name: "instead_delete".to_string(),
            schema: None,
            table_name: "my_view".to_string(),
            timing: TriggerTiming::InsteadOf,
            event: TriggerEvent::Delete,
            granularity: TriggerGranularity::Row,
            when_condition: None,
            triggered_action: TriggerAction::RawSql(
                " BEGIN DELETE FROM base_table WHERE id = OLD.id; END".to_string(),
            ),
            enabled: true,
            sql_definition: None,
        };

        let sql = generate_create_trigger_sql(&trigger);
        assert!(sql.contains("INSTEAD OF DELETE"));
        assert!(sql.contains("FOR EACH ROW"));
    }

    /// Create a minimal SelectStmt for testing purposes
    fn create_minimal_select_stmt() -> vibesql_ast::SelectStmt {
        vibesql_ast::SelectStmt {
            with_clause: None,
            distinct: false,
            select_list: vec![vibesql_ast::SelectItem::Wildcard { alias: None }],
            into_table: None,
            into_variables: None,
            from: None,
            where_clause: None,
            group_by: None,
            having: None,
            window_definitions: None,
            order_by: None,
            limit: None,
            offset: None,
            set_operation: None,
            values: None,
        }
    }

    #[test]
    fn test_generate_create_view_sql_with_definition() {
        use vibesql_catalog::ViewDefinition;

        // Create a view with sql_definition set
        let view = ViewDefinition::new_with_sql(
            "active_users".to_string(),
            Some(vec!["id".to_string(), "name".to_string()]),
            create_minimal_select_stmt(),
            false,
            "CREATE VIEW active_users (id, name) AS SELECT id, name FROM users WHERE active = 1"
                .to_string(),
        );

        let sql = generate_create_view_sql(&view);
        assert_eq!(
            sql,
            "CREATE VIEW active_users (id, name) AS SELECT id, name FROM users WHERE active = 1"
        );
    }

    #[test]
    fn test_generate_create_view_sql_fallback() {
        use vibesql_catalog::ViewDefinition;

        // Create a view without sql_definition (fallback path)
        let view = ViewDefinition::new(
            "test_view".to_string(),
            Some(vec!["col1".to_string()]),
            create_minimal_select_stmt(),
            false,
        );

        let sql = generate_create_view_sql(&view);
        // Should contain CREATE VIEW and the view name
        assert!(sql.contains("CREATE VIEW test_view"));
        // With column list specified
        assert!(sql.contains("(col1)"));
    }
}