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
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
/// Base parsing utilities (identifiers, literals, whitespace).
pub mod base;
/// Binary operator parsing (AND, OR, arithmetic).
pub mod binary_ops;
/// CASE WHEN expression parsing.
pub mod case_when;
/// Clause parsing (WHERE, ORDER BY, LIMIT, etc.).
pub mod clauses;
/// Common Table Expression (WITH) parsing.
pub mod cte;
/// Data Definition Language parsing (CREATE TABLE, INDEX).
pub mod ddl;
/// Data Manipulation Language parsing (INSERT values, ON CONFLICT).
pub mod dml;
/// Expression parsing (columns, functions, sub-expressions).
pub mod expressions;
/// Function call parsing.
pub mod functions;
/// JOIN clause parsing.
pub mod joins;
/// PostgreSQL MERGE parsing.
pub mod merge;
/// Special function parsing (COALESCE, NULLIF, GREATEST, etc.).
pub mod special_funcs;

use self::base::*;
use self::clauses::*;
use self::ddl::*;
use self::dml::*;
use self::joins::*;
use crate::ast::*;
use nom::{
    IResult, Parser,
    bytes::complete::tag_no_case,
    character::complete::{multispace0, multispace1},
    combinator::opt,
    multi::many0,
};
// use self::expressions::*; // Used in clauses module

/// Parse a QAIL query with comment preprocessing.
/// This is the recommended entry point - handles SQL comment stripping
/// and `table[filter]` shorthand desugaring.
pub fn parse(input: &str) -> Result<Qail, String> {
    let cleaned = strip_sql_comments(input);
    // Desugar table[filter] shorthand: "set users[active = true] fields ..."
    // → "set users fields ... where active = true"
    let desugared = desugar_bracket_filter(&cleaned);
    match parse_root(&desugared) {
        Ok(("", cmd)) => Ok(cmd),
        Ok((remaining, _)) => Err(format!("Unexpected trailing content: '{}'", remaining)),
        Err(e) => Err(format!("Parse error: {:?}", e)),
    }
}

/// Desugar `table[filter]` shorthand into `table ... where filter`.
/// Transforms: `action table[cond] rest` → `action table rest where cond`
fn desugar_bracket_filter(input: &str) -> String {
    let trimmed = input.trim();
    // Find the opening bracket after the table name
    // Must be: action<ws>table[...] — the [ must immediately follow the table name
    if let Some(bracket_start) = trimmed.find('[') {
        // Ensure the bracket is in the table position (after action + space + identifier)
        let before_bracket = &trimmed[..bracket_start];
        // There should be at least "action table" before the bracket
        if !before_bracket.contains(' ') {
            return trimmed.to_string();
        }

        // Guard: don't treat brackets in clauses/values as table shorthand.
        // Example to avoid: `... where tags && '["a","b"]'`
        let before_lower = before_bracket.to_ascii_lowercase();
        if before_lower.contains(" where ")
            || before_lower.contains(" fields ")
            || before_lower.contains(" having ")
            || before_lower.contains(" order ")
            || before_lower.contains(" limit ")
            || before_lower.contains(" offset ")
            || before_lower.contains(" join ")
        {
            return trimmed.to_string();
        }

        // Find matching closing bracket, respecting nesting and quotes
        let after_bracket = &trimmed[bracket_start + 1..];
        let mut depth = 1;
        let mut in_single_quote = false;
        let mut in_double_quote = false;
        let mut bracket_end = None;

        for (i, c) in after_bracket.char_indices() {
            match c {
                '\'' if !in_double_quote => in_single_quote = !in_single_quote,
                '"' if !in_single_quote => in_double_quote = !in_double_quote,
                '[' if !in_single_quote && !in_double_quote => depth += 1,
                ']' if !in_single_quote && !in_double_quote => {
                    depth -= 1;
                    if depth == 0 {
                        bracket_end = Some(i);
                        break;
                    }
                }
                _ => {}
            }
        }

        if let Some(end_pos) = bracket_end {
            let filter = &after_bracket[..end_pos];
            let rest = &after_bracket[end_pos + 1..].trim();

            // Check if there's already a "where" in the rest
            let rest_lower = rest.to_lowercase();
            if rest_lower.contains("where ") || rest_lower.contains("where\n") {
                // Already has WHERE — append with AND
                return format!("{} {} AND {}", before_bracket, rest, filter);
            } else if rest.is_empty() {
                return format!("{} where {}", before_bracket, filter);
            } else {
                return format!("{} {} where {}", before_bracket, rest, filter);
            }
        }
    }
    trimmed.to_string()
}

