qail-core 0.27.9

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
//! SQL Transpiler for QAIL AST.
//!

/// Condition-to-SQL conversion.
pub mod conditions;
/// DDL statement transpilation (CREATE TABLE, ALTER TABLE, etc.).
pub mod ddl;
/// SQL dialect selection (PostgreSQL, MySQL, SQLite).
pub mod dialect;
/// DML statement transpilation (INSERT, UPDATE, DELETE).
pub mod dml;
/// RLS policy transpilation (CREATE POLICY).
pub mod policy;
/// Core SQL generation utilities.
pub mod sql;
/// Transpiler traits (SqlGenerator, escape_identifier).
pub mod traits;

/// NoSQL transpilers (DynamoDB, MongoDB, Qdrant).
pub mod nosql;
pub use nosql::dynamo::ToDynamo;
pub use nosql::mongo::ToMongo;
pub use nosql::qdrant::ToQdrant;

#[cfg(test)]
mod tests;

use crate::ast::*;
pub use conditions::ConditionToSql;
pub use dialect::Dialect;
pub use traits::SqlGenerator;
pub use traits::escape_identifier;

/// Result of transpilation with extracted parameters.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TranspileResult {
    /// The SQL template with placeholders (e.g., $1, $2 or ?, ?)
    pub sql: String,
    /// The extracted parameter values in order
    pub params: Vec<Value>,
    /// Names of named parameters in order they appear (for :name → $n mapping)
    pub named_params: Vec<String>,
}

impl TranspileResult {
    /// Create a new TranspileResult.
    pub fn new(sql: impl Into<String>, params: Vec<Value>) -> Self {
        Self {
            sql: sql.into(),
            params,
            named_params: vec![],
        }
    }

    /// Create a result with no parameters.
    pub fn sql_only(sql: impl Into<String>) -> Self {
        Self {
            sql: sql.into(),
            params: Vec::new(),
            named_params: Vec::new(),
        }
    }
}

/// Trait for converting AST nodes to parameterized SQL.
pub trait ToSqlParameterized {
    /// Convert to SQL with extracted parameters (default dialect).
    fn to_sql_parameterized(&self) -> TranspileResult {
        self.to_sql_parameterized_with_dialect(Dialect::default())
    }
    /// Convert to SQL with extracted parameters for specific dialect.
    fn to_sql_parameterized_with_dialect(&self, dialect: Dialect) -> TranspileResult;
}

/// Trait for converting AST nodes to SQL.
pub trait ToSql {
    /// Convert this node to a SQL string using default dialect.
    fn to_sql(&self) -> String {
        self.to_sql_with_dialect(Dialect::default())
    }
    /// Convert this node to a SQL string with specific dialect.
    fn to_sql_with_dialect(&self, dialect: Dialect) -> String;
}

