vibesql-cli 0.1.3

Command-line interface for vibesql SQL database
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
//! TypeScript code generation from database schema
//!
//! This module generates TypeScript type definitions from VibeSQL database schemas,
//! enabling type-safe database interactions in TypeScript projects.

use std::fs;
use std::path::Path;

use anyhow::Result;
use vibesql_catalog::TableSchema;
use vibesql_parser::Parser;
use vibesql_storage::Database;
use vibesql_types::DataType;

/// Configuration for TypeScript code generation
#[derive(Debug, Clone)]
pub struct CodegenConfig {
    /// Output file path (stored for informational purposes)
    #[allow(dead_code)]
    pub output: String,
    /// Whether to generate table metadata objects
    pub include_metadata: bool,
    /// Whether to use camelCase for property names
    pub camel_case: bool,
}

impl Default for CodegenConfig {
    fn default() -> Self {
        CodegenConfig { output: "types.ts".to_string(), include_metadata: true, camel_case: false }
    }
}

/// Generate TypeScript types from a database
pub fn generate_from_database(db: &Database, config: &CodegenConfig) -> Result<String> {
    let tables = db.list_tables();
    let mut schemas: Vec<&TableSchema> = Vec::new();

    for table_name in &tables {
        if let Some(table) = db.get_table(table_name) {
            schemas.push(&table.schema);
        }
    }

    generate_typescript(&schemas, config)
}

/// Generate TypeScript types from a SQL schema file
pub fn generate_from_schema_file(path: &str, config: &CodegenConfig) -> Result<String> {
    let sql = fs::read_to_string(path)?;
    generate_from_sql(&sql, config)
}

/// Generate TypeScript types from SQL DDL statements
pub fn generate_from_sql(sql: &str, config: &CodegenConfig) -> Result<String> {
    let mut db = Database::new();

    // Pre-process SQL to strip comments before splitting
    let sql = strip_sql_comments(sql);

    // Split and execute each statement
    for stmt_sql in split_statements(&sql) {
        let trimmed = stmt_sql.trim();
        if trimmed.is_empty() {
            continue;
        }

        // Only process CREATE TABLE statements
        if trimmed.to_uppercase().starts_with("CREATE TABLE") {
            match Parser::parse_sql(trimmed) {
                Ok(vibesql_ast::Statement::CreateTable(create_stmt)) => {
                    if let Err(e) =
                        vibesql_executor::CreateTableExecutor::execute(&create_stmt, &mut db)
                    {
                        eprintln!("Warning: Failed to execute CREATE TABLE: {}", e);
                    }
                }
                Ok(_) => {
                    // Not a CREATE TABLE, skip
                }
                Err(e) => {
                    eprintln!("Warning: Failed to parse statement: {}", e);
                }
            }
        }
    }

    generate_from_database(&db, config)
}

/// Strip SQL comments from a string
///
/// Handles:
/// - Single-line comments starting with --
/// - Multi-line comments /* ... */
fn strip_sql_comments(sql: &str) -> String {
    let mut result = String::with_capacity(sql.len());
    let mut chars = sql.chars().peekable();
    let mut in_string = false;
    let mut string_char = '"';

    while let Some(ch) = chars.next() {
        // Track if we're inside a string literal
        if (ch == '\'' || ch == '"') && !in_string {
            in_string = true;
            string_char = ch;
            result.push(ch);
            continue;
        }

        if in_string {
            result.push(ch);
            if ch == string_char {
                in_string = false;
            }
            continue;
        }

        // Handle single-line comments (--)
        if ch == '-' && chars.peek() == Some(&'-') {
            chars.next(); // consume second -
                          // Skip until end of line
            for c in chars.by_ref() {
                if c == '\n' {
                    result.push('\n'); // Preserve line breaks
                    break;
                }
            }
            continue;
        }

        // Handle multi-line comments (/* ... */)
        if ch == '/' && chars.peek() == Some(&'*') {
            chars.next(); // consume *
                          // Skip until */
            while let Some(c) = chars.next() {
                if c == '*' && chars.peek() == Some(&'/') {
                    chars.next(); // consume /
                    break;
                }
            }
            continue;
        }

        result.push(ch);
    }

    result
}

