qail-core 1.2.0

AST-native query builder - type-safe expressions, zero SQL strings
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
//! Typed schema code generation.
//!
//! Generates Rust modules from `schema.qail` for compile-time type safety.

use std::collections::{HashMap, HashSet};
use std::fs;

use crate::migrate::types::ColumnType;

use super::schema::Schema;

fn qail_type_to_rust(col_type: &ColumnType) -> &'static str {
    match col_type {
        ColumnType::Uuid => "uuid::Uuid",
        ColumnType::Text | ColumnType::Varchar(_) => "String",
        ColumnType::Int | ColumnType::Serial => "i32",
        ColumnType::BigInt | ColumnType::BigSerial => "i64",
        ColumnType::Bool => "bool",
        ColumnType::Float => "f32",
        ColumnType::Decimal(_) => "rust_decimal::Decimal",
        ColumnType::Jsonb => "serde_json::Value",
        ColumnType::Timestamp | ColumnType::Timestamptz => "chrono::DateTime<chrono::Utc>",
        ColumnType::Date => "chrono::NaiveDate",
        ColumnType::Time => "chrono::NaiveTime",
        ColumnType::Bytea => "Vec<u8>",
        ColumnType::Array(_) => "Vec<serde_json::Value>",
        ColumnType::Enum { .. } => "String",
        ColumnType::Range(_) => "String",
        ColumnType::Interval => "String",
        ColumnType::Cidr | ColumnType::Inet => "String",
        ColumnType::MacAddr => "String",
    }
}

/// Convert table/column names to valid Rust identifiers
fn to_rust_ident(name: &str) -> String {
    escape_keyword(&sanitize_rust_ident(name))
}

/// Convert table name to PascalCase struct name
fn to_struct_name(name: &str) -> String {
    let mut out = String::new();
    for part in name
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|part| !part.is_empty())
    {
        let mut chars = part.chars();
        if let Some(first) = chars.next() {
            out.extend(first.to_uppercase());
            out.push_str(chars.as_str());
        }
    }

    if out.is_empty() {
        out.push_str("QailGenerated");
    }
    if out
        .chars()
        .next()
        .is_none_or(|c| !c.is_ascii_alphabetic() && c != '_')
    {
        out.insert_str(0, "Qail");
    }
    if is_rust_keyword(&out) {
        out.insert_str(0, "Qail");
    }
    out
}

fn sanitize_rust_ident(name: &str) -> String {
    let mut ident: String = name
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();

    if ident.is_empty() {
        ident.push('_');
    }
    if ident
        .chars()
        .next()
        .is_none_or(|c| !c.is_ascii_alphabetic() && c != '_')
    {
        ident.insert(0, '_');
    }

    ident
}

fn escape_keyword(name: &str) -> String {
    if is_rust_keyword(name) {
        format!("r#{}", name)
    } else {
        name.to_string()
    }
}

fn is_rust_keyword(name: &str) -> bool {
    const KEYWORDS: &[&str] = &[
        "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn",
        "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
        "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe",
        "use", "where", "while", "async", "await", "dyn", "abstract", "become", "box", "do",
        "final", "macro", "override", "priv", "try", "typeof", "unsized", "virtual", "yield",
    ];

    KEYWORDS.contains(&name)
}

fn rust_string_literal(value: &str) -> String {
    format!("{value:?}")
}

/// Generate typed Rust module from schema.
///
/// # Usage in consumer's build.rs:
/// ```ignore
/// fn main() {
///     let out_dir = std::env::var("OUT_DIR").unwrap();
///     qail_core::build::generate_typed_schema("schema.qail", &format!("{}/schema.rs", out_dir)).unwrap();
///     println!("cargo:rerun-if-changed=schema.qail");
/// }
/// ```
///
/// Then in the consumer's lib.rs:
/// ```ignore
/// include!(concat!(env!("OUT_DIR"), "/schema.rs"));
/// ```
pub fn generate_typed_schema(schema_path: &str, output_path: &str) -> Result<(), String> {
    let schema = Schema::parse_file(schema_path)?;
    let code = generate_schema_code(&schema);

    fs::write(output_path, code)
        .map_err(|e| format!("Failed to write schema module to '{}': {}", output_path, e))?;

    Ok(())
}