impl ToSql for Qail {
    fn to_sql_with_dialect(&self, dialect: Dialect) -> String {
        match self.action {
            Action::Get => dml::select::build_select(self, dialect),
            Action::Cnt => {
                // Build a count query: SELECT COUNT(*) FROM table WHERE ...
                let mut count_ast = self.clone();
                count_ast.action = Action::Get;
                count_ast.columns = vec![Expr::Aggregate {
                    col: "*".to_string(),
                    func: AggregateFunc::Count,
                    distinct: false,
                    filter: None,
                    alias: None,
                }];
                dml::select::build_select(&count_ast, dialect)
            }
            Action::Set => dml::update::build_update(self, dialect),
            Action::Del => dml::delete::build_delete(self, dialect),
            Action::Add => dml::insert::build_insert(self, dialect),
            Action::Gen => format!("-- gen::{}  (generates Rust struct, not SQL)", self.table),
            Action::Make => ddl::build_create_table(self, dialect),
            Action::Mod => ddl::build_alter_table(self, dialect),
            Action::Over => dml::window::build_window(self, dialect),
            Action::With => dml::cte::build_cte(self, dialect),
            Action::Index => ddl::build_create_index(self, dialect),
            Action::DropIndex => format!("DROP INDEX IF EXISTS {}", self.table),
            Action::Alter => ddl::build_alter_add_column(self, dialect),
            Action::AlterDrop => ddl::build_alter_drop_column(self, dialect),
            Action::AlterType => ddl::build_alter_column_type(self, dialect),
            // Stubs
            Action::TxnStart => "BEGIN TRANSACTION;".to_string(), // Default stub
            Action::TxnCommit => "COMMIT;".to_string(),
            Action::TxnRollback => "ROLLBACK;".to_string(),
            Action::Put => dml::upsert::build_upsert(self, dialect),
            Action::Drop => format!("DROP TABLE {}", self.table),
            Action::DropCol | Action::RenameCol => ddl::build_alter_column(self, dialect),
            // JSON features
            Action::JsonTable => dml::json_table::build_json_table(self, dialect),
            // COPY protocol (AST-native in qail-pg, generates SELECT for fallback)
            Action::Export => dml::select::build_select(self, dialect),
            // TRUNCATE TABLE
            Action::Truncate => format!("TRUNCATE TABLE {}", self.table),
            // EXPLAIN - wrap SELECT query
            Action::Explain => format!("EXPLAIN {}", dml::select::build_select(self, dialect)),
            // EXPLAIN ANALYZE - execute and analyze query
            Action::ExplainAnalyze => format!(
                "EXPLAIN ANALYZE {}",
                dml::select::build_select(self, dialect)
            ),
            // LOCK TABLE
            Action::Lock => format!("LOCK TABLE {} IN ACCESS EXCLUSIVE MODE", self.table),
            // CREATE MATERIALIZED VIEW - uses source_query for the view definition
            Action::CreateMaterializedView => {
                if let Some(source) = &self.source_query {
                    format!(
                        "CREATE MATERIALIZED VIEW {} AS {}",
                        self.table,
                        source.to_sql_with_dialect(dialect)
                    )
                } else if let Some(query) = &self.payload {
                    format!("CREATE MATERIALIZED VIEW {} AS {}", self.table, query)
                } else {
                    format!(
                        "CREATE MATERIALIZED VIEW {} AS {}",
                        self.table,
                        dml::select::build_select(self, dialect)
                    )
                }
            }
            // REFRESH MATERIALIZED VIEW
            Action::RefreshMaterializedView => format!("REFRESH MATERIALIZED VIEW {}", self.table),
            // DROP MATERIALIZED VIEW
            Action::DropMaterializedView => {
                format!("DROP MATERIALIZED VIEW IF EXISTS {}", self.table)
            }
            // LISTEN/NOTIFY (Pub/Sub)
            Action::Listen => {
                if let Some(ch) = &self.channel {
                    format!("LISTEN {}", ch)
                } else {
                    "LISTEN".to_string()
                }
            }
            Action::Notify => {
                if let Some(ch) = &self.channel {
                    if let Some(msg) = &self.payload {
                        format!("NOTIFY {}, '{}'", ch, msg)
                    } else {
                        format!("NOTIFY {}", ch)
                    }
                } else {
                    "NOTIFY".to_string()
                }
            }
            Action::Unlisten => {
                if let Some(ch) = &self.channel {
                    format!("UNLISTEN {}", ch)
                } else {
                    "UNLISTEN *".to_string()
                }
            }
            // Savepoints
            Action::Savepoint => {
                if let Some(name) = &self.savepoint_name {
                    format!("SAVEPOINT {}", name)
                } else {
                    "SAVEPOINT".to_string()
                }
            }
            Action::ReleaseSavepoint => {
                if let Some(name) = &self.savepoint_name {
                    format!("RELEASE SAVEPOINT {}", name)
                } else {
                    "RELEASE SAVEPOINT".to_string()
                }
            }
            Action::RollbackToSavepoint => {
                if let Some(name) = &self.savepoint_name {
                    format!("ROLLBACK TO SAVEPOINT {}", name)
                } else {
                    "ROLLBACK TO SAVEPOINT".to_string()
                }
            }
            // Views
            Action::CreateView => {
                if let Some(source) = &self.source_query {
                    format!(
                        "CREATE VIEW {} AS {}",
                        self.table,
                        source.to_sql_with_dialect(dialect)
                    )
                } else if let Some(query) = &self.payload {
                    format!("CREATE VIEW {} AS {}", self.table, query)
                } else {
                    format!(
                        "CREATE VIEW {} AS {}",
                        self.table,
                        dml::select::build_select(self, dialect)
                    )
                }
            }
            Action::DropView => format!("DROP VIEW IF EXISTS {}", self.table),
            // Vector database operations - use qail-qdrant driver instead
            operators::Action::Search | operators::Action::Upsert | operators::Action::Scroll => {
                format!(
                    "-- Vector operation {:?} not supported in SQL. Use qail-qdrant driver.",
                    self.action
                )
            }
            operators::Action::CreateCollection | operators::Action::DeleteCollection => {
                format!(
                    "-- Vector DDL {:?} not supported in SQL. Use qail-qdrant driver.",
                    self.action
                )
            }
            // Function and Trigger operations
            operators::Action::CreateFunction => {
                if let Some(func) = &self.function_def {
                    let lang = func.language.as_deref().unwrap_or("plpgsql");
                    let args = func.args.join(", ");
                    let volatility = func
                        .volatility
                        .as_deref()
                        .map(|v| format!(" {}", v.to_uppercase()))
                        .unwrap_or_default();
                    format!(
                        "CREATE OR REPLACE FUNCTION {}({}) RETURNS {} LANGUAGE {}{} AS $$ {} $$",
                        func.name, args, func.returns, lang, volatility, func.body
                    )
                } else {
                    "-- CreateFunction requires function_def".to_string()
                }
            }
            operators::Action::DropFunction => {
                if let Some(signature) = &self.payload {
                    format!("DROP FUNCTION IF EXISTS {}", signature)
                } else {
                    format!("DROP FUNCTION IF EXISTS {}()", self.table)
                }
            }
            operators::Action::CreateTrigger => {
                if let Some(trig) = &self.trigger_def {
                    let timing = match trig.timing {
                        crate::ast::TriggerTiming::Before => "BEFORE",
                        crate::ast::TriggerTiming::After => "AFTER",
                        crate::ast::TriggerTiming::InsteadOf => "INSTEAD OF",
                    };
                    let events: Vec<&str> = trig
                        .events
                        .iter()
                        .map(|e| match e {
                            crate::ast::TriggerEvent::Insert => "INSERT",
                            crate::ast::TriggerEvent::Update => "UPDATE",
                            crate::ast::TriggerEvent::Delete => "DELETE",
                            crate::ast::TriggerEvent::Truncate => "TRUNCATE",
                        })
                        .collect();
                    let for_each = if trig.for_each_row {
                        "FOR EACH ROW"
                    } else {
                        "FOR EACH STATEMENT"
                    };
                    format!(
                        "CREATE TRIGGER {} {} {} ON {} {} EXECUTE FUNCTION {}()",
                        trig.name,
                        timing,
                        events.join(" OR "),
                        trig.table,
                        for_each,
                        trig.execute_function
                    )
                } else {
                    "-- CreateTrigger requires trigger_def".to_string()
                }
            }
            operators::Action::DropTrigger => {
                if let Some((table, trigger)) = self.table.rsplit_once('.') {
                    format!("DROP TRIGGER IF EXISTS {} ON {}", trigger, table)
                } else {
                    format!("DROP TRIGGER IF EXISTS {}", self.table)
                }
            }
            // Phase 7: Extensions, Comments, Sequences
            Action::CreateExtension => ddl::build_create_extension(self, dialect),
            Action::DropExtension => ddl::build_drop_extension(self, dialect),
            Action::CommentOn => ddl::build_comment_on(self, dialect),
            Action::CreateSequence => ddl::build_create_sequence(self, dialect),
            Action::DropSequence => ddl::build_drop_sequence(self, dialect),
            Action::CreateEnum => ddl::build_create_enum(self, dialect),
            Action::DropEnum => ddl::build_drop_enum(self, dialect),
            Action::AlterEnumAddValue => ddl::build_alter_enum_add_value(self, dialect),
            // ALTER TABLE property operations (from diff engine)
            Action::AlterSetNotNull => {
                if let Some(Expr::Named(col)) = self.columns.first() {
                    format!(
                        "ALTER TABLE {} ALTER COLUMN {} SET NOT NULL",
                        self.table, col
                    )
                } else {
                    format!("ALTER TABLE {} ALTER COLUMN ... SET NOT NULL", self.table)
                }
            }
            Action::AlterDropNotNull => {
                if let Some(Expr::Named(col)) = self.columns.first() {
                    format!(
                        "ALTER TABLE {} ALTER COLUMN {} DROP NOT NULL",
                        self.table, col
                    )
                } else {
                    format!("ALTER TABLE {} ALTER COLUMN ... DROP NOT NULL", self.table)
                }
            }
            Action::AlterSetDefault => {
                if let Some(Expr::Named(col)) = self.columns.first() {
                    let default_expr = self.payload.as_deref().unwrap_or("NULL");
                    format!(
                        "ALTER TABLE {} ALTER COLUMN {} SET DEFAULT {}",
                        self.table, col, default_expr
                    )
                } else {
                    format!(
                        "ALTER TABLE {} ALTER COLUMN ... SET DEFAULT ...",
                        self.table
                    )
                }
            }
            Action::AlterDropDefault => {
                if let Some(Expr::Named(col)) = self.columns.first() {
                    format!(
                        "ALTER TABLE {} ALTER COLUMN {} DROP DEFAULT",
                        self.table, col
                    )
                } else {
                    format!("ALTER TABLE {} ALTER COLUMN ... DROP DEFAULT", self.table)
                }
            }
            Action::AlterEnableRls => {
                format!("ALTER TABLE {} ENABLE ROW LEVEL SECURITY", self.table)
            }
            Action::AlterDisableRls => {
                format!("ALTER TABLE {} DISABLE ROW LEVEL SECURITY", self.table)
            }
            Action::AlterForceRls => {
                format!("ALTER TABLE {} FORCE ROW LEVEL SECURITY", self.table)
            }
            Action::AlterNoForceRls => {
                format!("ALTER TABLE {} NO FORCE ROW LEVEL SECURITY", self.table)
            }
            // Session & procedural commands
            Action::Call => {
                format!("CALL {}", self.table)
            }
            Action::Do => {
                let body = self.payload.as_deref().unwrap_or("");
                let lang = if self.table.is_empty() {
                    "plpgsql"
                } else {
                    &self.table
                };
                format!("DO $$ {} $$ LANGUAGE {}", body, lang)
            }
            Action::SessionSet => {
                let value = self.payload.as_deref().unwrap_or("");
                format!("SET {} = '{}'", self.table, value)
            }
            Action::SessionShow => {
                format!("SHOW {}", self.table)
            }
            Action::SessionReset => {
                format!("RESET {}", self.table)
            }
            Action::CreateDatabase => {
                format!("CREATE DATABASE {}", escape_identifier(&self.table))
            }
            Action::DropDatabase => {
                format!("DROP DATABASE IF EXISTS {}", escape_identifier(&self.table))
            }
            Action::Grant => {
                let role = self.payload.as_deref().unwrap_or("");
                let privs: Vec<String> = self
                    .columns
                    .iter()
                    .filter_map(|c| match c {
                        Expr::Named(p) => Some(p.clone()),
                        _ => None,
                    })
                    .collect();
                format!("GRANT {} ON {} TO {}", privs.join(", "), self.table, role)
            }
            Action::Revoke => {
                let role = self.payload.as_deref().unwrap_or("");
                let privs: Vec<String> = self
                    .columns
                    .iter()
                    .filter_map(|c| match c {
                        Expr::Named(p) => Some(p.clone()),
                        _ => None,
                    })
                    .collect();
                format!(
                    "REVOKE {} ON {} FROM {}",
                    privs.join(", "),
                    self.table,
                    role
                )
            }
            Action::CreatePolicy => {
                if let Some(policy) = &self.policy_def {
                    policy::create_policy_sql(policy)
                } else {
                    "-- CreatePolicy requires policy_def".to_string()
                }
            }
            Action::DropPolicy => {
                if let Some(policy) = &self.policy_def {
                    policy::drop_policy_sql(&policy.name, &policy.table)
                } else if let Some(policy_name) = &self.payload {
                    policy::drop_policy_sql(policy_name, &self.table)
                } else {
                    "-- DropPolicy requires policy name + table".to_string()
                }
            }
        }
    }
}