/// Split SQL into individual statements
fn split_statements(sql: &str) -> Vec<&str> {
    sql.split(';').filter(|s| !s.trim().is_empty()).collect()
}

/// Generate TypeScript code from table schemas
fn generate_typescript(schemas: &[&TableSchema], config: &CodegenConfig) -> Result<String> {
    let mut output = String::new();

    // Header
    output.push_str("// Auto-generated by vibesql codegen - DO NOT EDIT\n");
    output.push_str("// Generated from VibeSQL database schema\n\n");

    // Sort tables alphabetically for consistent output
    let mut sorted_schemas: Vec<&&TableSchema> = schemas.iter().collect();
    sorted_schemas.sort_by(|a, b| a.name.cmp(&b.name));

    // Generate interfaces for each table
    for schema in &sorted_schemas {
        output.push_str(&generate_interface(schema, config));
        output.push('\n');
    }

    // Generate table metadata if requested
    if config.include_metadata {
        output.push_str(&generate_metadata(&sorted_schemas, config));
    }

    Ok(output)
}

/// Generate a TypeScript interface for a table
fn generate_interface(schema: &TableSchema, config: &CodegenConfig) -> String {
    let mut output = String::new();

    // Interface name is PascalCase version of table name
    let interface_name = to_pascal_case(&schema.name);

    output.push_str(&format!("export interface {} {{\n", interface_name));

    for column in &schema.columns {
        let prop_name = if config.camel_case {
            to_camel_case(&column.name)
        } else {
            column.name.to_lowercase()
        };

        let ts_type = sql_type_to_typescript(&column.data_type);
        let nullable_suffix = if column.nullable { " | null" } else { "" };

        output.push_str(&format!("  {}: {}{};\n", prop_name, ts_type, nullable_suffix));
    }

    output.push_str("}\n");
    output
}

/// Generate table metadata object
fn generate_metadata(schemas: &[&&TableSchema], config: &CodegenConfig) -> String {
    let mut output = String::new();

    output.push_str("// Table metadata for runtime use\n");
    output.push_str("export const tables = {\n");

    for schema in schemas.iter() {
        let table_key = if config.camel_case {
            to_camel_case(&schema.name)
        } else {
            schema.name.to_lowercase()
        };

        output.push_str(&format!("  {}: {{\n", table_key));
        output.push_str(&format!("    name: '{}',\n", schema.name));

        // Columns array
        let columns: Vec<String> = schema
            .columns
            .iter()
            .map(|c| {
                if config.camel_case {
                    format!("'{}'", to_camel_case(&c.name))
                } else {
                    format!("'{}'", c.name.to_lowercase())
                }
            })
            .collect();
        output.push_str(&format!("    columns: [{}],\n", columns.join(", ")));

        // Primary key
        if let Some(pk) = &schema.primary_key {
            if pk.len() == 1 {
                let pk_name =
                    if config.camel_case { to_camel_case(&pk[0]) } else { pk[0].to_lowercase() };
                output.push_str(&format!("    primaryKey: '{}',\n", pk_name));
            } else {
                let pk_names: Vec<String> = pk
                    .iter()
                    .map(|p| {
                        if config.camel_case {
                            format!("'{}'", to_camel_case(p))
                        } else {
                            format!("'{}'", p.to_lowercase())
                        }
                    })
                    .collect();
                output.push_str(&format!("    primaryKey: [{}],\n", pk_names.join(", ")));
            }
        }

        // Column types mapping
        output.push_str("    columnTypes: {\n");
        for column in &schema.columns {
            let col_name = if config.camel_case {
                to_camel_case(&column.name)
            } else {
                column.name.to_lowercase()
            };
            let sql_type = format_sql_type(&column.data_type);
            output.push_str(&format!("      {}: '{}',\n", col_name, sql_type));
        }
        output.push_str("    },\n");

        // Nullable columns
        let nullable_cols: Vec<String> = schema
            .columns
            .iter()
            .filter(|c| c.nullable)
            .map(|c| {
                if config.camel_case {
                    format!("'{}'", to_camel_case(&c.name))
                } else {
                    format!("'{}'", c.name.to_lowercase())
                }
            })
            .collect();
        output.push_str(&format!("    nullable: [{}],\n", nullable_cols.join(", ")));

        output.push_str("  },\n");
    }

    output.push_str("} as const;\n\n");

    // Generate type helpers
    output.push_str("// Type helper for table names\n");
    output.push_str("export type TableName = keyof typeof tables;\n\n");

    // Generate row types
    output.push_str("// Row type mapping\n");
    output.push_str("export type TableRow<T extends TableName> = \n");
    for (i, schema) in schemas.iter().enumerate() {
        let table_key = if config.camel_case {
            to_camel_case(&schema.name)
        } else {
            schema.name.to_lowercase()
        };
        let interface_name = to_pascal_case(&schema.name);
        if i == 0 {
            output.push_str(&format!("  T extends '{}' ? {} :\n", table_key, interface_name));
        } else if i == schemas.len() - 1 {
            output.push_str(&format!("  T extends '{}' ? {} :\n", table_key, interface_name));
            output.push_str("  never;\n");
        } else {
            output.push_str(&format!("  T extends '{}' ? {} :\n", table_key, interface_name));
        }
    }

    output
}