/// Parse a QAIL query (root entry point).
/// Note: Does NOT strip comments. Use `parse()` for automatic comment handling.
pub fn parse_root(input: &str) -> IResult<&str, Qail> {
    let input = input.trim();

    // Try transaction commands first (single keywords)
    if let Ok((remaining, cmd)) = parse_txn_command(input) {
        return Ok((remaining, cmd));
    }

    // Parse procedural/session commands that don't follow `action table ...`
    if let Ok((remaining, cmd)) = parse_procedural_command(input) {
        return Ok((remaining, cmd));
    }

    // Try CREATE INDEX first (special case: "index name on table ...")
    if let Ok((remaining, cmd)) = parse_create_index(input) {
        return Ok((remaining, cmd));
    }

    // Try WITH clause (CTE) parsing
    let lower_input = input.to_lowercase();
    let (input, ctes) = if lower_input.starts_with("with")
        && lower_input
            .chars()
            .nth(4)
            .map(|c| c.is_whitespace())
            .unwrap_or(false)
    {
        let (remaining, (cte_defs, _is_recursive)) = cte::parse_with_clause(input)?;
        let (remaining, _) = multispace0(remaining)?;
        (remaining, cte_defs)
    } else {
        (input, vec![])
    };

    let (input, (action, distinct)) = parse_action(input)?;
    // v2 syntax only: whitespace separator between action and table
    let (input, _) = multispace1(input)?;

    // Supports expressions like: CASE WHEN ... END, functions, columns
    let (input, distinct_on) = if distinct {
        // If already parsed "get distinct", check for "on (...)"
        if let Ok((remaining, _)) = tag_no_case::<_, _, nom::error::Error<&str>>("on").parse(input)
        {
            let (remaining, _) = multispace0(remaining)?;
            let (remaining, exprs) = nom::sequence::delimited(
                nom::character::complete::char('('),
                nom::multi::separated_list1(
                    (
                        multispace0,
                        nom::character::complete::char(','),
                        multispace0,
                    ),
                    expressions::parse_expression,
                ),
                nom::character::complete::char(')'),
            )
            .parse(remaining)?;
            let (remaining, _) = multispace1(remaining)?;
            (remaining, exprs)
        } else {
            (input, vec![])
        }
    } else {
        (input, vec![])
    };

    //  Parse table name
    let (input, table) = parse_identifier(input)?;
    let (input, _) = multispace0(input)?;

    // For MAKE (CREATE TABLE): parse column definitions
    if matches!(action, Action::Make) {
        return parse_create_table(input, table);
    }

    if matches!(action, Action::Merge) {
        return merge::parse_merge_after_target(input, table, ctes);
    }

    let (input, joins) = many0(parse_join_clause).parse(input)?;
    let (input, _) = multispace0(input)?;

    // For SET/UPDATE: parse "values col = val, col2 = val2" before fields
    let (input, set_cages) = if matches!(action, Action::Set) {
        opt(parse_values_clause).parse(input)?
    } else {
        (input, None)
    };
    let (input, _) = multispace0(input)?;

    let (input, columns) = opt(parse_fields_clause).parse(input)?;
    let (input, _) = multispace0(input)?;

    // For ADD/INSERT: try "from (get ...)" first, then fall back to "values val1, val2"
    let (input, source_query) = if matches!(action, Action::Add) {
        opt(dml::parse_source_query).parse(input)?
    } else {
        (input, None)
    };
    let (input, _) = multispace0(input)?;

    // Only parse values if no source_query (INSERT...SELECT takes precedence)
    let (input, add_cages) = if source_query.is_none() && matches!(action, Action::Add) {
        opt(dml::parse_insert_values).parse(input)?
    } else {
        (input, None)
    };
    let (input, _) = multispace0(input)?;

    let (input, where_cages) = opt(parse_where_clause).parse(input)?;
    let (input, _) = multispace0(input)?;

    let (input, having) = opt(parse_having_clause).parse(input)?;
    let (input, _) = multispace0(input)?;

    let (input, on_conflict) = if matches!(action, Action::Add) {
        opt(dml::parse_on_conflict).parse(input)?
    } else {
        (input, None)
    };
    let (input, _) = multispace0(input)?;

    let (input, order_cages) = opt(parse_order_by_clause).parse(input)?;
    let (input, _) = multispace0(input)?;
    let (input, limit_cage) = opt(parse_limit_clause).parse(input)?;
    let (input, _) = multispace0(input)?;
    let (input, offset_cage) = opt(parse_offset_clause).parse(input)?;

    let mut cages = Vec::new();

    // For SET, values come first (as Payload cage)
    if let Some(sc) = set_cages {
        cages.push(sc);
    }

    // For ADD, values come as Payload cage too
    if let Some(ac) = add_cages {
        cages.push(ac);
    }

    if let Some(wc) = where_cages {
        cages.extend(wc);
    }
    if let Some(oc) = order_cages {
        cages.extend(oc);
    }
    if let Some(lc) = limit_cage {
        cages.push(lc);
    }
    if let Some(oc) = offset_cage {
        cages.push(oc);
    }

    Ok((
        input,
        Qail {
            action,
            table: table.to_string(),
            columns: columns.unwrap_or_else(|| vec![Expr::Star]),
            joins,
            cages,
            distinct,
            distinct_on,
            index_def: None,
            table_constraints: vec![],
            set_ops: vec![],
            having: having.unwrap_or_default(),
            group_by_mode: GroupByMode::default(),
            returning: None,
            ctes,
            on_conflict,
            merge: None,
            source_query,
            channel: None,
            payload: None,
            savepoint_name: None,
            from_tables: vec![],
            using_tables: vec![],
            lock_mode: None,
            skip_locked: false,
            fetch: None,
            default_values: false,
            overriding: None,
            sample: None,
            only_table: false,
            vector: None,
            score_threshold: None,
            vector_name: None,
            with_vector: false,
            vector_size: None,
            distance: None,
            on_disk: None,
            function_def: None,
            trigger_def: None,
            policy_def: None,
        },
    ))
}

