qail-core 1.3.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
//! Type-safe schema code generation.
//!
//! Generates Rust code from schema.qail for compile-time type safety.
//!
//! # Usage from build.rs
//! ```ignore
//! qail_core::codegen::generate_to_file("schema.qail", "src/generated/schema.rs")?;
//! ```
//!
//! # Generated code example
//! ```ignore
//! pub mod users {
//!     use qail_core::typed::{Table, TypedColumn};
//!     
//!     pub struct Users;
//!     impl Table for Users { fn table_name() -> &'static str { "users" } }
//!     
//!     pub fn id() -> TypedColumn<uuid::Uuid> { TypedColumn::new("users", "id") }
//!     pub fn age() -> TypedColumn<i64> { TypedColumn::new("users", "age") }
//! }
//! ```

use crate::build::Schema;
use crate::migrate::types::ColumnType;
use std::fs;

/// Generate typed Rust code from a schema.qail file and write to output
pub fn generate_to_file(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 output: {}", e))?;
    Ok(())
}

/// Generate typed Rust code from a schema.qail file
pub fn generate_from_file(schema_path: &str) -> Result<String, String> {
    let schema = Schema::parse_file(schema_path)?;
    Ok(generate_schema_code(&schema))
}

/// Generate Rust code for the schema
pub fn generate_schema_code(schema: &Schema) -> String {
    let mut code = String::new();

    // Header
    code.push_str("//! Auto-generated by `qail types`\n");
    code.push_str("//! Do not edit manually.\n\n");
    code.push_str("#![allow(dead_code)]\n\n");
    code.push_str("use qail_core::typed::{Table, TypedColumn, RequiresRls, DirectBuild, Bucket, Queue, Topic};\n\n");

    // Generate table modules
    let mut table_names: Vec<_> = schema.tables.keys().collect();
    table_names.sort();

    for table_name in &table_names {
        if let Some(table) = schema.tables.get(*table_name) {
            code.push_str(&generate_table_module(table_name, table));
            code.push('\n');
        }
    }

    // Generate tables re-export
    code.push_str("/// Re-export all table types\n");
    code.push_str("pub mod tables {\n");

    for table_name in &table_names {
        let module_name = to_rust_ident(table_name);
        let struct_name = to_pascal_case(table_name);
        code.push_str(&format!(
            "    pub use super::{}::{};\n",
            module_name, struct_name
        ));
    }
    code.push_str("}\n\n");

    // Generate resource modules
    let mut resource_names: Vec<_> = schema.resources.keys().collect();
    resource_names.sort();

    for res_name in &resource_names {
        if let Some(resource) = schema.resources.get(*res_name) {
            code.push_str(&generate_resource_module(res_name, resource));
            code.push('\n');
        }
    }

    // Generate resources re-export
    if !resource_names.is_empty() {
        code.push_str("/// Re-export all resource types\n");
        code.push_str("pub mod resources {\n");
        for res_name in &resource_names {
            let module_name = to_rust_ident(res_name);
            let struct_name = to_pascal_case(res_name);
            code.push_str(&format!(
                "    pub use super::{}::{};\n",
                module_name, struct_name
            ));
        }
        code.push_str("}\n");
    }

    code
}