/// Convert SQL data type to TypeScript type
fn sql_type_to_typescript(data_type: &DataType) -> &'static str {
    match data_type {
        // Numeric types -> number
        DataType::Integer
        | DataType::Smallint
        | DataType::Bigint
        | DataType::Unsigned
        | DataType::Real
        | DataType::Float { .. }
        | DataType::DoublePrecision => "number",

        // Decimal/Numeric -> string (for precision)
        DataType::Decimal { .. } | DataType::Numeric { .. } => "string",

        // String types -> string
        DataType::Character { .. }
        | DataType::Varchar { .. }
        | DataType::CharacterLargeObject
        | DataType::Name => "string",

        // Boolean -> boolean
        DataType::Boolean => "boolean",

        // Date/time types -> Date
        DataType::Date | DataType::Time { .. } | DataType::Timestamp { .. } => "Date",

        // Interval -> string representation
        DataType::Interval { .. } => "string",

        // Binary types -> Uint8Array
        DataType::BinaryLargeObject | DataType::Bit { .. } => "Uint8Array",

        // Vector -> number[]
        DataType::Vector { .. } => "number[]",

        // User-defined types -> unknown
        DataType::UserDefined { .. } => "unknown",

        // NULL type -> null
        DataType::Null => "null",
    }
}

/// Format SQL type as string for metadata
fn format_sql_type(data_type: &DataType) -> String {
    match data_type {
        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::Decimal { precision, scale } => format!("DECIMAL({}, {})", precision, scale),
        DataType::Numeric { precision, scale } => format!("NUMERIC({}, {})", precision, scale),
        DataType::Character { length } => format!("CHAR({})", length),
        DataType::Varchar { max_length } => {
            if let Some(len) = max_length {
                format!("VARCHAR({})", len)
            } else {
                "VARCHAR".to_string()
            }
        }
        DataType::CharacterLargeObject => "CLOB".to_string(),
        DataType::Name => "NAME".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::Vector { dimensions } => format!("VECTOR({})", dimensions),
        DataType::UserDefined { type_name } => type_name.clone(),
        DataType::Null => "NULL".to_string(),
    }
}