/// Generate typed Rust code from schema (does not write to file)
pub fn generate_schema_code(schema: &Schema) -> String {
    let mut code = String::new();

    // Header
    code.push_str("//! Auto-generated typed schema from schema.qail\n");
    code.push_str("//! Do not edit manually - regenerate with `cargo build`\n\n");
    code.push_str("#![allow(dead_code, non_upper_case_globals)]\n\n");
    code.push_str("use qail_core::typed::{Table, TypedColumn, RelatedTo, Public, Protected};\n\n");

    // Sort tables for deterministic output
    let mut tables: Vec<_> = schema.tables.values().collect();
    tables.sort_by(|a, b| a.name.cmp(&b.name));

    for table in &tables {
        let mod_name = to_rust_ident(&table.name);
        let struct_name = to_struct_name(&table.name);

        code.push_str(&format!("/// Typed schema for `{}` table\n", table.name));
        code.push_str(&format!("pub mod {} {{\n", mod_name));
        code.push_str("    use super::*;\n\n");

        // Table struct implementing Table trait
        code.push_str(&format!("    /// Table marker for `{}`\n", table.name));
        code.push_str("    #[derive(Debug, Clone, Copy)]\n");
        code.push_str(&format!("    pub struct {};\n\n", struct_name));

        code.push_str(&format!("    impl Table for {} {{\n", struct_name));
        code.push_str(&format!(
            "        fn table_name() -> &'static str {{ {} }}\n",
            rust_string_literal(&table.name)
        ));
        code.push_str("    }\n\n");

        code.push_str(&format!("    impl From<{}> for String {{\n", struct_name));
        code.push_str(&format!(
            "        fn from(_: {}) -> String {{ {}.to_string() }}\n",
            struct_name,
            rust_string_literal(&table.name)
        ));
        code.push_str("    }\n\n");

        code.push_str(&format!("    impl AsRef<str> for {} {{\n", struct_name));
        code.push_str(&format!(
            "        fn as_ref(&self) -> &str {{ {} }}\n",
            rust_string_literal(&table.name)
        ));
        code.push_str("    }\n\n");

        // Table constant for convenience
        code.push_str(&format!("    /// The `{}` table\n", table.name));
        code.push_str(&format!(
            "    pub const table: {} = {};\n\n",
            struct_name, struct_name
        ));

        // Sort columns for deterministic output
        let mut columns: Vec<_> = table.columns.iter().collect();
        columns.sort_by(|a, b| a.0.cmp(b.0));

        // Column constants
        for (col_name, col_type) in columns {
            let rust_type = qail_type_to_rust(col_type);
            let col_ident = to_rust_ident(col_name);
            let policy = table
                .policies
                .get(col_name)
                .map(|s| s.as_str())
                .unwrap_or("Public");
            let rust_policy = if policy == "Protected" {
                "Protected"
            } else {
                "Public"
            };

            code.push_str(&format!(
                "    /// Column `{}.{}` ({}) - {}\n",
                table.name,
                col_name,
                col_type.to_pg_type(),
                policy
            ));
            code.push_str(&format!(
                "    pub const {}: TypedColumn<{}, {}> = TypedColumn::new({}, {});\n",
                col_ident,
                rust_type,
                rust_policy,
                rust_string_literal(&table.name),
                rust_string_literal(col_name)
            ));
        }

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

    // ==========================================================================
    // Generate RelatedTo impls for compile-time relationship checking
    // ==========================================================================

    code.push_str(
        "// =============================================================================\n",
    );
    code.push_str("// Compile-Time Relationship Safety (RelatedTo impls)\n");
    code.push_str(
        "// =============================================================================\n\n",
    );

    let table_names: HashSet<&str> = tables.iter().map(|table| table.name.as_str()).collect();
    let mut relation_impl_counts: HashMap<(&str, &str), usize> = HashMap::new();
    for table in &tables {
        for fk in &table.foreign_keys {
            if !table_names.contains(fk.ref_table.as_str()) {
                continue;
            }
            *relation_impl_counts
                .entry((table.name.as_str(), fk.ref_table.as_str()))
                .or_default() += 1;
            *relation_impl_counts
                .entry((fk.ref_table.as_str(), table.name.as_str()))
                .or_default() += 1;
        }
    }

    for table in &tables {
        for fk in &table.foreign_keys {
            if !table_names.contains(fk.ref_table.as_str()) {
                continue;
            }
            // table.column refs ref_table.ref_column
            // This means: table is related TO ref_table (forward)
            // AND: ref_table is related FROM table (reverse - parent has many children)

            let from_mod = to_rust_ident(&table.name);
            let from_struct = to_struct_name(&table.name);
            let to_mod = to_rust_ident(&fk.ref_table);
            let to_struct = to_struct_name(&fk.ref_table);

            // Forward: From table (child) -> Referenced table (parent)
            // Example: posts -> users (posts.user_id -> users.id)
            if relation_impl_counts
                .get(&(table.name.as_str(), fk.ref_table.as_str()))
                .copied()
                .unwrap_or_default()
                == 1
            {
                code.push_str(&format!(
                    "/// {} has a foreign key to {} via {}.{}\n",
                    table.name, fk.ref_table, table.name, fk.column
                ));
                code.push_str(&format!(
                    "impl RelatedTo<{}::{}> for {}::{} {{\n",
                    to_mod, to_struct, from_mod, from_struct
                ));
                code.push_str(&format!(
                    "    fn join_columns() -> (&'static str, &'static str) {{ ({}, {}) }}\n",
                    rust_string_literal(&fk.column),
                    rust_string_literal(&fk.ref_column)
                ));
                code.push_str("}\n\n");
            }

            // Reverse: Referenced table (parent) -> From table (child)
            // Example: users -> posts (users.id -> posts.user_id)
            // This allows: Qail::get(users::table).join_related(posts::table)
            if relation_impl_counts
                .get(&(fk.ref_table.as_str(), table.name.as_str()))
                .copied()
                .unwrap_or_default()
                == 1
            {
                code.push_str(&format!(
                    "/// {} is referenced by {} via {}.{}\n",
                    fk.ref_table, table.name, table.name, fk.column
                ));
                code.push_str(&format!(
                    "impl RelatedTo<{}::{}> for {}::{} {{\n",
                    from_mod, from_struct, to_mod, to_struct
                ));
                code.push_str(&format!(
                    "    fn join_columns() -> (&'static str, &'static str) {{ ({}, {}) }}\n",
                    rust_string_literal(&fk.ref_column),
                    rust_string_literal(&fk.column)
                ));
                code.push_str("}\n\n");
            }
        }
    }

    code
}

#[cfg(test)]
mod codegen_tests {
    use super::*;

    #[test]
    fn test_generate_schema_code() {
        let schema_content = r#"
table users {
    id UUID primary_key
    email TEXT not_null
    age INT
}

table posts {
    id UUID primary_key
    user_id UUID ref:users.id
    title TEXT
}
"#;

        let schema = Schema::parse(schema_content).unwrap();
        let code = generate_schema_code(&schema);

        // Verify module structure
        assert!(code.contains("pub mod users {"));
        assert!(code.contains("pub mod posts {"));

        // Verify table structs
        assert!(code.contains("pub struct Users;"));
        assert!(code.contains("pub struct Posts;"));

        // Verify columns
        assert!(code.contains("pub const id: TypedColumn<uuid::Uuid, Public>"));
        assert!(code.contains("pub const email: TypedColumn<String, Public>"));
        assert!(code.contains("pub const age: TypedColumn<i32, Public>"));

        // Verify RelatedTo impls for compile-time relationship checking
        assert!(code.contains("impl RelatedTo<users::Users> for posts::Posts"));
        assert!(code.contains("impl RelatedTo<posts::Posts> for users::Users"));
    }

    #[test]
    fn test_generate_protected_column() {
        let schema_content = r#"
table secrets {
    id UUID primary_key
    token TEXT protected
}
"#;
        let schema = Schema::parse(schema_content).unwrap();
        let code = generate_schema_code(&schema);

        // Verify Protected policy
        assert!(code.contains("pub const token: TypedColumn<String, Protected>"));
    }

    #[test]
    fn test_generate_schema_code_skips_ambiguous_related_to_impls() {
        let schema_content = r#"
table users {
    id UUID primary_key
}

table invoices {
    id UUID primary_key
    buyer_id UUID ref:users.id
    seller_id UUID ref:users.id
}
"#;

        let schema = Schema::parse(schema_content).unwrap();
        let code = generate_schema_code(&schema);

        assert!(code.contains("pub const buyer_id: TypedColumn<uuid::Uuid, Public>"));
        assert!(code.contains("pub const seller_id: TypedColumn<uuid::Uuid, Public>"));
        assert!(!code.contains("impl RelatedTo<users::Users> for invoices::Invoices"));
        assert!(!code.contains("impl RelatedTo<invoices::Invoices> for users::Users"));
    }

    #[test]
    fn test_generate_schema_code_skips_missing_target_related_to_impls() {
        let schema_content = r#"
table posts {
    id UUID primary_key
    user_id UUID ref:users.id
}
"#;

        let schema = Schema::parse(schema_content).unwrap();
        let code = generate_schema_code(&schema);

        assert!(code.contains("pub mod posts {"));
        assert!(!code.contains("impl RelatedTo<users::Users> for posts::Posts"));
        assert!(!code.contains("impl RelatedTo<posts::Posts> for users::Users"));
    }

    #[test]
    fn test_generate_schema_code_sanitizes_rust_identifiers() {
        let schema_content = r#"
table type {
    1st TEXT
    match TEXT
}
"#;
        let schema = Schema::parse(schema_content).unwrap();
        let code = generate_schema_code(&schema);

        assert!(code.contains("pub mod r#type {"));
        assert!(code.contains("pub struct Type;"));
        assert!(code.contains("pub const _1st: TypedColumn<String, Public>"));
        assert!(code.contains("pub const r#match: TypedColumn<String, Public>"));
        assert!(code.contains("TypedColumn::new(\"type\", \"1st\")"));
    }
}

#[cfg(test)]
mod migration_parser_tests {
    use super::*;

    #[test]
    fn test_agent_contracts_migration_parses_all_columns() {
        let sql = r#"
CREATE TABLE agent_contracts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
    operator_id UUID NOT NULL REFERENCES operators(id) ON DELETE CASCADE,
    pricing_model VARCHAR(20) NOT NULL CHECK (pricing_model IN ('commission', 'static_markup', 'net_rate')),
    commission_percent DECIMAL(5,2),
    static_markup DECIMAL(10,2),
    is_active BOOLEAN DEFAULT true,
    valid_from DATE,
    valid_until DATE,
    approved_by UUID REFERENCES users(id),
    created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,
    updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,
    UNIQUE(agent_id, operator_id)
);
"#;

        let mut schema = Schema::default();
        schema.parse_sql_migration(sql);

        let table = schema
            .tables
            .get("agent_contracts")
            .expect("agent_contracts table should exist");

        for col in &[
            "id",
            "agent_id",
            "operator_id",
            "pricing_model",
            "commission_percent",
            "static_markup",
            "is_active",
            "valid_from",
            "valid_until",
            "approved_by",
            "created_at",
            "updated_at",
        ] {
            assert!(
                table.columns.contains_key(*col),
                "Missing column: '{}'. Found: {:?}",
                col,
                table.columns.keys().collect::<Vec<_>>()
            );
        }
    }

    /// Regression test: column names that START with SQL keywords must parse correctly.
    /// e.g., created_at starts with CREATE, primary_contact starts with PRIMARY, etc.
    #[test]
    fn test_keyword_prefixed_column_names_are_not_skipped() {
        let sql = r#"
CREATE TABLE edge_cases (
    id UUID PRIMARY KEY,
    created_at TIMESTAMPTZ NOT NULL,
    created_by UUID,
    primary_contact VARCHAR(255),
    check_status VARCHAR(20),
    unique_code VARCHAR(50),
    foreign_ref UUID,
    constraint_name VARCHAR(100),
    PRIMARY KEY (id),
    CHECK (check_status IN ('pending', 'active')),
    UNIQUE (unique_code),
    CONSTRAINT fk_ref FOREIGN KEY (foreign_ref) REFERENCES other(id)
);
"#;

        let mut schema = Schema::default();
        schema.parse_sql_migration(sql);

        let table = schema
            .tables
            .get("edge_cases")
            .expect("edge_cases table should exist");

        // These column names start with SQL keywords — all must be found
        for col in &[
            "created_at",
            "created_by",
            "primary_contact",
            "check_status",
            "unique_code",
            "foreign_ref",
            "constraint_name",
        ] {
            assert!(
                table.columns.contains_key(*col),
                "Column '{}' should NOT be skipped just because it starts with a SQL keyword. Found: {:?}",
                col,
                table.columns.keys().collect::<Vec<_>>()
            );
        }

        // These are constraint keywords, not columns — must NOT appear
        // (PRIMARY KEY, CHECK, UNIQUE, CONSTRAINT lines should be skipped)
        assert!(
            !table.columns.contains_key("primary"),
            "Constraint keyword 'PRIMARY' should not be treated as a column"
        );
    }
}