/// Generate a module for an infrastructure resource
fn generate_resource_module(
    resource_name: &str,
    resource: &crate::build::ResourceSchema,
) -> String {
    let mut code = String::new();
    let module_name = to_rust_ident(resource_name);
    let struct_name = to_pascal_case(resource_name);
    let kind = &resource.kind;

    code.push_str(&format!("/// {} resource: {}\n", kind, resource_name));
    code.push_str(&format!("pub mod {} {{\n", module_name));
    code.push_str("    use super::*;\n\n");

    // Struct
    code.push_str(&format!(
        "    /// Type-safe reference to {} `{}`\n",
        kind, resource_name
    ));
    code.push_str("    #[derive(Debug, Clone, Copy, Default)]\n");
    code.push_str(&format!("    pub struct {};\n\n", struct_name));

    // Implement the appropriate trait
    let (trait_name, method_name) = match kind.as_str() {
        "bucket" => ("Bucket", "bucket_name"),
        "queue" => ("Queue", "queue_name"),
        "topic" => ("Topic", "topic_name"),
        _ => ("Bucket", "bucket_name"), // fallback
    };

    code.push_str(&format!("    impl {} for {} {{\n", trait_name, struct_name));
    code.push_str(&format!(
        "        fn {}() -> &'static str {{ {} }}\n",
        method_name,
        rust_string_literal(resource_name)
    ));
    code.push_str("    }\n");

    // Add provider constant if specified
    if let Some(ref provider) = resource.provider {
        code.push_str(&format!(
            "\n    pub const PROVIDER: &str = {};\n",
            rust_string_literal(provider)
        ));
    }

    // Add property constants
    for (key, value) in &resource.properties {
        let const_name = to_const_ident(key);
        code.push_str(&format!(
            "    pub const {}: &str = {};\n",
            const_name,
            rust_string_literal(value)
        ));
    }

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

fn generate_table_module(table_name: &str, table: &crate::build::TableSchema) -> String {
    let mut code = String::new();
    let module_name = to_rust_ident(table_name);
    let struct_name = to_pascal_case(table_name);

    code.push_str(&format!("/// Table: {}\n", table_name));
    code.push_str(&format!("pub mod {} {{\n", module_name));
    code.push_str("    use super::*;\n\n");

    // Table struct with Table trait
    code.push_str(&format!(
        "    /// Type-safe reference to `{}`\n",
        table_name
    ));
    code.push_str("    #[derive(Debug, Clone, Copy, Default)]\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");

    // Implement From<Table> for String to work with Qail::get()
    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");

    // AsRef<str> for TypedQail compatibility
    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");

    // RLS trait: RequiresRls for tables with tenant_id, DirectBuild for others
    if table.rls_enabled {
        code.push_str("    /// This table has `tenant_id` — queries require `.with_rls()` proof\n");
        code.push_str(&format!(
            "    impl RequiresRls for {} {{}}\n\n",
            struct_name
        ));
    } else {
        code.push_str(&format!(
            "    impl DirectBuild for {} {{}}\n\n",
            struct_name
        ));
    }

    // Typed column functions
    let mut col_names: Vec<_> = table.columns.keys().collect();
    col_names.sort();

    for col_name in &col_names {
        if let Some(col_type) = table.columns.get(*col_name) {
            let rust_type = column_type_to_rust(col_type);
            let fn_name = to_rust_ident(col_name);
            code.push_str(&format!(
                "    /// Column `{}` ({})\n",
                col_name,
                col_type.to_pg_type()
            ));
            code.push_str(&format!(
                "    pub fn {}() -> TypedColumn<{}> {{ TypedColumn::new({}, {}) }}\n\n",
                fn_name,
                rust_type,
                rust_string_literal(table_name),
                rust_string_literal(col_name)
            ));
        }
    }

    code.push_str("}\n");

    code
}

/// Map ColumnType AST enum to Rust types (for codegen).
/// This is the ONLY place where we map SQL types to Rust types.
fn column_type_to_rust(col_type: &ColumnType) -> &'static str {
    match col_type {
        ColumnType::Uuid => "uuid::Uuid",
        ColumnType::Text | ColumnType::Varchar(_) => "String",
        ColumnType::Int | ColumnType::BigInt | ColumnType::Serial | ColumnType::BigSerial => "i64",
        ColumnType::Bool => "bool",
        ColumnType::Float | ColumnType::Decimal(_) => "f64",
        ColumnType::Jsonb => "serde_json::Value",
        ColumnType::Timestamp | ColumnType::Timestamptz | ColumnType::Date | ColumnType::Time => {
            "chrono::DateTime<chrono::Utc>"
        }
        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 snake_case to PascalCase
fn to_pascal_case(s: &str) -> String {
    let pascal: String = s
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|word| !word.is_empty())
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(c) => c.to_uppercase().chain(chars).collect(),
            }
        })
        .collect();

    let mut pascal = if pascal.is_empty() {
        "QailGenerated".to_string()
    } else {
        pascal
    };
    if pascal
        .chars()
        .next()
        .is_none_or(|c| !c.is_ascii_alphabetic() && c != '_')
    {
        pascal.insert_str(0, "Qail");
    }
    if is_rust_keyword(&pascal) {
        pascal.insert_str(0, "Qail");
    }
    pascal
}

/// Escape Rust reserved keywords with r# prefix
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 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 to_rust_ident(name: &str) -> String {
    escape_keyword(&sanitize_rust_ident(name))
}

fn to_const_ident(name: &str) -> String {
    to_rust_ident(&name.to_ascii_uppercase())
}

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

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

    #[test]
    fn test_pascal_case() {
        assert_eq!(to_pascal_case("users"), "Users");
        assert_eq!(to_pascal_case("user_profiles"), "UserProfiles");
        assert_eq!(to_pascal_case("123_events"), "Qail123Events");
        assert_eq!(to_pascal_case("self"), "QailSelf");
    }

    #[test]
    fn test_rust_identifier_sanitizing() {
        assert_eq!(to_rust_ident("type"), "r#type");
        assert_eq!(to_rust_ident("123abc"), "_123abc");
        assert_eq!(to_rust_ident("user-files"), "user_files");
    }

    #[test]
    fn test_column_type_mapping() {
        assert_eq!(column_type_to_rust(&ColumnType::Int), "i64");
        assert_eq!(column_type_to_rust(&ColumnType::Text), "String");
        assert_eq!(column_type_to_rust(&ColumnType::Uuid), "uuid::Uuid");
        assert_eq!(column_type_to_rust(&ColumnType::Bool), "bool");
        assert_eq!(column_type_to_rust(&ColumnType::Jsonb), "serde_json::Value");
        assert_eq!(column_type_to_rust(&ColumnType::BigInt), "i64");
        assert_eq!(column_type_to_rust(&ColumnType::Float), "f64");
        assert_eq!(
            column_type_to_rust(&ColumnType::Timestamp),
            "chrono::DateTime<chrono::Utc>"
        );
        assert_eq!(column_type_to_rust(&ColumnType::Bytea), "Vec<u8>");
    }

    #[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 fn _1st()"));
        assert!(code.contains("pub fn r#match()"));
        assert!(code.contains("TypedColumn::new(\"type\", \"1st\")"));
    }
}