impl ToSqlParameterized for Qail {
    fn to_sql_parameterized_with_dialect(&self, dialect: Dialect) -> TranspileResult {
        // Use the full ToSql implementation which handles CTEs, JOINs, etc.
        // Then post-process to extract named parameters for binding
        let full_sql = self.to_sql_with_dialect(dialect);

        // and replace them with positional parameters ($1, $2, etc.)
        let mut named_params: Vec<String> = Vec::new();
        let mut seen_params: std::collections::HashMap<String, usize> =
            std::collections::HashMap::new();
        let mut result = String::with_capacity(full_sql.len());
        let mut chars = full_sql.chars().peekable();
        let mut param_index = 1;

        while let Some(c) = chars.next() {
            if c == ':'
                && let Some(&next) = chars.peek()
            {
                if next == ':' {
                    result.push(':');
                    if let Some(double_colon) = chars.next() {
                        result.push(double_colon);
                    }
                    continue;
                }
                if next.is_ascii_alphabetic() || next == '_' {
                    let mut param_name = String::new();
                    while let Some(&ch) = chars.peek() {
                        if ch.is_ascii_alphanumeric() || ch == '_' {
                            if let Some(param_ch) = chars.next() {
                                param_name.push(param_ch);
                            } else {
                                break;
                            }
                        } else {
                            break;
                        }
                    }

                    let idx = if let Some(&existing) = seen_params.get(&param_name) {
                        existing
                    } else {
                        let idx = param_index;
                        seen_params.insert(param_name.clone(), idx);
                        named_params.push(param_name);
                        param_index += 1;
                        idx
                    };

                    result.push('$');
                    result.push_str(&idx.to_string());
                    continue;
                }
            }
            result.push(c);
        }

        TranspileResult {
            sql: result,
            params: Vec::new(), // Positional params not used, named_params provides mapping
            named_params,
        }
    }
}