/// Convert snake_case or UPPER_CASE to PascalCase
fn to_pascal_case(s: &str) -> String {
    s.split('_')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                Some(first) => {
                    first.to_uppercase().chain(chars.flat_map(|c| c.to_lowercase())).collect()
                }
                None => String::new(),
            }
        })
        .collect()
}

/// Convert snake_case or UPPER_CASE to camelCase
fn to_camel_case(s: &str) -> String {
    let pascal = to_pascal_case(s);
    let mut chars = pascal.chars();
    match chars.next() {
        Some(first) => first.to_lowercase().chain(chars).collect(),
        None => String::new(),
    }
}

/// Write generated TypeScript to a file
pub fn write_to_file(typescript: &str, path: &str) -> Result<()> {
    let path = Path::new(path);

    // Create parent directories if needed
    if let Some(parent) = path.parent() {
        if !parent.exists() {
            fs::create_dir_all(parent)?;
        }
    }

    fs::write(path, typescript)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use vibesql_catalog::ColumnSchema;

    fn create_test_schema() -> TableSchema {
        let columns = vec![
            ColumnSchema::new("id".to_string(), DataType::Integer, false),
            ColumnSchema::new(
                "email".to_string(),
                DataType::Varchar { max_length: Some(255) },
                false,
            ),
            ColumnSchema::new(
                "name".to_string(),
                DataType::Varchar { max_length: Some(100) },
                true,
            ),
            ColumnSchema::new(
                "created_at".to_string(),
                DataType::Timestamp { with_timezone: false },
                false,
            ),
            ColumnSchema::new(
                "balance".to_string(),
                DataType::Decimal { precision: 10, scale: 2 },
                true,
            ),
            ColumnSchema::new("is_active".to_string(), DataType::Boolean, false),
        ];
        TableSchema::with_primary_key("users".to_string(), columns, vec!["id".to_string()])
    }

    #[test]
    fn test_to_pascal_case() {
        assert_eq!(to_pascal_case("users"), "Users");
        assert_eq!(to_pascal_case("user_posts"), "UserPosts");
        assert_eq!(to_pascal_case("USER_POSTS"), "UserPosts");
        assert_eq!(to_pascal_case("USERS"), "Users");
    }

    #[test]
    fn test_to_camel_case() {
        assert_eq!(to_camel_case("users"), "users");
        assert_eq!(to_camel_case("user_posts"), "userPosts");
        assert_eq!(to_camel_case("USER_POSTS"), "userPosts");
        assert_eq!(to_camel_case("USERS"), "users");
    }

    #[test]
    fn test_sql_type_to_typescript() {
        assert_eq!(sql_type_to_typescript(&DataType::Integer), "number");
        assert_eq!(sql_type_to_typescript(&DataType::Bigint), "number");
        assert_eq!(sql_type_to_typescript(&DataType::Varchar { max_length: Some(255) }), "string");
        assert_eq!(sql_type_to_typescript(&DataType::Boolean), "boolean");
        assert_eq!(sql_type_to_typescript(&DataType::Timestamp { with_timezone: false }), "Date");
        assert_eq!(
            sql_type_to_typescript(&DataType::Decimal { precision: 10, scale: 2 }),
            "string"
        );
        assert_eq!(sql_type_to_typescript(&DataType::Vector { dimensions: 128 }), "number[]");
    }

    #[test]
    fn test_generate_interface() {
        let schema = create_test_schema();
        let config = CodegenConfig::default();
        let result = generate_interface(&schema, &config);

        assert!(result.contains("export interface Users {"));
        assert!(result.contains("id: number;"));
        assert!(result.contains("email: string;"));
        assert!(result.contains("name: string | null;"));
        assert!(result.contains("created_at: Date;"));
        assert!(result.contains("balance: string | null;")); // Decimal -> string
        assert!(result.contains("is_active: boolean;"));
    }

    #[test]
    fn test_generate_interface_camel_case() {
        let schema = create_test_schema();
        let config = CodegenConfig { camel_case: true, ..Default::default() };
        let result = generate_interface(&schema, &config);

        assert!(result.contains("createdAt: Date;"));
        assert!(result.contains("isActive: boolean;"));
    }

    #[test]
    fn test_generate_from_sql() {
        let sql = r#"
            CREATE TABLE users (
                id INTEGER PRIMARY KEY,
                email VARCHAR(255) NOT NULL,
                name VARCHAR(100)
            );

            CREATE TABLE posts (
                id INTEGER PRIMARY KEY,
                user_id INTEGER NOT NULL,
                title VARCHAR(255) NOT NULL,
                content TEXT,
                published BOOLEAN DEFAULT FALSE
            );
        "#;

        let config = CodegenConfig::default();
        let result = generate_from_sql(sql, &config).unwrap();

        assert!(result.contains("export interface Users {"));
        assert!(result.contains("export interface Posts {"));
        assert!(result.contains("export const tables = {"));
    }

    #[test]
    fn test_generate_metadata() {
        let schema = create_test_schema();
        let schemas: Vec<&TableSchema> = vec![&schema];
        let schema_refs: Vec<&&TableSchema> = schemas.iter().collect();
        let config = CodegenConfig::default();
        let result = generate_metadata(&schema_refs, &config);

        assert!(result.contains("export const tables = {"));
        assert!(result.contains("users: {"));
        assert!(result.contains("name: 'users'"));
        assert!(result.contains("primaryKey: 'id'"));
        assert!(result.contains("columns: ["));
        assert!(result.contains("columnTypes: {"));
        assert!(result.contains("nullable: ["));
        assert!(result.contains("export type TableName = keyof typeof tables;"));
        assert!(result.contains("export type TableRow<T extends TableName>"));
    }

    #[test]
    fn test_strip_sql_comments_single_line() {
        let sql = "-- This is a comment\nCREATE TABLE users (id INT);";
        let result = strip_sql_comments(sql);
        assert!(!result.contains("This is a comment"));
        assert!(result.contains("CREATE TABLE users"));
    }

    #[test]
    fn test_strip_sql_comments_multi_line() {
        let sql = "/* Multi\nline\ncomment */\nCREATE TABLE users (id INT);";
        let result = strip_sql_comments(sql);
        assert!(!result.contains("Multi"));
        assert!(!result.contains("line"));
        assert!(!result.contains("comment"));
        assert!(result.contains("CREATE TABLE users"));
    }

    #[test]
    fn test_strip_sql_comments_inline() {
        let sql = "CREATE TABLE users (id INT); -- inline comment\nCREATE TABLE posts (id INT);";
        let result = strip_sql_comments(sql);
        assert!(!result.contains("inline comment"));
        assert!(result.contains("CREATE TABLE users"));
        assert!(result.contains("CREATE TABLE posts"));
    }

    #[test]
    fn test_strip_sql_comments_preserves_strings() {
        let sql = "CREATE TABLE users (name VARCHAR(100) DEFAULT '--not a comment');";
        let result = strip_sql_comments(sql);
        assert!(result.contains("'--not a comment'"));
    }

    #[test]
    fn test_generate_from_sql_with_comments() {
        let sql = r#"
            -- Database schema for application
            /*
             * User management tables
             */
            CREATE TABLE users (
                id INTEGER PRIMARY KEY,
                email VARCHAR(255) NOT NULL -- User's email
            );

            -- Posts table
            CREATE TABLE posts (
                id INTEGER PRIMARY KEY,
                user_id INTEGER NOT NULL
            );
        "#;

        let config = CodegenConfig::default();
        let result = generate_from_sql(sql, &config).unwrap();

        assert!(result.contains("export interface Users {"));
        assert!(result.contains("export interface Posts {"));
        assert!(!result.contains("Database schema for application"));
        assert!(!result.contains("User management tables"));
    }
}