/// Strip SQL comments from input (both -- line comments and /* */ block comments)
fn strip_sql_comments(input: &str) -> String {
    let mut result = String::with_capacity(input.len());
    let bytes = input.as_bytes();
    let mut i = 0;
    let mut in_single_quote = false;
    let mut in_double_quote = false;
    let mut raw_delimiter: Option<String> = None;

    while i < input.len() {
        if let Some(ref delimiter) = raw_delimiter {
            if input[i..].starts_with(delimiter) {
                result.push_str(delimiter);
                i += delimiter.len();
                raw_delimiter = None;
            } else {
                push_char_at(input, &mut result, &mut i);
            }
            continue;
        }

        if in_single_quote {
            if bytes[i] == b'\'' {
                result.push('\'');
                i += 1;
                if i < input.len() && bytes[i] == b'\'' {
                    result.push('\'');
                    i += 1;
                } else {
                    in_single_quote = false;
                }
            } else {
                push_char_at(input, &mut result, &mut i);
            }
            continue;
        }

        if in_double_quote {
            if bytes[i] == b'"' {
                result.push('"');
                i += 1;
                if i < input.len() && bytes[i] == b'"' {
                    result.push('"');
                    i += 1;
                } else {
                    in_double_quote = false;
                }
            } else {
                push_char_at(input, &mut result, &mut i);
            }
            continue;
        }

        if input[i..].starts_with("'''") || input[i..].starts_with("\"\"\"") {
            let delimiter = &input[i..i + 3];
            result.push_str(delimiter);
            raw_delimiter = Some(delimiter.to_string());
            i += 3;
            continue;
        }

        if bytes[i] == b'\'' {
            in_single_quote = true;
            result.push('\'');
            i += 1;
            continue;
        }

        if bytes[i] == b'"' {
            in_double_quote = true;
            result.push('"');
            i += 1;
            continue;
        }

        if let Some(delimiter_len) = dollar_quote_delimiter_len(bytes, i) {
            let delimiter = &input[i..i + delimiter_len];
            result.push_str(delimiter);
            raw_delimiter = Some(delimiter.to_string());
            i += delimiter_len;
            continue;
        }

        if bytes[i] == b'-' && i + 1 < input.len() && bytes[i + 1] == b'-' {
            i += 2;
            while i < input.len() {
                let Some(ch) = input.get(i..).and_then(|s| s.chars().next()) else {
                    break;
                };
                i += ch.len_utf8();
                if ch == '\n' {
                    result.push('\n');
                    break;
                }
            }
        } else if bytes[i] == b'/' && i + 1 < input.len() && bytes[i + 1] == b'*' {
            i += 2;
            let mut closed = false;
            while i < input.len() {
                if bytes[i] == b'*' && i + 1 < input.len() && bytes[i + 1] == b'/' {
                    i += 2;
                    result.push(' '); // replace with space to preserve separation
                    closed = true;
                    break;
                }
                advance_char(input, &mut i);
            }
            if !closed {
                // Unclosed block comment — preserve raw text so parser reports error
                result.push_str("/*");
            }
        } else {
            push_char_at(input, &mut result, &mut i);
        }
    }

    result
}

fn push_char_at(input: &str, output: &mut String, index: &mut usize) {
    if let Some(ch) = input.get(*index..).and_then(|s| s.chars().next()) {
        output.push(ch);
        *index += ch.len_utf8();
    } else {
        *index = input.len();
    }
}

fn advance_char(input: &str, index: &mut usize) {
    if let Some(ch) = input.get(*index..).and_then(|s| s.chars().next()) {
        *index += ch.len_utf8();
    } else {
        *index = input.len();
    }
}

fn dollar_quote_delimiter_len(bytes: &[u8], start: usize) -> Option<usize> {
    if bytes.get(start) != Some(&b'$') {
        return None;
    }

    let mut end = start + 1;
    if bytes.get(end) == Some(&b'$') {
        return Some(2);
    }

    let first = *bytes.get(end)?;
    if !first.is_ascii_alphabetic() && first != b'_' {
        return None;
    }
    end += 1;

    while let Some(&byte) = bytes.get(end) {
        if byte == b'$' {
            return Some(end - start + 1);
        }
        if !byte.is_ascii_alphanumeric() && byte != b'_' {
            return None;
        }
        end += 1;
    }

    None
}