Skip to main content

spg_sql/
parser.rs

1//! Recursive-descent parser with a Pratt (precedence-climbing) sub-parser for
2//! expressions.
3//!
4//! Precedence (lowest → highest binding):
5//! `OR` (1) `<` `AND` (2) `<` `NOT` unary (3) `<`
6//! comparisons `=` `<>` `<` `<=` `>` `>=` (4) `<`
7//! `+` `-` (5) `<` `*` `/` (6) `<` unary `-` (7) `<` parens / atom.
8//!
9//! This matches PG's behaviour for the operators we support — e.g. `NOT a = b`
10//! parses as `NOT (a = b)` and `-a * b` as `(-a) * b`.
11
12use alloc::boxed::Box;
13use alloc::format;
14use alloc::string::{String, ToString};
15use alloc::vec;
16use alloc::vec::Vec;
17use core::fmt;
18use core::mem;
19
20use crate::ast::{
21    AssignTarget, BinOp, CastTarget, Collation, ColumnDef, ColumnName, ColumnTypeName,
22    CreateFunctionStatement, CreateIndexStatement, CreatePublicationStatement,
23    CreateSubscriptionStatement, CreateTableStatement, CreateTriggerStatement, DiscardTarget, Expr,
24    ExtractField, FkAction, ForeignKeyConstraint, FrameBound, FrameExclusion, FrameKind,
25    FromClause, FromJoin, FunctionArg, FunctionArgMode, FunctionArgType, FunctionAttrs,
26    FunctionBody, FunctionParallel, FunctionReturn, FunctionVolatility, GrantObject, GrantPriv,
27    GrantStatement, IndexMethod, InsertStatement, IsolationLevel, JoinKind, Literal, MysqlIntWidth,
28    NullTreatment, OrderBy, Overriding, PlPgSqlBlock, PlPgSqlDeclare, PlPgSqlStmt,
29    PublicationScope, RaiseLevel, RangeKindAst, ReturnTarget, SelectItem, SelectStatement,
30    Statement, TableRef, TriggerEvent, TriggerForEach, TriggerTiming, UnOp, UnionKind, VecEncoding,
31    WindowFrame,
32};
33use crate::lexer::{self, LexError, Token};
34
35/// v7.38 — a `WINDOW w AS (…)` definition body:
36/// `(PARTITION BY exprs, ORDER BY (expr, desc, nulls_first), frame)`.
37type WindowDef = (
38    Vec<Expr>,
39    Vec<(Expr, bool, Option<bool>)>,
40    Option<WindowFrame>,
41);
42
43/// v7.14.0 — true when the leading keyword of a top-level
44/// statement is one of the dump-emitted DDL forms SPG accepts
45/// as a no-op (no behavioural effect on the single-schema /
46/// single-database model). These statements are consumed up to
47/// the next `;` / EOF and returned as `Statement::Empty`.
48/// v7.39 (read01 round 57) — wrap a parsed GRANT body in the right statement.
49fn finish_grant(grant: bool, g: GrantStatement) -> Statement {
50    if grant {
51        Statement::Grant(g)
52    } else {
53        Statement::Revoke(g)
54    }
55}
56
57fn is_dump_noise_statement(lc: &str) -> bool {
58    matches!(
59        lc,
60        // v7.39 (read01 round 50): "comment" moved OUT — COMMENT ON is now a
61        // real statement with a real store. v7.39 (read01 round 57): "grant" /
62        // "revoke" moved OUT — table privileges are now REAL (stored in
63        // `relacl`, enforced against the session role); a grant on any other
64        // object class still parses and no-ops so dumps restore.
65        // MySQL bulk-load brackets.
66        "unlock"
67            // MySQL OPTIMIZE / ANALYZE TABLE / CHECK TABLE
68            // diagnostics that pg_dump-style tools also emit
69            // post-restore.
70            | "optimize"
71            | "check"
72            // PG psql backslash meta-commands that newer
73            // pg_dump versions emit unescaped (\restrict /
74            // \unrestrict). Real psql intercepts these; SPG's
75            // PG-wire sees them as raw text.
76            | "\\restrict"
77            | "\\unrestrict"
78            // v7.17.0 Phase 4.1 — MySQL `DELIMITER //` and
79            // `DELIMITER ;` directives. Technically client-side
80            // (the `mysql` CLI uses them to set the statement
81            // terminator), not SQL — but mysqldump and stored-
82            // procedure scripts emit them inline. SPG's parser
83            // sees one statement at a time and doesn't care
84            // about the terminator, so consume DELIMITER lines
85            // as Empty.
86            | "delimiter"
87            // v7.37.17 (17.6 siblings) — additional PG maintenance /
88            // session-state statements pg_dump + application startup
89            // scripts emit. SPG has no matching session-state to
90            // discard (no prepared-plan cache surface, no temp
91            // sequences), no matching security-label / storage-
92            // option to apply, no separate CREATE/DROP CAST that
93            // affects execution.
94            // v7.37.17 (17.6 siblings) — PG role-cleanup statements
95            // pg_dump / pg_dumpall emit around DROP ROLE:
96            //   REASSIGN OWNED BY <role> [, ...] TO <newrole>
97            //   DROP OWNED BY <role> [, ...] [CASCADE | RESTRICT]
98            // Both operate on the role's owned objects; SPG has no
99            // role-owner model, so accept-and-no-op.
100            // v7.37.17 (17.6 sibling) — LOAD '<library>'. pg_dump
101            // + extension scripts use LOAD to preload shared
102            // libraries. SPG doesn't have a shared-library extension
103            // point today (extensions ship as first-class crates
104            // linked at build time); accept as a no-op.
105            | "load"
106    )
107}
108
109/// v7.37.43-T4 — PG-unreserved keywords that are legal identifiers
110/// per `pg_get_keywords()`. SPG tokenizes these as named variants
111/// so the parser can dispatch on them in their owning contexts
112/// (`RELEASE SAVEPOINT`, `SHOW name`, `BEGIN`/`COMMIT`/`ROLLBACK`,
113/// `CREATE INDEX`, etc.), but they MUST stay usable as table /
114/// column / alias names — that's the PG contract for unreserved
115/// keywords (see PG docs Appendix C.1).
116///
117/// Before this generalisation, sentori migration 0001_init.sql
118/// `release TEXT NOT NULL` blew up the parser with "expected
119/// identifier, got Release", and the same gap stalked every
120/// SPG drop-in user whose schema had a column / alias named
121/// `release` / `index` / `tables` / `show` / `savepoint` /
122/// `begin` / `commit` / `rollback` / `drop` / `insert` / `values`
123/// / `limit` / `partition`. PG accepts all of them as identifiers
124/// when unquoted, so SPG must too.
125///
126/// Returns the canonical lowercase identifier text when the token
127/// belongs to PG's unreserved class, `None` otherwise. Used by
128/// `expect_ident_like` (column / table / alias names) so the
129/// generalisation applies everywhere an identifier may appear,
130/// not just in the contexts these tokens were introduced for.
131fn unreserved_keyword_text(tok: &Token) -> Option<String> {
132    let s = match tok {
133        // PG keyword class: unreserved or col_name.
134        //
135        Token::Release => "release",
136        Token::Savepoint => "savepoint",
137        Token::Show => "show",
138        Token::Index => "index",
139        Token::Begin => "begin",
140        Token::Commit => "commit",
141        Token::Rollback => "rollback",
142        Token::Drop => "drop",
143        Token::Insert => "insert",
144        Token::Values => "values",
145        Token::Limit => "limit",
146        Token::Partition => "partition",
147        Token::Tables => "tables",
148        Token::Connection => "connection",
149        Token::Publication => "publication",
150        Token::Subscription => "subscription",
151        Token::Interval => "interval",
152        // `extract` is non-reserved in PG too (it's a function the
153        // parser dispatches via context — outside that context it's
154        // a plain identifier).
155        Token::Extract => "extract",
156        Token::Offset => "offset",
157        // `to` is reserved in PG (used in many "AS … TO …" forms), so
158        // it is NOT relaxed here. Same for `from`, `where`, `as`,
159        // `select`, `not`, `and`, `or`, `null`, `true`, `false`,
160        // `create`, `table`, `into`, `on`, `order`, `by`, `having`,
161        // `group`, `distinct`, `union`, `all`, `join`, `inner`,
162        // `left`, `cross`, `outer`, `default`, `is`, `between`,
163        // `in`, `like`, `for`, `except`, `desc`, `asc`, `partition`
164        // (partial — keep partition as unreserved per modern PG).
165        _ => return None,
166    };
167    Some(s.to_string())
168}
169
170/// v7.9.22 — recognise pgvector / SPG vector-index opclass names
171/// in CREATE INDEX. SPG's HNSW already routes by query operator;
172/// the opclass is accepted for `pg_dump` compatibility (mailrs
173/// migration follow-up G5).
174/// v7.13.0 — extended to recognise PG built-in / pg_trgm opclasses
175/// (mailrs round-5 G5). These are tokens-only acceptance — SPG
176/// doesn't change index behaviour based on them.
177/// v7.37.17 (17.6 siblings) — the four PG `each` SRFs share one
178/// FROM-clause pipeline; the stored name tells the executor whether
179/// the value column keeps JSON rendering (`jsonb_each` / `json_each`)
180/// or unwraps to text (`*_each_text`).
181fn is_json_each_name(s: &str) -> bool {
182    s.eq_ignore_ascii_case("jsonb_each_text")
183        || s.eq_ignore_ascii_case("jsonb_each")
184        || s.eq_ignore_ascii_case("json_each_text")
185        || s.eq_ignore_ascii_case("json_each")
186}
187
188/// v7.38 (read01, T14) — resolve named function arguments (`argname => value`)
189/// to positional order for the `make_*` family (the AST stays positional).
190/// Positional args fill slots left-to-right; a named arg goes to its registered
191/// slot; unfilled slots default to integer 0 (PG's optional make_interval
192/// fields — the make_date/time arity is still checked at eval time).
193fn reorder_named_args(
194    fname: &str,
195    args: Vec<Expr>,
196    names: &[Option<String>],
197) -> Result<Vec<Expr>, String> {
198    let params: &[&str] = match fname.to_ascii_lowercase().as_str() {
199        "make_date" => &["year", "month", "day"],
200        "make_time" => &["hour", "min", "sec"],
201        "make_timestamp" | "make_timestamptz" => &["year", "month", "mday", "hour", "min", "sec"],
202        "make_interval" => &["years", "months", "weeks", "days", "hours", "mins", "secs"],
203        other => {
204            return Err(alloc::format!(
205                "function {other}(...) does not support named arguments"
206            ));
207        }
208    };
209    let mut slots: Vec<Option<Expr>> = (0..params.len()).map(|_| None).collect();
210    let mut next_positional = 0usize;
211    for (arg, name) in args.into_iter().zip(names.iter()) {
212        let idx = match name {
213            Some(n) => params
214                .iter()
215                .position(|p| p.eq_ignore_ascii_case(n))
216                .ok_or_else(|| alloc::format!("{fname}(...) has no argument named \"{n}\""))?,
217            None => {
218                let i = next_positional;
219                next_positional += 1;
220                i
221            }
222        };
223        if idx >= slots.len() {
224            return Err(alloc::format!("too many arguments for {fname}(...)"));
225        }
226        if slots[idx].is_some() {
227            return Err(alloc::format!(
228                "argument \"{}\" specified more than once",
229                params[idx]
230            ));
231        }
232        slots[idx] = Some(arg);
233    }
234    Ok(slots
235        .into_iter()
236        .map(|s| s.unwrap_or(Expr::Literal(Literal::Integer(0))))
237        .collect())
238}
239
240/// v7.38 (read01) — parse a lexer `Token::Numeric` source string (digits with
241/// an optional single `.`, no sign, no exponent) into `(unscaled, scale)` for
242/// `Literal::Numeric`. Returns `None` if the mantissa overflows i128.
243/// v7.39 (read01 numeric.c) — the result of expanding an `1.5e3`-style
244/// scientific literal into PG's plain NUMERIC decimal form.
245#[derive(Debug)]
246pub enum SciExpanded {
247    /// Plain decimal string ("1.5e3" → "1500", "1e-5" → "0.00001").
248    Expanded(String),
249    /// Exponent pushes the value outside PG's numeric format
250    /// (more than 131072 integer digits or 16383 fractional digits).
251    Overflow,
252    /// Not a `[±]digits[.digits]e[±]digits` literal at all.
253    NotScientific,
254}
255
256/// Expand scientific notation into a plain decimal string by moving the
257/// decimal point — no float round-trip, so the value stays exact. PG treats
258/// such literals as NUMERIC; the digit-count caps mirror PG's numeric format
259/// limits ("value overflows numeric format").
260pub fn expand_scientific_literal(s: &str) -> SciExpanded {
261    let s = s.trim();
262    let Some(epos) = s.find(['e', 'E']) else {
263        return SciExpanded::NotScientific;
264    };
265    let (mant, exp_str) = (&s[..epos], &s[epos + 1..]);
266    let Ok(exp) = exp_str.parse::<i64>() else {
267        return SciExpanded::NotScientific;
268    };
269    let (neg, mant) = match mant.strip_prefix('-') {
270        Some(r) => (true, r),
271        None => (false, mant.strip_prefix('+').unwrap_or(mant)),
272    };
273    let (int_part, frac_part) = match mant.split_once('.') {
274        Some((i, f)) => (i, f),
275        None => (mant, ""),
276    };
277    if (int_part.is_empty() && frac_part.is_empty())
278        || !int_part.bytes().all(|b| b.is_ascii_digit())
279        || !frac_part.bytes().all(|b| b.is_ascii_digit())
280    {
281        return SciExpanded::NotScientific;
282    }
283    let mut digits = String::with_capacity(int_part.len() + frac_part.len());
284    digits.push_str(int_part);
285    digits.push_str(frac_part);
286    // Decimal point position within `digits` after applying the exponent.
287    let new_point = int_part.len() as i64 + exp;
288    // PG's numeric format: up to 131072 digits before the point, 16383 after.
289    if new_point > 131_072 {
290        return SciExpanded::Overflow;
291    }
292    if (digits.len() as i64 - new_point) > 16_383 {
293        return SciExpanded::Overflow;
294    }
295    let sign = if neg { "-" } else { "" };
296    let plain = if new_point <= 0 {
297        let mut out = String::with_capacity(digits.len() + 2 + (-new_point) as usize);
298        out.push_str("0.");
299        for _ in 0..(-new_point) {
300            out.push('0');
301        }
302        out.push_str(&digits);
303        out
304    } else if (new_point as usize) >= digits.len() {
305        let mut out = digits;
306        for _ in 0..(new_point as usize - out.len()) {
307            out.push('0');
308        }
309        out
310    } else {
311        let mut out = String::with_capacity(digits.len() + 1);
312        out.push_str(&digits[..new_point as usize]);
313        out.push('.');
314        out.push_str(&digits[new_point as usize..]);
315        out
316    };
317    SciExpanded::Expanded(alloc::format!("{sign}{plain}"))
318}
319
320/// v7.39 (round 367, M20) — lower a MySQL hexadecimal binary-string
321/// literal (`0x…` / `X'…'`) onto the existing bytea cast. The hex digits
322/// are left-padded to an even count (`0x123` → byte string `01 23`, per
323/// MariaDB) and handed to the PG bytea input format (`\x…`).
324#[inline(never)]
325fn hex_literal_to_bytea_expr(hex: &str) -> Expr {
326    let padded = if hex.len() % 2 == 1 {
327        alloc::format!("0{hex}")
328    } else {
329        hex.to_string()
330    };
331    Expr::Cast {
332        expr: alloc::boxed::Box::new(Expr::Literal(Literal::String(alloc::format!(
333            "\\x{padded}"
334        )))),
335        target: CastTarget::Named("bytea".to_string()),
336    }
337}
338
339/// v7.39 (round 367, M20) — lower a MySQL bit-value literal (`b'1010'`)
340/// onto the bytea cast. The bits are read big-endian and left-padded to a
341/// whole number of bytes (`b'1010'` → one byte `0x0A`, per MariaDB).
342#[inline(never)]
343fn bits_literal_to_bytea_expr(bits: &str) -> Expr {
344    let pad = (8 - bits.len() % 8) % 8;
345    let mut hex = String::with_capacity((bits.len() + pad).div_ceil(4));
346    let padded: String = core::iter::repeat_n('0', pad).chain(bits.chars()).collect();
347    for nibble in padded.as_bytes().chunks(4) {
348        let mut v = 0u8;
349        for &b in nibble {
350            v = (v << 1) | (b - b'0');
351        }
352        hex.push(char::from_digit(u32::from(v), 16).unwrap_or('0'));
353    }
354    hex_literal_to_bytea_expr(&hex)
355}
356
357/// Resolve a lexer `Token::Numeric` into its literal. PG semantics: a dotted
358/// or over-i64 literal is exact NUMERIC; scientific notation is NUMERIC too
359/// (expanded to the plain decimal form); only a fractional depth beyond SPG's
360/// scale width (u8) falls back to double precision.
361///
362/// v7.38.19 — that sentence used to end "(recorded delta)". Measured
363/// against PG 18.4: a literal with 300 fractional digits round-trips
364/// identically on both engines, so whatever the note described is gone.
365/// It is RD-7 in `docs/RECORDED_DELTAS.md`, under "corrected by
366/// measurement" rather than under "open".
367/// Kept out of the parse_expr recursion frame — see the call site.
368#[inline(never)]
369fn numeric_token_to_literal(s: String) -> Result<Literal, String> {
370    match parse_decimal_literal(&s) {
371        Some((unscaled, scale)) => Ok(Literal::Numeric { unscaled, scale }),
372        // v7.38 (read01, T3.C3) — a plain decimal too wide for i128 keeps
373        // its exact value as a NumericBig.
374        None if !s.contains(['e', 'E']) => Ok(Literal::NumericBig(s)),
375        // v7.39 (read01 numeric.c) — expand the exponent form.
376        None => match expand_scientific_literal(&s) {
377            SciExpanded::Expanded(plain) => match parse_decimal_literal(&plain) {
378                Some((unscaled, scale)) => Ok(Literal::Numeric { unscaled, scale }),
379                None if plain
380                    .split_once('.')
381                    .is_none_or(|(_, f)| u8::try_from(f.len()).is_ok()) =>
382                {
383                    Ok(Literal::NumericBig(plain))
384                }
385                None => s
386                    .parse::<f64>()
387                    .map(Literal::Float)
388                    .map_err(|_| format!("invalid numeric literal {s:?}")),
389            },
390            SciExpanded::Overflow => Err("value overflows numeric format".to_string()),
391            SciExpanded::NotScientific => s
392                .parse::<f64>()
393                .map(Literal::Float)
394                .map_err(|_| format!("invalid numeric literal {s:?}")),
395        },
396    }
397}
398
399fn parse_decimal_literal(s: &str) -> Option<(i128, u16)> {
400    let (int_part, frac_part) = match s.split_once('.') {
401        Some((i, f)) => (i, f),
402        None => (s, ""),
403    };
404    // v7.39 (round 271) — was u8::MAX. A literal with 256 decimal
405    // places fell out of the numeric path here, which is why
406    // `pg_typeof(1e-256)` answered double precision and a plain
407    // 256-place decimal aborted the query in the big-decimal converter.
408    if frac_part.len() > u16::MAX as usize {
409        return None;
410    }
411    let mut digits = String::with_capacity(int_part.len() + frac_part.len());
412    digits.push_str(int_part);
413    digits.push_str(frac_part);
414    let mantissa: i128 = digits.parse().ok()?;
415    #[allow(clippy::cast_possible_truncation)]
416    Some((mantissa, frac_part.len() as u16))
417}
418
419/// `jsonb_to_record` / `jsonb_to_recordset` (+ `json_` variants) — the
420/// record-returning JSON functions that take a `AS alias(col type, …)`
421/// column-definition list in FROM position.
422fn is_json_to_record_name(s: &str) -> bool {
423    s.eq_ignore_ascii_case("jsonb_to_recordset")
424        || s.eq_ignore_ascii_case("jsonb_to_record")
425        // v7.39 (read01 jsonfuncs.c) — the populate family with an AS
426        // column-definition list desugars identically (the record base
427        // argument only carries the type; a non-NULL base's field
428        // defaults are a recorded delta, RD-6).
429        || s.eq_ignore_ascii_case("json_populate_record")
430        || s.eq_ignore_ascii_case("jsonb_populate_record")
431        || s.eq_ignore_ascii_case("json_populate_recordset")
432        || s.eq_ignore_ascii_case("jsonb_populate_recordset")
433        || s.eq_ignore_ascii_case("json_to_recordset")
434        || s.eq_ignore_ascii_case("json_to_record")
435}
436
437impl Parser {
438    /// Whether what follows an identifier ends an index key, which is how
439    /// an operator class is told from anything else in that position.
440    fn opclass_position_follows(next: Option<&Token>) -> bool {
441        match next {
442            // `ASC` / `DESC` have their own tokens; matching them as
443            // identifiers named "asc" / "desc" — which the first version of
444            // this did — never fires, and `(c text_pattern_ops DESC)` (which
445            // PG18.4 accepts, verified) went on failing to parse.
446            Some(Token::Comma | Token::RParen | Token::Asc | Token::Desc) => true,
447            Some(Token::Ident(w)) => {
448                w.eq_ignore_ascii_case("nulls") || w.eq_ignore_ascii_case("collate")
449            }
450            _ => false,
451        }
452    }
453}
454
455fn is_vector_opclass_name(name: &str) -> bool {
456    let lc = name.to_ascii_lowercase();
457    matches!(
458        lc.as_str(),
459        "vector_cosine_ops"
460            | "vector_l2_ops"
461            | "vector_ip_ops"
462            | "halfvec_cosine_ops"
463            | "halfvec_l2_ops"
464            | "halfvec_ip_ops"
465            | "sq8_cosine_ops"
466            | "sq8_l2_ops"
467            | "sq8_ip_ops"
468            // pg_trgm — trigram operator class. SPG's GIN index
469            // already uses tsvector tokens; trigram-style LIKE
470            // pattern matching still routes through a sequential
471            // scan, but the opclass name is accepted so PG schemas
472            // load.
473            | "gin_trgm_ops"
474            | "gist_trgm_ops"
475            // PG built-in btree opclasses occasionally appear in
476            // pg_dump output for column types with multiple
477            // sort orders (text_pattern_ops, varchar_pattern_ops,
478            // bpchar_pattern_ops).
479            | "text_pattern_ops"
480            | "varchar_pattern_ops"
481            | "bpchar_pattern_ops"
482            | "int4_ops"
483            | "int8_ops"
484            | "text_ops"
485    )
486}
487
488#[derive(Debug, Clone, PartialEq, Eq)]
489pub struct ParseError {
490    pub message: String,
491    /// Index into the token stream where parsing tripped. Not a byte offset.
492    /// v7.39 (read01 round 95) — the byte/char position is NOT stored here: a
493    /// field would grow every `Result<_, ParseError>` slot on the deeply
494    /// recursive parse stack and tip the nesting-budget frame cliff. PG's
495    /// 1-based char position is recovered on the cold error path by
496    /// [`syntax_error_position`], which re-tokenizes to map this token index.
497    pub token_pos: usize,
498}
499
500impl fmt::Display for ParseError {
501    /// v7.39 (round 322/V24) — the message ALONE. It used to be prefixed
502    /// with `parse error at token #N: `, which PG has no equivalent of:
503    /// the message bodies are already PG's verbatim (`LIMIT must not be
504    /// negative`, `invalid input syntax for type bigint: "abc"`), and the
505    /// prefix was SPG's internal token index leaking into every one of
506    /// them. `token_pos` stays a field — the wire recovers PG's 1-based
507    /// character position from it for the ErrorResponse `P`.
508    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
509        f.write_str(&self.message)
510    }
511}
512
513impl From<LexError> for ParseError {
514    fn from(e: LexError) -> Self {
515        Self {
516            message: format!("lex: {e}"),
517            token_pos: 0,
518        }
519    }
520}
521
522/// v7.9.30 — parse a single expression (no trailing junk). Used by
523/// the engine to re-hydrate stored partial-index / unique-index
524/// predicates from their canonical Display form. The same Pratt
525/// parser the statement path uses; this entry point just skips the
526/// statement dispatch.
527pub fn parse_expression(input: &str) -> Result<Expr, ParseError> {
528    let (tokens, offsets) = lexer::tokenize_with_offsets(input, lexer::Dialect::PG)
529        .map_err(|e| shape_lex_error(&e, input))?;
530    let mut p = Parser::new(tokens);
531    let expr = p
532        .parse_expr(0)
533        .and_then(|e| p.expect_eof().map(|()| e))
534        .map_err(|e| shape_syntax_error(e, input, &offsets))?;
535    Ok(expr)
536}
537
538/// Parse exactly one statement, swallow an optional trailing `;`, and require
539/// the token stream to end there. PG string semantics.
540pub fn parse_statement(input: &str) -> Result<Statement, ParseError> {
541    parse_statement_with(input, lexer::Dialect::PG)
542}
543
544/// v7.22 (round-13 T3) — dialect-aware entry: `backslash_escapes`
545/// selects MySQL-style string lexing (see `lexer::tokenize_with`).
546/// The engine threads its session flag through here.
547pub fn parse_statement_with(input: &str, dialect: lexer::Dialect) -> Result<Statement, ParseError> {
548    let (tokens, offsets, merges) =
549        lexer::tokenize_with_merges(input, dialect).map_err(|e| shape_lex_error(&e, input))?;
550    // v7.39.2 — the grammar follows "is this MySQL", the lexer follows
551    // "does backslash escape". They used to be one flag, and a session
552    // that turned escapes off lost the grammar with them.
553    let mut p = Parser::new_with_dialect(tokens, dialect.speaks_mysql)
554        .with_source(input, &offsets)
555        .with_merges(merges);
556    let stmt = (|| {
557        let stmt = p.parse_one_statement()?;
558        if matches!(p.peek(), Token::Semicolon) {
559            p.advance();
560        }
561        p.expect_eof()?;
562        Ok(stmt)
563    })()
564    .map_err(|e: ParseError| shape_syntax_error(e, input, &offsets))?;
565    Ok(stmt)
566}
567
568/// v7.39 (round 340, V56) — PG has exactly two syntax-error wordings:
569/// `syntax error at or near "<token>"` and `syntax error at end of input`
570/// (measured on 18.4 across a dozen shapes). SPG wrote its own per-site
571/// prose — `expected identifier, got Eof`, `unexpected token From in
572/// expression`, `expected end of input, got Ident("with")` — which named
573/// internal token types and, in the Debug forms, leaked the parser's own
574/// enum into a message clients read.
575///
576/// Applied once on the way out, so every construction site is covered and
577/// the token named is the one the error itself points at. Messages whose
578/// bodies are already PG's verbatim (`LIMIT must not be negative`,
579/// `invalid input syntax for type bigint: "abc"`) are left alone — those
580/// are PG's own errors, not its syntax error.
581fn shape_syntax_error(e: ParseError, input: &str, offsets: &[usize]) -> ParseError {
582    if !(e.message.starts_with("expected ") || e.message.starts_with("unexpected token ")) {
583        return e;
584    }
585    let message = match offending_lexeme(input, offsets, e.token_pos) {
586        Some(tok) => alloc::format!("syntax error at or near \"{tok}\""),
587        None => "syntax error at end of input".into(),
588    };
589    ParseError {
590        message,
591        token_pos: e.token_pos,
592    }
593}
594
595/// v7.39 (round 340, V56) — a lexer-level failure the way PG words it.
596/// Measured on 18.4: `unterminated quoted string at or near "'abc"`,
597/// `unterminated quoted identifier at or near ""abc"`, `unterminated /*
598/// comment at or near "/* x"` — the quoted part runs from the opening
599/// delimiter to the end of the input. SPG reported its own internal
600/// shape instead (`unterminated string literal at byte 7`), which named
601/// a byte offset no client can use.
602fn shape_lex_error(e: &lexer::LexError, input: &str) -> ParseError {
603    use lexer::LexErrorKind as K;
604    let from_here = input.get(e.pos..).map(str::trim_end).unwrap_or("");
605    let message = match &e.kind {
606        K::UnterminatedString => {
607            alloc::format!("unterminated quoted string at or near \"{from_here}\"")
608        }
609        K::UnterminatedQuotedIdent => {
610            alloc::format!("unterminated quoted identifier at or near \"{from_here}\"")
611        }
612        K::UnterminatedBlockComment => {
613            alloc::format!("unterminated /* comment at or near \"{from_here}\"")
614        }
615        // PG has no "unknown character" error of its own — the character
616        // is skipped and the parser reports the next token. SPG stops at
617        // the character itself and names it, which is the same shape.
618        K::UnknownChar(c) => alloc::format!("syntax error at or near \"{c}\""),
619        // The number-literal kinds already carry PG's `at or near` form.
620        other => alloc::format!(
621            "{}",
622            lexer::LexError {
623                kind: other.clone(),
624                pos: e.pos,
625            }
626        ),
627    };
628    ParseError {
629        message,
630        token_pos: 0,
631    }
632}
633
634/// The offending token exactly as it appears in the input, or `None` at
635/// end of input. PG echoes the source spelling — a lower-case `frm`
636/// reports as `frm`, not as a canonicalised keyword.
637fn offending_lexeme<'a>(input: &'a str, offsets: &[usize], token_pos: usize) -> Option<&'a str> {
638    let start = *offsets.get(token_pos)?;
639    if start >= input.len() {
640        return None;
641    }
642    let end = offsets
643        .get(token_pos + 1)
644        .copied()
645        .unwrap_or(input.len())
646        .min(input.len());
647    let seg = input.get(start..end)?.trim();
648    if seg.is_empty() {
649        return None;
650    }
651    // A quoted literal / identifier keeps its inner spaces; anything else
652    // ends at the first whitespace (the segment runs to the NEXT token's
653    // start, which may swallow a comment).
654    if seg.starts_with('\'') || seg.starts_with('"') || seg.starts_with('`') {
655        Some(seg)
656    } else {
657        seg.split_whitespace().next()
658    }
659}
660
661/// v7.39 (read01 round 95) — recover PG's 1-based CHARACTER error position for
662/// a [`ParseError::token_pos`]. Kept off the `ParseError` struct (and so off
663/// every recursive `Result` slot) to protect the nesting-budget frame cliff:
664/// this re-tokenizes `input` on the cold error path to map the failing token
665/// index to its start byte, then to a character offset. The dialect
666/// must match the parse that produced `token_pos` (it barely shifts offsets,
667/// but stay consistent). Returns `None` when the index has no offset or the
668/// byte isn't a char boundary. The wire attaches it as the ErrorResponse `P`.
669#[must_use]
670pub fn syntax_error_position(
671    input: &str,
672    dialect: lexer::Dialect,
673    token_pos: usize,
674) -> Option<usize> {
675    let (_, offsets) = lexer::tokenize_with_offsets(input, dialect).ok()?;
676    let byte_off = *offsets.get(token_pos)?;
677    if byte_off > input.len() || !input.is_char_boundary(byte_off) {
678        return None;
679    }
680    Some(input[..byte_off].chars().count() + 1)
681}
682
683struct Parser {
684    tokens: Vec<Token>,
685    pos: usize,
686    /// v7.39 (round 274) — the session's dialect, carried by the same
687    /// signal that drives string-literal escaping: `SET sql_mode` (only
688    /// MySQL clients and mysqldump preambles emit it) turns it on,
689    /// `SET standard_conforming_strings` (every pg_dump preamble) turns
690    /// it off. Needed here because the two dialects disagree about what
691    /// `REAL` means — see the type mapping below.
692    mysql_dialect: bool,
693    /// v7.30.2 (mailrs round-25 ask 2) — live nesting depth of the
694    /// mutually recursive expr/select parsers. Bounded so a deeply
695    /// nested input returns a parse error instead of overflowing
696    /// the stack (embed hosts die on overflow — it is an abort,
697    /// not a catchable error).
698    nest_depth: usize,
699    /// TABLESAMPLE lowering channel: the table-ref parser pushes a
700    /// `random() < p/100` predicate here; the enclosing SELECT
701    /// drains the list after its WHERE parses and ANDs the
702    /// predicates in. parse_bare_select save/restores around its
703    /// FROM+WHERE so nested selects only drain their own.
704    pending_sample_preds: Vec<Expr>,
705    /// v7.38.19 — the target of a `SELECT … INTO <table>`, carried out
706    /// of `parse_bare_select` (which returns a `SelectStatement` and has
707    /// nowhere to put it) to the caller that lowers the pair to the CTAS
708    /// node. `bool` is `TEMP`.
709    pending_select_into: Option<(String, bool)>,
710    /// v7.39 (round 691) — collation lowering channel, the same shape as
711    /// `pending_sample_preds` above. `expr COLLATE "name"` is ORDERING
712    /// information, and `ast::OrderBy` is where this parser keeps ordering
713    /// information (`desc`, `nulls_first`); the alternative — a new `Expr`
714    /// variant — puts a new arm on `eval_expr`, which this repo has
715    /// measured to overflow the debug stack. So while an ORDER BY KEY is
716    /// being parsed the postfix loop drops the name here instead of
717    /// refusing it, and the key's parser takes it.
718    ///
719    /// Only inside an ORDER BY key: everywhere else an unperformable
720    /// collation still errors, because accepting one at a COMPARISON and
721    /// ignoring it is the defect F36 exists to close.
722    in_order_by_key: bool,
723    order_key_collation: Option<String>,
724    /// POSITION(sub IN str) — while parsing the needle, the IN
725    /// keyword is the argument separator, not a membership test.
726    /// The postfix loop leaves IN unconsumed when this is set.
727    suppress_in_tail: bool,
728    /// Index of the token the last `advance()` returned — see
729    /// [`Parser::consumed_pos`].
730    last_consumed: usize,
731    /// v7.39 (round 506) — the statement's own text and the byte each token
732    /// starts at, so a MySQL projection item can report the SOURCE TEXT
733    /// MariaDB reports: `SELECT a  +  b` names its column `a  +  b`,
734    /// spacing and all. Only filled for a MySQL session — a PG one names
735    /// columns from the parsed shape and pays nothing for this.
736    src: Option<(String, Vec<usize>)>,
737    /// v7.39.3 — (token index, first-segment byte length) for every
738    /// string literal the lexer built by implicit concatenation.
739    merges: Vec<(usize, usize)>,
740}
741
742/// Max expr/select parser nesting (parens, subqueries, CASE, …).
743/// Real SQL nests a few dozen levels at the extreme. Each nesting level
744/// costs a parse_expr→parse_unary→parse_atom frame chain, so the budget
745/// exists to turn a deep statement into a catchable parse ERROR: a stack
746/// overflow is an abort, and in the server it does not fail one query, it
747/// takes the process down and every other connection with it.
748///
749/// v7.39 (round 507) — measured, because the figure here used to be a
750/// guess ("over 10 KiB in debug … comfortably inside a 2 MiB worker stack
751/// in BOTH debug and release"), and the debug half of that is wrong by
752/// more than an order of magnitude:
753///
754///   * RELEASE, on a 2 MiB worker stack: every recursive shape reaches
755///     this budget and errors. Verified against a live server for nested
756///     derived tables, parens, calls, CASE, IN-subqueries, scalar
757///     subqueries, NOT and unary minus — the server stayed up through all
758///     of them. This is the contract that matters, and it holds.
759///   * DEBUG: nested derived tables cost roughly 235 KiB of stack PER
760///     LEVEL, so parsing alone aborts around 35 levels on an 8 MiB stack
761///     and executing aborts around 8 inside a test thread. The budget is
762///     simply unreachable there, which is why a deep-nesting test has to
763///     ask for a large stack of its own — see `nesting_budget_errors_at`
764///     in the parser tests.
765/// v7.39 (round 541) — the pg_catalog relations SPG synthesises, in
766/// one place.
767///
768/// There were two copies of this fact: a curated list, used for BARE
769/// names, and — in `try_peek_meta_qualified` — no list at all, which
770/// rewrote `pg_catalog.<anything>` to `__spg_pg_<anything>` and left
771/// the engine to complain about a view it could not materialise. So
772/// writing the schema qualifier CHANGED THE ANSWER: `pg_stat_activity`
773/// had rows, `pg_catalog.pg_stat_activity` was an error.
774///
775/// PG puts `pg_catalog` at the implicit front of every search_path, so
776/// the two spellings name the same relation and must resolve the same
777/// way. Names NOT here (`pg_stat_activity`, `pg_locks`,
778/// `pg_stat_statements`, `pg_statio_user_tables`) route through the
779/// meta_view_result path under their own names and must not be
780/// rewritten; a name that is neither reaches the ordinary resolver,
781/// which reports that the relation does not exist — PG's answer.
782const SYNTHESISED_PG_CATALOGS: &[&str] = &[
783    "pg_am",
784    "pg_attrdef",
785    "pg_attribute",
786    "pg_cast",
787    "pg_db_role_setting",
788    "pg_conversion",
789    "pg_default_acl",
790    "pg_shadow",
791    "pg_sequences",
792    "pg_range",
793    "pg_partitioned_table",
794    "pg_language",
795    "pg_group",
796    "pg_authid",
797    "pg_class",
798    "pg_collation",
799    "pg_constraint",
800    "pg_database",
801    "pg_depend",
802    "pg_amop",
803    "pg_amproc",
804    "pg_opclass",
805    "pg_opfamily",
806    // v7.39 (read01 round 50) — COMMENT ON store, PG's pg_description.
807    "pg_description",
808    "pg_enum",
809    "pg_extension",
810    // v7.39 (round 541) — pg_dump reads it for every relation of kind
811    // 'f'. SPG has no foreign tables, so it is empty, which is also
812    // what PG reports on a database that has none.
813    "pg_foreign_table",
814    // v7.39 (round 541) — the empty-by-truth family; see
815    // EMPTY_PG_CATALOGS in spg-engine::system_catalog.
816    "pg_event_trigger",
817    "pg_file_settings",
818    "pg_foreign_data_wrapper",
819    "pg_foreign_server",
820    "pg_hba_file_rules",
821    "pg_ident_file_mappings",
822    "pg_init_privs",
823    "pg_parameter_acl",
824    "pg_prepared_xacts",
825    "pg_publication_namespace",
826    "pg_publication_rel",
827    "pg_publication_tables",
828    "pg_replication_origin",
829    "pg_replication_origin_status",
830    "pg_seclabel",
831    "pg_seclabels",
832    "pg_shdepend",
833    "pg_shdescription",
834    "pg_shmem_allocations",
835    "pg_shmem_allocations_numa",
836    "pg_shseclabel",
837    "pg_statistic_ext_data",
838    "pg_stats_ext",
839    "pg_stats_ext_exprs",
840    "pg_subscription_rel",
841    "pg_transform",
842    "pg_user_mapping",
843    "pg_user_mappings",
844    "pg_index",
845    "pg_indexes",
846    "pg_inherits",
847    // v7.39 (round 650) — the text-search catalogs SPG can fill
848    // honestly. `pg_ts_config_map` is deliberately NOT here: it maps
849    // token types to dictionaries and SPG has no token-type model,
850    // the same gap that leaves `ts_token_type` / `ts_debug` unbuilt.
851    "pg_ts_config",
852    "pg_ts_config_map",
853    "pg_ts_dict",
854    "pg_ts_parser",
855    "pg_ts_template",
856    "pg_matviews",
857    "pg_namespace",
858    // v7.39 (round 621)
859    "pg_operator",
860    "pg_policies",
861    "pg_policy",
862    "pg_proc",
863    "pg_publication",
864    "pg_replication_slots",
865    "pg_roles",
866    // v7.39 (round 143) — the rewrite-rule listing view.
867    // v7.39 (round 312) — and the rule catalogue itself, which
868    // `pg_get_ruledef(oid)` resolves against.
869    "pg_rewrite",
870    "pg_rules",
871    "pg_sequence",
872    "pg_settings",
873    "pg_stat_archiver",
874    "pg_stat_bgwriter",
875    "pg_stat_checkpointer",
876    "pg_stat_database",
877    "pg_stat_io",
878    "pg_stat_progress_analyze",
879    "pg_auth_members",
880    "pg_stat_progress_create_index",
881    "pg_stat_progress_vacuum",
882    "pg_stat_replication",
883    "pg_stat_slru",
884    "pg_stat_subscription_stats",
885    "pg_stat_user_functions",
886    "pg_stat_user_indexes",
887    "pg_stat_user_tables",
888    "pg_stat_wal",
889    "pg_prepared_statements",
890    "pg_largeobject",
891    "pg_largeobject_metadata",
892    "pg_statistic",
893    "pg_statistic_ext",
894    // v7.38.18 — the readable view over pg_statistic.
895    "pg_stats",
896    "pg_subscription",
897    "pg_tables",
898    "pg_tablespace",
899    // v7.39 (round 502) — the timezone catalogues. SPG resolved
900    // named zones correctly but could not list them, so a client
901    // populating a timezone picker got "relation does not exist".
902    "pg_timezone_abbrevs",
903    "pg_timezone_names",
904    "pg_trigger",
905    "pg_type",
906    "pg_user",
907    "pg_views",
908];
909
910const MAX_NEST_DEPTH: usize = 64;
911
912/// Stack accounting for the nesting budget, test-only.
913///
914/// `MAX_NEST_DEPTH` is a fixed count calibrated against a frame size
915/// that MOVES: a compiler upgrade grew the parser's debug frames and
916/// silently ate the margin until `nesting_budget_errors_cleanly` went
917/// from erroring cleanly to aborting on a stack overflow. A count
918/// cannot notice that on its own, so the budget is measured here and
919/// held to a ceiling.
920///
921/// The reading has to come from a helper whose OWN frame is the same at
922/// every call: debug slot placement does not follow source order, so a
923/// local's address inside the function under test is not that
924/// function's frame boundary. Two earlier probes were wrong that way —
925/// one read `&self.nest_depth`, which is the `Parser`'s address and
926/// never moves at all.
927#[cfg(test)]
928mod frame_meter {
929    extern crate std;
930    use std::cell::Cell;
931
932    // Per-THREAD, not global. `cargo test` runs tests in parallel and
933    // plenty of them parse nested expressions, so shared statics get
934    // stack addresses from several threads at once and the subtraction
935    // below turns into noise — it read 229,772 bytes per level that way,
936    // while passing when the test was run on its own.
937    std::thread_local! {
938        static AT_LO: Cell<usize> = const { Cell::new(0) };
939        static AT_HI: Cell<usize> = const { Cell::new(0) };
940    }
941
942    pub(super) const SAMPLE_LO: usize = 4;
943    pub(super) const SAMPLE_HI: usize = 24;
944
945    #[inline(never)]
946    pub(super) fn record(depth: usize) {
947        let anchor = 0u8;
948        let at = core::ptr::from_ref(&anchor) as usize;
949        if depth == SAMPLE_LO {
950            AT_LO.with(|c| c.set(at));
951        } else if depth == SAMPLE_HI {
952            AT_HI.with(|c| c.set(at));
953        }
954    }
955
956    /// Bytes of stack one nesting level costs, averaged over the span.
957    pub(super) fn bytes_per_level() -> usize {
958        let lo = AT_LO.with(Cell::get);
959        let hi = AT_HI.with(Cell::get);
960        assert!(lo > 0 && hi > 0, "meter never sampled: lo={lo} hi={hi}");
961        assert!(lo > hi, "stack grew upwards? lo={lo} hi={hi}");
962        (lo - hi) / (SAMPLE_HI - SAMPLE_LO)
963    }
964
965    pub(super) fn reset() {
966        AT_LO.with(|c| c.set(0));
967        AT_HI.with(|c| c.set(0));
968    }
969}
970
971/// v7.39 (read01 geo_ops.c) — prefix `@@` desugar target, out-of-line so
972/// the constructor's temporaries stay off `parse_unary`'s recursion frame.
973#[inline(never)]
974fn build_center_call(e: Expr) -> Expr {
975    Expr::FunctionCall {
976        name: alloc::string::String::from("center"),
977        args: alloc::vec![e],
978    }
979}
980
981/// Max consecutive binary operators at ONE precedence level
982/// (`a OR b OR c …`, `1+1+1…`). The chain builds iteratively at
983/// parse time but evaluates and drops recursively — depth beyond
984/// this overflows 2 MiB worker stacks (debug eval frames run
985/// multiple KiB). `IN (…)` lists are flat and unaffected.
986const MAX_BINARY_CHAIN: usize = 256;
987
988/// v7.22 (round-13 gap 5) — the kind keyword after `CONSTRAINT
989/// <name>` in a CREATE TABLE column list. FOREIGN KEY is not here:
990/// it keeps its dedicated path (`parse_table_level_fk`).
991enum NamedTableConstraintKind {
992    Check,
993    Unique,
994    PrimaryKey,
995    Exclude,
996}
997
998impl Parser {
999    fn new(tokens: Vec<Token>) -> Self {
1000        Self::new_with_dialect(tokens, false)
1001    }
1002
1003    fn new_with_dialect(tokens: Vec<Token>, mysql_dialect: bool) -> Self {
1004        Self {
1005            tokens,
1006            mysql_dialect,
1007            in_order_by_key: false,
1008            order_key_collation: None,
1009            pos: 0,
1010            nest_depth: 0,
1011            pending_sample_preds: Vec::new(),
1012            pending_select_into: None,
1013            suppress_in_tail: false,
1014            last_consumed: 0,
1015            src: None,
1016            merges: Vec::new(),
1017        }
1018    }
1019
1020    /// Hand the parser the text it is parsing, for [`Parser::source_span`].
1021    fn with_source(mut self, input: &str, offsets: &[usize]) -> Self {
1022        if self.mysql_dialect {
1023            self.src = Some((input.to_string(), offsets.to_vec()));
1024        }
1025        self
1026    }
1027
1028    /// v7.39.3 — the implicit-concatenation log from the lexer, so a
1029    /// merged literal can still be LABELLED by its first segment the way
1030    /// MySQL 9.7.2 labels it.
1031    fn with_merges(mut self, merges: Vec<(usize, usize)>) -> Self {
1032        if self.mysql_dialect {
1033            self.merges = merges;
1034        }
1035        self
1036    }
1037
1038    /// The byte length of the first segment of the literal at `tok`, when
1039    /// that literal was built by implicit concatenation.
1040    fn merged_first_len(&self, tok: usize) -> Option<usize> {
1041        self.merges
1042            .iter()
1043            .find(|(k, _)| *k == tok)
1044            .map(|(_, len)| *len)
1045    }
1046
1047    /// The source text spanning tokens `start ..= end`, trimmed.
1048    ///
1049    /// The offsets are token STARTS, so the span runs to the start of the
1050    /// token after `end` and gives back the whitespace between them —
1051    /// trimming is what makes `a + b FROM t` end at `b`.
1052    fn source_span(&self, start: usize, end: usize) -> Option<&str> {
1053        let (text, offsets) = self.src.as_ref()?;
1054        let from = *offsets.get(start)?;
1055        let to = *offsets.get(end + 1)?;
1056        text.get(from..to).map(str::trim_end)
1057    }
1058
1059    /// v7.30.2 (mailrs round-25 ask 2) — bump the expr/select
1060    /// nesting depth, erroring out cleanly past the budget.
1061    fn enter_nested(&mut self) -> Result<(), ParseError> {
1062        self.nest_depth += 1;
1063        #[cfg(test)]
1064        frame_meter::record(self.nest_depth);
1065        if self.nest_depth > MAX_NEST_DEPTH {
1066            self.nest_depth -= 1;
1067            return Err(self.err(alloc::format!(
1068                "statement nests deeper than {MAX_NEST_DEPTH} levels"
1069            )));
1070        }
1071        Ok(())
1072    }
1073
1074    fn peek(&self) -> &Token {
1075        // tokens always ends with Eof; pos is clamped in advance().
1076        &self.tokens[self.pos]
1077    }
1078
1079    fn advance(&mut self) -> Token {
1080        let t = mem::replace(&mut self.tokens[self.pos], Token::Eof);
1081        self.last_consumed = self.pos;
1082        if self.pos + 1 < self.tokens.len() {
1083            self.pos += 1;
1084        }
1085        t
1086    }
1087
1088    /// v7.39 (round 340, V56) — the index of the token `advance()` just
1089    /// returned. It was computed as `pos - 1`, which is wrong at both
1090    /// ends: `advance()` parks on the final Eof rather than running off
1091    /// the end (so `SELECT * FROM` named `FROM` where PG says `at end of
1092    /// input`), and after backtracking `pos` is no longer one past the
1093    /// token that failed. Recorded by `advance()` itself instead.
1094    const fn consumed_pos(&self) -> usize {
1095        self.last_consumed
1096    }
1097
1098    fn err(&self, message: String) -> ParseError {
1099        ParseError {
1100            message,
1101            token_pos: self.pos,
1102        }
1103    }
1104
1105    /// v7.39.3 — like [`Parser::err`] but pointing at a token the caller
1106    /// names rather than at the current one.
1107    ///
1108    /// The position is not decoration on the MySQL wire: its syntax-error
1109    /// sentence quotes the source from there to the end of the statement,
1110    /// so an error raised after the construct it is about quotes nothing.
1111    fn err_at(&self, token_pos: usize, message: String) -> ParseError {
1112        ParseError { message, token_pos }
1113    }
1114
1115    fn expect_eof(&self) -> Result<(), ParseError> {
1116        if matches!(self.peek(), Token::Eof) {
1117            Ok(())
1118        } else {
1119            Err(self.err(format!("expected end of input, got {:?}", self.peek())))
1120        }
1121    }
1122
1123    /// v7.14.0 — swallow every token up to (but not including) the
1124    /// next semicolon / EOF. Used by the dump-noise dispatcher
1125    /// to consume `COMMENT ON …`, `GRANT …`, `LOCK TABLES …`,
1126    /// etc. without modeling each grammar.
1127    /// v7.39 (read01 round 50) — `COMMENT ON <kind> <name> IS { 'text' | NULL }`.
1128    /// Kinds SPG stores by name: TABLE / COLUMN / INDEX / VIEW / SEQUENCE /
1129    /// SCHEMA / TYPE / DATABASE / FUNCTION. Anything else (and the multi-word
1130    /// `CONSTRAINT c ON t` / `MATERIALIZED VIEW` forms) keeps the old
1131    /// swallow-as-no-op behaviour so a pg_dump tail still loads.
1132    fn parse_comment_on(&mut self) -> Result<Statement, ParseError> {
1133        let start = self.pos;
1134        self.advance(); // COMMENT
1135        if !matches!(self.peek(), Token::On) {
1136            self.pos = start;
1137            self.consume_until_statement_boundary();
1138            return Ok(Statement::Empty);
1139        }
1140        self.advance(); // ON
1141        let kind = match self.peek() {
1142            Token::Ident(s) | Token::QuotedIdent(s) => s.to_ascii_lowercase(),
1143            Token::Table => "table".into(),
1144            _ => {
1145                self.consume_until_statement_boundary();
1146                return Ok(Statement::Empty);
1147            }
1148        };
1149        if !matches!(
1150            kind.as_str(),
1151            "table"
1152                | "column"
1153                | "index"
1154                | "view"
1155                | "sequence"
1156                | "schema"
1157                | "type"
1158                | "database"
1159                | "function"
1160        ) {
1161            self.consume_until_statement_boundary();
1162            return Ok(Statement::Empty);
1163        }
1164        self.advance(); // the kind keyword
1165        // The object name. ⚠️ `expect_ident_like` strips a leading
1166        // `<schema>.` qualifier and returns only the trailing ident (SPG is
1167        // single-schema), which would turn `COMMENT ON COLUMN t.c` into just
1168        // `c`. Read the dotted parts from raw tokens instead, then let a
1169        // 3-part `schema.t.c` drop its leading schema like everywhere else.
1170        let mut parts: alloc::vec::Vec<String> = alloc::vec::Vec::new();
1171        loop {
1172            match self.advance() {
1173                Token::Ident(s) | Token::QuotedIdent(s) => parts.push(s),
1174                other if unreserved_keyword_text(&other).is_some() => {
1175                    parts.push(unreserved_keyword_text(&other).unwrap());
1176                }
1177                other => {
1178                    return Err(ParseError {
1179                        message: alloc::format!("expected identifier, got {other:?}"),
1180                        token_pos: self.consumed_pos(),
1181                    });
1182                }
1183            }
1184            if matches!(self.peek(), Token::Dot) {
1185                self.advance();
1186            } else {
1187                break;
1188            }
1189        }
1190        // COLUMN wants `table.column`; every other kind wants a bare name.
1191        let want = if kind == "column" { 2 } else { 1 };
1192        while parts.len() > want {
1193            parts.remove(0);
1194        }
1195        let name = parts.join(".");
1196        // v7.39 (round 710) — `COMMENT ON FUNCTION f(int, text) IS …`.
1197        // pg_dump writes the SIGNATURE, and the paren list was a syntax
1198        // error here — a dump carrying one function comment failed to
1199        // restore. The list is consumed (the comment store keys by name;
1200        // overload-precise comments are the function-predicate follow-up).
1201        if matches!(self.peek(), Token::LParen)
1202            && matches!(
1203                kind.as_str(),
1204                "function" | "procedure" | "aggregate" | "routine"
1205            )
1206        {
1207            let mut depth = 0usize;
1208            loop {
1209                match self.advance() {
1210                    Token::LParen => depth += 1,
1211                    Token::RParen => {
1212                        depth -= 1;
1213                        if depth == 0 {
1214                            break;
1215                        }
1216                    }
1217                    Token::Eof => {
1218                        return Err(self.err(alloc::string::String::from(
1219                            "unterminated argument list in COMMENT ON",
1220                        )));
1221                    }
1222                    _ => {}
1223                }
1224            }
1225        }
1226        // `IS`
1227        if !matches!(self.peek(), Token::Is) {
1228            self.expect_keyword_ident("is")?;
1229        } else {
1230            self.advance();
1231        }
1232        let comment = match self.peek() {
1233            Token::Null => {
1234                self.advance();
1235                None
1236            }
1237            _ => Some(self.expect_string_literal()?),
1238        };
1239        Ok(Statement::CommentOn {
1240            kind,
1241            name,
1242            comment,
1243        })
1244    }
1245
1246    /// v7.39 (read01 round 57) — `GRANT <privs> ON <obj> TO <roles> [WITH GRANT
1247    /// OPTION]` / `REVOKE [GRANT OPTION FOR] <privs> ON <obj> FROM <roles>
1248    /// [CASCADE|RESTRICT]`.
1249    ///
1250    /// TABLE privileges are the real ones (stored, enforced, introspectable).
1251    /// Every other object class — SCHEMA / SEQUENCE / DATABASE / FUNCTION / …,
1252    /// and the no-ON `GRANT role TO role` membership form — parses into
1253    /// `GrantObject::Other` and no-ops in the engine, so a pg_dump that grants
1254    /// on them still restores.
1255    fn parse_grant_or_revoke(&mut self, grant: bool) -> Result<Statement, ParseError> {
1256        self.advance(); // GRANT / REVOKE
1257        // REVOKE's optional `GRANT OPTION FOR` prefix.
1258        let mut grant_option = false;
1259        if !grant
1260            && self.peek_keyword_ident("grant")
1261            && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("option"))
1262        {
1263            self.advance(); // GRANT
1264            self.advance(); // OPTION
1265            self.expect_keyword_ident("for")?;
1266            grant_option = true;
1267        }
1268        // The privilege list: `ALL [PRIVILEGES] [(cols)]`, or comma-separated
1269        // words each with an optional COLUMN list.
1270        let mut privileges: Vec<GrantPriv> = Vec::new();
1271        if matches!(self.peek(), Token::All) {
1272            self.advance();
1273            if self.peek_keyword_ident("privileges") {
1274                self.advance();
1275            }
1276            // `GRANT ALL (col) ON t TO r` — every column privilege, on that
1277            // column only.
1278            if matches!(self.peek(), Token::LParen) {
1279                let columns = self.parse_grant_column_list()?;
1280                privileges.push(GrantPriv {
1281                    word: "ALL".into(),
1282                    columns,
1283                });
1284            }
1285        } else {
1286            loop {
1287                // SELECT and INSERT lex as reserved tokens, so they never
1288                // reach `expect_ident_like` as plain idents; the rest
1289                // (UPDATE / DELETE / TRUNCATE / REFERENCES / TRIGGER /
1290                // MAINTAIN) are ordinary identifiers.
1291                let w = match self.peek() {
1292                    Token::Select => {
1293                        self.advance();
1294                        "SELECT".to_string()
1295                    }
1296                    Token::Insert => {
1297                        self.advance();
1298                        "INSERT".to_string()
1299                    }
1300                    // v7.39 (read01 round 60) — CREATE is a privilege word on a
1301                    // schema / database, and it lexes as a reserved token.
1302                    Token::Create => {
1303                        self.advance();
1304                        "CREATE".to_string()
1305                    }
1306                    // NOT upper-cased: in the no-ON shape (`GRANT devs TO
1307                    // alice`) these "privilege words" are ROLE NAMES, and a
1308                    // role name is case-sensitive. `priv_from_word` folds case
1309                    // itself when they really are privileges.
1310                    _ => self.expect_ident_like()?,
1311                };
1312                // v7.39 (read01 round 59) — the optional per-privilege COLUMN
1313                // list: `GRANT SELECT (a, b), INSERT (c) ON t TO dan`.
1314                let columns = if matches!(self.peek(), Token::LParen) {
1315                    self.parse_grant_column_list()?
1316                } else {
1317                    Vec::new()
1318                };
1319                privileges.push(GrantPriv { word: w, columns });
1320                if matches!(self.peek(), Token::Comma) {
1321                    self.advance();
1322                } else {
1323                    break;
1324                }
1325            }
1326        }
1327        // v7.39 (read01 round 58) — no ON clause at all = `GRANT devs TO alice`:
1328        // role MEMBERSHIP. The words parsed as "privileges" are the role names.
1329        if !matches!(self.peek(), Token::On) {
1330            let roles: Vec<String> = core::mem::take(&mut privileges)
1331                .into_iter()
1332                .map(|p| p.word)
1333                .collect();
1334            let grantees = self.parse_grantee_list(grant)?;
1335            // `WITH ADMIN OPTION` / `GRANTED BY x` — accepted, ignored (SPG has
1336            // no admin-option layer: a member cannot re-grant).
1337            self.consume_until_statement_boundary();
1338            return Ok(finish_grant(
1339                grant,
1340                GrantStatement {
1341                    privileges: Vec::new(),
1342                    object: GrantObject::Roles(roles),
1343                    grantees,
1344                    grant_option,
1345                },
1346            ));
1347        }
1348        self.advance(); // ON
1349        // An optional object-class keyword. `TABLE` (or no keyword at all) is
1350        // the enforced case; anything else parses and no-ops.
1351        let mut class = "TABLE";
1352        match self.peek() {
1353            Token::Table => {
1354                self.advance();
1355            }
1356            Token::All => {
1357                // v7.39 (read01 round 61) — `ALL TABLES IN SCHEMA x` expands to
1358                // every table at GRANT time, like PG. `ALL SEQUENCES/FUNCTIONS
1359                // IN SCHEMA` stay no-ops and keep their own object class.
1360                self.advance(); // ALL
1361                let kind = match self.peek() {
1362                    Token::Ident(w) | Token::QuotedIdent(w) => w.to_ascii_lowercase(),
1363                    // TABLES has its own token (SHOW TABLES owns it).
1364                    Token::Tables | Token::Table => "tables".to_string(),
1365                    _ => String::new(),
1366                };
1367                if !kind.is_empty() {
1368                    self.advance();
1369                }
1370                // `IN SCHEMA <name>`
1371                if matches!(self.peek(), Token::In) {
1372                    self.advance();
1373                    if self.peek_keyword_ident("schema") {
1374                        self.advance();
1375                        let _schema = self.expect_ident_like()?;
1376                    }
1377                }
1378                if kind != "tables" {
1379                    self.consume_until_statement_boundary();
1380                    return Ok(finish_grant(
1381                        grant,
1382                        GrantStatement {
1383                            privileges,
1384                            object: GrantObject::Other("ALL … IN SCHEMA".into()),
1385                            grantees: Vec::new(),
1386                            grant_option,
1387                        },
1388                    ));
1389                }
1390                let grantees = self.parse_grantee_list(grant)?;
1391                self.consume_until_statement_boundary();
1392                return Ok(finish_grant(
1393                    grant,
1394                    GrantStatement {
1395                        privileges,
1396                        object: GrantObject::AllTablesInSchema,
1397                        grantees,
1398                        grant_option,
1399                    },
1400                ));
1401            }
1402            Token::Ident(w) | Token::QuotedIdent(w) => {
1403                let lc = w.to_ascii_lowercase();
1404                // v7.39 (read01 round 60) — SEQUENCE / SCHEMA / DATABASE are
1405                // real objects with real ACLs now.
1406                if matches!(lc.as_str(), "sequence" | "schema" | "database") {
1407                    self.advance();
1408                    let mut names: Vec<String> = Vec::new();
1409                    loop {
1410                        let mut parts: Vec<String> = Vec::new();
1411                        loop {
1412                            parts.push(self.expect_ident_like()?);
1413                            if matches!(self.peek(), Token::Dot) {
1414                                self.advance();
1415                            } else {
1416                                break;
1417                            }
1418                        }
1419                        names.push(parts.pop().expect("at least one part"));
1420                        if matches!(self.peek(), Token::Comma) {
1421                            self.advance();
1422                        } else {
1423                            break;
1424                        }
1425                    }
1426                    let grantees = self.parse_grantee_list(grant)?;
1427                    let mut grant_option = grant_option;
1428                    if grant && self.peek_keyword_ident("with") {
1429                        self.advance();
1430                        self.expect_keyword_ident("grant")?;
1431                        self.expect_keyword_ident("option")?;
1432                        grant_option = true;
1433                    }
1434                    self.consume_until_statement_boundary();
1435                    let object = match lc.as_str() {
1436                        "sequence" => GrantObject::Sequences(names),
1437                        "schema" => GrantObject::Schemas(names),
1438                        _ => GrantObject::Databases(names),
1439                    };
1440                    return Ok(finish_grant(
1441                        grant,
1442                        GrantStatement {
1443                            privileges,
1444                            object,
1445                            grantees,
1446                            grant_option,
1447                        },
1448                    ));
1449                }
1450                // v7.39 (read01 round 61) — `ON FUNCTION f(int)` is real. SPG
1451                // keys functions by NAME, so the argument list parses and is
1452                // dropped (an overload set shares one ACL — recorded residual).
1453                if matches!(lc.as_str(), "function" | "procedure" | "routine") {
1454                    self.advance();
1455                    let mut names: Vec<(String, Option<Vec<String>>)> = Vec::new();
1456                    loop {
1457                        let mut parts: Vec<String> = Vec::new();
1458                        loop {
1459                            parts.push(self.expect_ident_like()?);
1460                            if matches!(self.peek(), Token::Dot) {
1461                                self.advance();
1462                            } else {
1463                                break;
1464                            }
1465                        }
1466                        let fname = parts.pop().expect("at least one part");
1467                        // v7.39 (read01 round 62) — the signature picks the
1468                        // overload, so it is captured.
1469                        let sig = if matches!(self.peek(), Token::LParen) {
1470                            Some(self.parse_function_signature_types()?)
1471                        } else {
1472                            None
1473                        };
1474                        names.push((fname, sig));
1475                        if matches!(self.peek(), Token::Comma) {
1476                            self.advance();
1477                        } else {
1478                            break;
1479                        }
1480                    }
1481                    let grantees = self.parse_grantee_list(grant)?;
1482                    self.consume_until_statement_boundary();
1483                    return Ok(finish_grant(
1484                        grant,
1485                        GrantStatement {
1486                            privileges,
1487                            object: GrantObject::Functions(names),
1488                            grantees,
1489                            grant_option,
1490                        },
1491                    ));
1492                }
1493                if matches!(
1494                    lc.as_str(),
1495                    "type"
1496                        | "domain"
1497                        | "language"
1498                        | "tablespace"
1499                        | "large"
1500                        | "foreign"
1501                        | "parameter"
1502                ) {
1503                    self.consume_until_statement_boundary();
1504                    return Ok(finish_grant(
1505                        grant,
1506                        GrantStatement {
1507                            privileges,
1508                            object: GrantObject::Other(lc.to_ascii_uppercase()),
1509                            grantees: Vec::new(),
1510                            grant_option,
1511                        },
1512                    ));
1513                }
1514                class = "TABLE";
1515            }
1516            _ => {}
1517        }
1518        let _ = class;
1519        // The table list. Schema-qualified names drop their qualifier (SPG is
1520        // single-schema) — but read the dotted parts from raw tokens, since
1521        // `expect_ident_like` would silently swallow the leading part.
1522        let mut tables: Vec<String> = Vec::new();
1523        loop {
1524            let mut parts: Vec<String> = Vec::new();
1525            loop {
1526                parts.push(self.expect_ident_like()?);
1527                if matches!(self.peek(), Token::Dot) {
1528                    self.advance();
1529                } else {
1530                    break;
1531                }
1532            }
1533            tables.push(parts.pop().expect("at least one part"));
1534            if matches!(self.peek(), Token::Comma) {
1535                self.advance();
1536            } else {
1537                break;
1538            }
1539        }
1540        let grantees = self.parse_grantee_list(grant)?;
1541        if grant && self.peek_keyword_ident("with") {
1542            self.advance();
1543            self.expect_keyword_ident("grant")?;
1544            self.expect_keyword_ident("option")?;
1545            grant_option = true;
1546        }
1547        // REVOKE's trailing CASCADE / RESTRICT — SPG has no dependent grants
1548        // to cascade to (no re-granting), so both are accepted and ignored.
1549        if !grant && (self.peek_keyword_ident("cascade") || self.peek_keyword_ident("restrict")) {
1550            self.advance();
1551        }
1552        Ok(finish_grant(
1553            grant,
1554            GrantStatement {
1555                privileges,
1556                object: GrantObject::Tables(tables),
1557                grantees,
1558                grant_option,
1559            },
1560        ))
1561    }
1562
1563    /// v7.39 (read01 round 62) — the argument TYPES in a function signature:
1564    /// `(int, text)` or `(x int, y text)` (PG accepts either). Returns the type
1565    /// words; the caller normalises them into a signature key.
1566    fn parse_function_signature_types(&mut self) -> Result<Vec<String>, ParseError> {
1567        self.advance(); // (
1568        let mut types: Vec<String> = Vec::new();
1569        if matches!(self.peek(), Token::RParen) {
1570            self.advance();
1571            return Ok(types);
1572        }
1573        loop {
1574            // Collect the words of one argument up to a comma / close paren.
1575            let mut words: Vec<String> = Vec::new();
1576            loop {
1577                match self.peek() {
1578                    Token::Comma | Token::RParen | Token::Eof => break,
1579                    _ => {}
1580                }
1581                let tok = self.advance();
1582                match tok {
1583                    Token::Ident(w) | Token::QuotedIdent(w) => words.push(w),
1584                    other => {
1585                        if let Some(w) = unreserved_keyword_text(&other) {
1586                            words.push(w);
1587                        }
1588                    }
1589                }
1590            }
1591            // `name TYPE` or a bare `TYPE`. Several of PG's type names are
1592            // themselves several words (`double precision`, `character
1593            // varying`, `timestamp with time zone`), so "two words means the
1594            // first is a parameter name" reads the type off `f(double
1595            // precision)` as `precision`. v7.39 (round 282): recognise the
1596            // multi-word spellings first — a leading word that STARTS one of
1597            // them is part of the type, not a name.
1598            let joined = words.join(" ");
1599            let ty = if words.len() >= 2 && is_multiword_type_phrase(&joined) {
1600                joined
1601            } else if words.len() >= 2 {
1602                words[1..].join(" ")
1603            } else {
1604                words.first().cloned().unwrap_or_default()
1605            };
1606            types.push(ty);
1607            if matches!(self.peek(), Token::Comma) {
1608                self.advance();
1609            } else {
1610                break;
1611            }
1612        }
1613        if matches!(self.peek(), Token::RParen) {
1614            self.advance();
1615        }
1616        Ok(types)
1617    }
1618
1619    /// v7.39 (read01 round 59) — `( col, col, … )` after a privilege word.
1620    fn parse_grant_column_list(&mut self) -> Result<Vec<String>, ParseError> {
1621        self.advance(); // (
1622        let mut cols = Vec::new();
1623        loop {
1624            cols.push(self.expect_ident_like()?);
1625            if matches!(self.peek(), Token::Comma) {
1626                self.advance();
1627            } else {
1628                break;
1629            }
1630        }
1631        if !matches!(self.peek(), Token::RParen) {
1632            return Err(self.err(alloc::format!(
1633                "expected ')' to close the column list, got {:?}",
1634                self.peek()
1635            )));
1636        }
1637        self.advance(); // )
1638        Ok(cols)
1639    }
1640
1641    /// `TO <roles>` (grant) / `FROM <roles>` (revoke). An empty-string entry is
1642    /// PUBLIC.
1643    fn parse_grantee_list(&mut self, grant: bool) -> Result<Vec<String>, ParseError> {
1644        if grant {
1645            if matches!(self.peek(), Token::To) {
1646                self.advance();
1647            } else {
1648                self.expect_keyword_ident("to")?;
1649            }
1650        } else if matches!(self.peek(), Token::From) {
1651            self.advance();
1652        } else {
1653            self.expect_keyword_ident("from")?;
1654        }
1655        let mut grantees: Vec<String> = Vec::new();
1656        loop {
1657            // `GROUP name` is the legacy spelling of a plain role name.
1658            if self.peek_keyword_ident("group") {
1659                self.advance();
1660            }
1661            if self.peek_keyword_ident("public") {
1662                self.advance();
1663                grantees.push(String::new()); // PUBLIC
1664            } else {
1665                grantees.push(self.expect_ident_like()?);
1666            }
1667            if matches!(self.peek(), Token::Comma) {
1668                self.advance();
1669            } else {
1670                break;
1671            }
1672        }
1673        Ok(grantees)
1674    }
1675
1676    /// v7.39 (round 277) — `PREPARE <name> [(type, …)] AS <statement>`.
1677    /// The body keeps its `$N` placeholders; substitution happens at
1678    /// EXECUTE. The declared types are recorded for
1679    /// `pg_prepared_statements.parameter_types` but are not enforced —
1680    /// PG infers when the list is omitted, and SPG resolves the values
1681    /// at substitution time either way.
1682    fn parse_prepare(&mut self) -> Result<Statement, ParseError> {
1683        let start = self.pos;
1684        self.advance(); // PREPARE
1685        // v7.39 (round 278) — `PREPARE TRANSACTION '<gid>'` is 2PC, a
1686        // different statement that happens to share the keyword. PG
1687        // ships with `max_prepared_transactions = 0` and reports it
1688        // this way; SPG has no prepared-transaction registry, so the
1689        // same wording is the accurate answer rather than a dodge.
1690        // Round 277 turned this from a silent no-op into a confusing
1691        // "expected AS in PREPARE" parse error.
1692        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("transaction")) {
1693            self.advance();
1694            let gid = match self.advance() {
1695                Token::String(g) => g,
1696                other => {
1697                    return Err(self.err(alloc::format!(
1698                        "expected a transaction identifier after PREPARE TRANSACTION, got {other:?}"
1699                    )));
1700                }
1701            };
1702            return Ok(Statement::PrepareTransaction(gid));
1703        }
1704        let name = self.expect_ident_like()?;
1705        let mut param_types = Vec::new();
1706        if matches!(self.peek(), Token::LParen) {
1707            self.advance();
1708            loop {
1709                let mut ty = self.expect_ident_like()?;
1710                // A parameterised type name (`numeric(10,2)`,
1711                // `varchar(20)`) keeps its argument list in the text.
1712                if matches!(self.peek(), Token::LParen) {
1713                    let mut depth = 0usize;
1714                    let mut buf = String::from("(");
1715                    loop {
1716                        match self.advance() {
1717                            Token::LParen => {
1718                                depth += 1;
1719                                if depth > 1 {
1720                                    buf.push('(');
1721                                }
1722                            }
1723                            Token::RParen => {
1724                                depth -= 1;
1725                                buf.push(')');
1726                                if depth == 0 {
1727                                    break;
1728                                }
1729                            }
1730                            Token::Comma => buf.push(','),
1731                            Token::Integer(n) => buf.push_str(&alloc::format!("{n}")),
1732                            Token::Eof => break,
1733                            _ => {}
1734                        }
1735                    }
1736                    ty.push_str(&buf);
1737                }
1738                // r1049 — `PREPARE p(bigint[]) AS …`: the sixth `[]`
1739                // position, same family as the parameter list above.
1740                let array_suffix = self.consume_array_suffix();
1741                ty.push_str(&array_suffix);
1742                param_types.push(ty);
1743                match self.peek() {
1744                    Token::Comma => {
1745                        self.advance();
1746                    }
1747                    Token::RParen => {
1748                        self.advance();
1749                        break;
1750                    }
1751                    other => {
1752                        return Err(self.err(alloc::format!(
1753                            "expected ',' or ')' in PREPARE parameter list, got {other:?}"
1754                        )));
1755                    }
1756                }
1757            }
1758        }
1759        if !matches!(self.peek(), Token::As) {
1760            return Err(self.err(alloc::format!(
1761                "expected AS in PREPARE, got {:?}",
1762                self.peek()
1763            )));
1764        }
1765        self.advance();
1766        let body = self.parse_one_statement()?;
1767        // The Parser holds tokens, not the source text, so the
1768        // statement PG reports in `pg_prepared_statements.statement`
1769        // is rebuilt from the AST rather than sliced from the input.
1770        let _ = start;
1771        let mut source = alloc::format!("PREPARE {}", crate::ast::quote_ident(&name));
1772        if !param_types.is_empty() {
1773            source.push_str(" (");
1774            source.push_str(&param_types.join(", "));
1775            source.push(')');
1776        }
1777        source.push_str(" AS ");
1778        source.push_str(&alloc::format!("{body}"));
1779        Ok(Statement::Prepare {
1780            name,
1781            param_types,
1782            body: alloc::boxed::Box::new(body),
1783            source,
1784        })
1785    }
1786
1787    /// v7.39 (round 277) — `EXECUTE <name> [(<expr>, …)]`.
1788    fn parse_execute(&mut self) -> Result<Statement, ParseError> {
1789        self.advance(); // EXECUTE
1790        let name = self.expect_ident_like()?;
1791        let mut args = Vec::new();
1792        if matches!(self.peek(), Token::LParen) {
1793            self.advance();
1794            if matches!(self.peek(), Token::RParen) {
1795                self.advance();
1796            } else {
1797                loop {
1798                    args.push(self.parse_expr(0)?);
1799                    match self.advance() {
1800                        Token::Comma => {}
1801                        Token::RParen => break,
1802                        other => {
1803                            return Err(self.err(alloc::format!(
1804                                "expected ',' or ')' in EXECUTE arguments, got {other:?}"
1805                            )));
1806                        }
1807                    }
1808                }
1809            }
1810        }
1811        Ok(Statement::Execute { name, args })
1812    }
1813
1814    /// v7.39 (round 277) — `DEALLOCATE {[PREPARE] <name> | ALL}`.
1815    /// v7.39 (round 278) — `CALL <proc>([args])`. There is no
1816    /// procedure catalog yet, so this reports PG's not-found error
1817    /// (with its HINT) rather than pretending the call ran.
1818    /// v7.39 (round 320, V53) — `DISCARD { ALL | PLANS | SEQUENCES | TEMP }`.
1819    /// Bare `DISCARD` is a syntax error in PG; so it is here.
1820    fn parse_discard(&mut self) -> Result<Statement, ParseError> {
1821        self.advance(); // DISCARD
1822        let target = match self.advance() {
1823            Token::All => DiscardTarget::All,
1824            Token::Ident(w) | Token::QuotedIdent(w) => match w.to_ascii_lowercase().as_str() {
1825                "all" => DiscardTarget::All,
1826                "plans" => DiscardTarget::Plans,
1827                "sequences" => DiscardTarget::Sequences,
1828                "temp" | "temporary" => DiscardTarget::Temp,
1829                other => {
1830                    return Err(self.err(format!(
1831                        "expected ALL / PLANS / SEQUENCES / TEMP after DISCARD, got {other:?}"
1832                    )));
1833                }
1834            },
1835            other => {
1836                return Err(self.err(format!(
1837                    "expected ALL / PLANS / SEQUENCES / TEMP after DISCARD, got {other:?}"
1838                )));
1839            }
1840        };
1841        Ok(Statement::Discard(target))
1842    }
1843
1844    /// v7.39 (round 318, V51) — MySQL `KILL [HARD|SOFT] [CONNECTION|QUERY]
1845    /// <expr>`. MariaDB accepts an expression for the id (its own docs use
1846    /// `KILL connection_id()`), and the HARD / SOFT prefixes only pick how
1847    /// aggressively the server interrupts, which SPG does not distinguish.
1848    /// Bare `KILL <id>` means CONNECTION.
1849    fn parse_kill(&mut self) -> Result<Statement, ParseError> {
1850        self.advance(); // KILL
1851        let mut query_only = false;
1852        loop {
1853            // CONNECTION is a reserved keyword token (it also opens
1854            // `CREATE SUBSCRIPTION … CONNECTION '…'`), so it arrives as
1855            // `Token::Connection` rather than a bare ident.
1856            if matches!(self.peek(), Token::Connection) {
1857                self.advance();
1858                break;
1859            }
1860            let (Token::Ident(w) | Token::QuotedIdent(w)) = self.peek() else {
1861                break;
1862            };
1863            match w.to_ascii_lowercase().as_str() {
1864                "hard" | "soft" => {
1865                    self.advance();
1866                }
1867                "query" => {
1868                    self.advance();
1869                    query_only = true;
1870                    break;
1871                }
1872                _ => break,
1873            }
1874        }
1875        let id = self.parse_expr(0)?;
1876        Ok(Statement::Kill {
1877            query_only,
1878            id: Box::new(id),
1879        })
1880    }
1881
1882    fn parse_call(&mut self) -> Result<Statement, ParseError> {
1883        self.advance(); // CALL
1884        let name = self.expect_ident_like()?;
1885        self.consume_until_statement_boundary();
1886        Ok(Statement::Call(name))
1887    }
1888
1889    fn parse_deallocate(&mut self) -> Result<Statement, ParseError> {
1890        self.advance(); // DEALLOCATE
1891        // PG accepts an optional noise `PREPARE` keyword here.
1892        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("prepare")) {
1893            self.advance();
1894        }
1895        if matches!(self.peek(), Token::All) {
1896            self.advance();
1897            return Ok(Statement::Deallocate(None));
1898        }
1899        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("all")) {
1900            self.advance();
1901            return Ok(Statement::Deallocate(None));
1902        }
1903        let name = self.expect_ident_like()?;
1904        Ok(Statement::Deallocate(Some(name)))
1905    }
1906
1907    fn consume_until_statement_boundary(&mut self) {
1908        loop {
1909            match self.peek() {
1910                Token::Semicolon | Token::Eof => return,
1911                _ => self.advance(),
1912            };
1913        }
1914    }
1915
1916    /// v7.38.19 — the database name a `CREATE DATABASE` names, skipping
1917    /// an `IF NOT EXISTS`. Consumes only the name; the collation scanner
1918    /// runs after it and eats the rest.
1919    fn scan_database_name(&mut self) -> Option<String> {
1920        // The caller has only PEEKED at `DATABASE`; step past it, or the
1921        // first identifier found is the keyword itself. It was, and
1922        // `pg_database` listed a database called `database`.
1923        if matches!(self.peek(), Token::Ident(w) | Token::QuotedIdent(w) if w.eq_ignore_ascii_case("database"))
1924        {
1925            self.advance();
1926        }
1927        for kw in ["if", "not", "exists"] {
1928            if matches!(self.peek(), Token::Ident(w) | Token::QuotedIdent(w) if w.eq_ignore_ascii_case(kw))
1929            {
1930                self.advance();
1931            }
1932        }
1933        match self.peek().clone() {
1934            Token::Ident(w) | Token::QuotedIdent(w) => {
1935                self.advance();
1936                Some(w)
1937            }
1938            _ => None,
1939        }
1940    }
1941
1942    /// v7.38.18 — consume to the statement boundary like
1943    /// `consume_until_statement_boundary`, but pick out the collation a
1944    /// `CREATE DATABASE` asked for on the way.
1945    ///
1946    /// `LC_COLLATE 'de_DE.utf8'` and `LOCALE 'de_DE.utf8'` both count;
1947    /// `LC_CTYPE` does not, because SPG has no separate ctype and
1948    /// pretending to honour it would be the more misleading answer. An
1949    /// `=` between the keyword and the value is optional, as in PG.
1950    ///
1951    /// The whole statement used to be thrown away. Being single-database
1952    /// makes the NAME a no-op; it does not make the collation one.
1953    fn scan_database_collation_until_boundary(&mut self) -> Option<String> {
1954        let mut want_value = false;
1955        let mut found: Option<String> = None;
1956        loop {
1957            let tok = self.peek().clone();
1958            match &tok {
1959                Token::Semicolon | Token::Eof => break,
1960                Token::Ident(w) | Token::QuotedIdent(w)
1961                    if w.eq_ignore_ascii_case("lc_collate") || w.eq_ignore_ascii_case("locale") =>
1962                {
1963                    want_value = true;
1964                }
1965                Token::Eq if want_value => {}
1966                Token::String(v) if want_value => {
1967                    found = Some(v.clone());
1968                    want_value = false;
1969                }
1970                Token::Ident(v) | Token::QuotedIdent(v) if want_value => {
1971                    found = Some(v.clone());
1972                    want_value = false;
1973                }
1974                _ => want_value = false,
1975            }
1976            self.advance();
1977        }
1978        found
1979    }
1980
1981    /// v7.22 (round-13 T2) — consume to the statement boundary like
1982    /// `consume_until_statement_boundary`, but pick out the sequence
1983    /// name on the way: either `SEQUENCE NAME <ident>` (identity
1984    /// columns) or the first string literal (`nextval('<seq>')`).
1985    /// Schema qualifiers and `::regclass` casts are stripped.
1986    fn scan_sequence_name_until_boundary(&mut self) -> Option<String> {
1987        let mut seq: Option<String> = None;
1988        let mut after_sequence_kw = false;
1989        let mut after_name_kw = false;
1990        loop {
1991            match self.peek().clone() {
1992                Token::Semicolon | Token::Eof => break,
1993                Token::Ident(s) | Token::QuotedIdent(s) => {
1994                    if after_name_kw && seq.is_none() {
1995                        self.advance();
1996                        let mut name = s;
1997                        // `SEQUENCE NAME public.groups_id_seq` — keep
1998                        // the bare name, drop qualifiers.
1999                        while matches!(self.peek(), Token::Dot) {
2000                            self.advance();
2001                            if let Token::Ident(n) | Token::QuotedIdent(n) = self.advance() {
2002                                name = n;
2003                            }
2004                        }
2005                        seq = Some(name);
2006                        after_name_kw = false;
2007                        continue;
2008                    }
2009                    if after_sequence_kw && s.eq_ignore_ascii_case("name") {
2010                        after_name_kw = true;
2011                        after_sequence_kw = false;
2012                    } else {
2013                        after_sequence_kw = s.eq_ignore_ascii_case("sequence");
2014                    }
2015                    self.advance();
2016                }
2017                Token::String(s) => {
2018                    if seq.is_none() {
2019                        // `nextval('public.groups_id_seq'::regclass)`
2020                        let bare = s
2021                            .rsplit_once('.')
2022                            .map_or_else(|| s.clone(), |(_, b)| b.to_string());
2023                        seq = Some(bare);
2024                    }
2025                    self.advance();
2026                }
2027                _ => {
2028                    after_sequence_kw = false;
2029                    after_name_kw = false;
2030                    self.advance();
2031                }
2032            }
2033        }
2034        seq
2035    }
2036
2037    /// v7.39 (round 621) — is the next token the keyword `BY`?
2038    ///
2039    /// `pg_get_keywords()` classes `by` as `U` (unreserved), so it is a legal
2040    /// column, table and alias name — and SPG lexed it into a dedicated
2041    /// `Token::By`, which made it unusable as a name ANYWHERE. Of the seven
2042    /// two-letter keywords the lexer knew, this was the only one PG leaves
2043    /// unreserved (`as`, `in`, `on`, `or`, `to` are reserved and `is` is `T`).
2044    ///
2045    /// The token is gone; the three clauses that own the word — GROUP BY,
2046    /// ORDER BY, PARTITION BY — and the handful of other places that expect it
2047    /// ask this instead. Adding it to the unreserved-identifier table was not
2048    /// enough on its own: identifier positions that match the token shape
2049    /// directly (an index's column list, a table alias) never consult that
2050    /// table, so `CREATE INDEX … ON t(by)` and `FROM t AS by` still failed.
2051    /// Not lexing it as a keyword closes the whole class rather than the two
2052    /// positions that happened to be noticed.
2053    fn peek_is_by(&self) -> bool {
2054        matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("by"))
2055    }
2056
2057    /// v7.39 (round 621) — the optional `CASCADE` / `RESTRICT` trailer a DROP
2058    /// takes. Accepted and dropped: SPG tracks no dependents to cascade to,
2059    /// which is what `DROP TABLE` and `DROP INDEX` have done since v7.14.
2060    fn consume_drop_behaviour(&mut self) {
2061        if matches!(
2062            self.peek(),
2063            Token::Ident(s) if s.eq_ignore_ascii_case("cascade") || s.eq_ignore_ascii_case("restrict")
2064        ) {
2065            self.advance();
2066        }
2067    }
2068
2069    fn expect_ident_like(&mut self) -> Result<String, ParseError> {
2070        let first = match self.advance() {
2071            Token::Ident(s) | Token::QuotedIdent(s) => s,
2072            // v7.37.43-T4 — PG-unreserved keywords are legal identifiers
2073            // per PG's `pg_get_keywords()` classification. SPG tokenizes
2074            // these as named variants for parsing leverage in the
2075            // contexts that own them (`RELEASE SAVEPOINT`, `SHOW name`,
2076            // `BEGIN`, etc.), but they MUST still be usable as table /
2077            // column / alias names in DDL+DML. Sentori migrations like
2078            // 0001_init.sql ship `release TEXT NOT NULL` in the events
2079            // table — the `events.release` column carries the release
2080            // identifier string. Pre-T4 this triggered "expected
2081            // identifier, got Release" and blocked every drop-in user
2082            // whose schema had a column / alias with one of these names.
2083            other if unreserved_keyword_text(&other).is_some() => {
2084                unreserved_keyword_text(&other).unwrap()
2085            }
2086            other => {
2087                return Err(ParseError {
2088                    message: format!("expected identifier, got {other:?}"),
2089                    token_pos: self.consumed_pos(),
2090                });
2091            }
2092        };
2093        // v7.14.0 — strip optional `<schema>.` prefix. PG dumps
2094        // qualify every name with `public.` (and pg_catalog.* for
2095        // functions); SPG is single-schema so we discard the
2096        // prefix and return only the trailing ident. Same shape
2097        // also handles MySQL `db.tbl` cross-database refs (SPG
2098        // ignores the db part).
2099        if matches!(self.peek(), Token::Dot) {
2100            self.advance();
2101            match self.advance() {
2102                Token::Ident(s) | Token::QuotedIdent(s) => return Ok(s),
2103                other if unreserved_keyword_text(&other).is_some() => {
2104                    return Ok(unreserved_keyword_text(&other).unwrap());
2105                }
2106                other => {
2107                    return Err(ParseError {
2108                        message: format!("expected identifier after '{first}.', got {other:?}"),
2109                        token_pos: self.consumed_pos(),
2110                    });
2111                }
2112            }
2113        }
2114        Ok(first)
2115    }
2116
2117    #[allow(clippy::too_many_lines)]
2118    fn parse_one_statement(&mut self) -> Result<Statement, ParseError> {
2119        // v7.14.0 — empty / comment-only / semicolon-only input
2120        // (after the lexer strips line + block + MySQL
2121        // conditional comments) lands as Statement::Empty.
2122        // pg_dump and mysqldump emit several wrappers that
2123        // collapse to nothing after stripping (`/*!40101 SET …
2124        // */;`, blank lines between statements); the engine
2125        // returns CommandOk no-op so the dump loads cleanly.
2126        if matches!(self.peek(), Token::Eof | Token::Semicolon) {
2127            return Ok(Statement::Empty);
2128        }
2129        // v7.14.0 — pg_dump / mysqldump "noise" statements:
2130        // catalog / metadata DDL that has no behavioural effect
2131        // on SPG's single-schema, single-database, single-user
2132        // model. Consume the whole statement up to the next
2133        // semicolon / EOF and return Empty. This is broader than
2134        // the per-keyword DROP / SET / COMMENT arms but lets the
2135        // long tail of `LOCK TABLES`, `UNLOCK TABLES`, `GRANT`,
2136        // `REVOKE`, `ALTER OWNER TO`, `\restrict`, `\unrestrict`,
2137        // `BEGIN; COMMIT;` wrappers, etc. all pass through.
2138        if let Token::Ident(s) | Token::QuotedIdent(s) = self.peek() {
2139            let lc = s.to_ascii_lowercase();
2140            // v7.39 (read01 round 50) — COMMENT ON is a real statement now.
2141            if lc == "comment" {
2142                return self.parse_comment_on();
2143            }
2144            // v7.39 (read01 round 57) — so is GRANT / REVOKE.
2145            if lc == "grant" || lc == "revoke" {
2146                return self.parse_grant_or_revoke(lc == "grant");
2147            }
2148            // v7.39 (round 277) — the SQL-level prepared-statement
2149            // surface is REAL now. It used to be accepted and dropped
2150            // on the theory that "real execution still happens via the
2151            // extended-query flow" — true only for a driver that uses
2152            // that flow; a plain SQL PREPARE / EXECUTE returned no
2153            // rows at all.
2154            if lc == "prepare" {
2155                return self.parse_prepare();
2156            }
2157            if lc == "execute" {
2158                return self.parse_execute();
2159            }
2160            if lc == "deallocate" {
2161                return self.parse_deallocate();
2162            }
2163            // v7.39 (round 278) — `CALL <proc>(<args>)` used to be
2164            // accepted and dropped, so an application's stored-procedure
2165            // invocation reported success and did nothing. SPG has no
2166            // procedure catalog, so every CALL names a procedure that
2167            // does not exist — which is exactly what PG says.
2168            if lc == "call" {
2169                return self.parse_call();
2170            }
2171            // v7.39 (round 318, V51) — MySQL `KILL`. Not dump noise: it
2172            // names one connection and acts on it.
2173            if lc == "kill" {
2174                return self.parse_kill();
2175            }
2176            if lc == "discard" {
2177                return self.parse_discard();
2178            }
2179            // v7.39 (round 696) — REASSIGN OWNED BY <role> [, …] TO <role>.
2180            // Still performs nothing; the roles are carried out so a name
2181            // that does not exist is refused, as PG18 refuses it.
2182            if lc == "reassign" {
2183                self.advance();
2184                if matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("owned")) {
2185                    self.advance();
2186                }
2187                if self.peek_is_by() {
2188                    self.advance();
2189                }
2190                // Only the roles BEFORE the TO are the ones that must
2191                // exist — `TO` names the new owner, which PG checks as
2192                // well, so both lists are collected.
2193                let mut names = self.take_comma_separated_names();
2194                if matches!(self.peek(), Token::To) {
2195                    self.advance();
2196                    names.extend(self.take_comma_separated_names());
2197                }
2198                self.consume_until_statement_boundary();
2199                return Ok(Statement::ValidateOnly {
2200                    kind: crate::ast::ValidateOnlyKind::RoleName,
2201                    names,
2202                });
2203            }
2204            // v7.39 (round 696) — SECURITY LABEL. PG18 refuses it
2205            // unconditionally with `no security label providers have been
2206            // loaded`, whatever object it names, because none is loaded.
2207            // SPG has none either; accepting it told the caller a label had
2208            // been applied when nothing anywhere records one.
2209            if lc == "security" {
2210                self.consume_until_statement_boundary();
2211                return Ok(Statement::ValidateOnly {
2212                    kind: crate::ast::ValidateOnlyKind::SecurityLabel,
2213                    names: Vec::new(),
2214                });
2215            }
2216            // v7.39.2 — `USE <db>` is a real statement now, and only in
2217            // the MySQL dialect. It used to be swallowed here with the
2218            // dump noise, so `USE myapp; SELECT DATABASE()` answered the
2219            // same constant it answered before — MySQL 9.7.2 answers
2220            // `myapp`. PostgreSQL has no USE at all, and pg_dump does not
2221            // emit one, but the swallow stays on that side: it was put
2222            // there for restores and taking it away is not this defect.
2223            if lc == "use" {
2224                if self.mysql_dialect {
2225                    self.advance();
2226                    let name = self.expect_ident_like()?;
2227                    return Ok(Statement::UseDatabase(name));
2228                }
2229                self.consume_until_statement_boundary();
2230                return Ok(Statement::Empty);
2231            }
2232            if is_dump_noise_statement(&lc) {
2233                self.consume_until_statement_boundary();
2234                return Ok(Statement::Empty);
2235            }
2236        }
2237        match self.peek() {
2238            Token::Select => self.parse_select_stmt(),
2239            // v7.37.17 (17.6 siblings) — a statement opening with a
2240            // parenthesized query group: `(SELECT … UNION …)
2241            // INTERSECT …`. parse_bare_select's group arm consumes
2242            // the parens; the select parser handles the outer chain
2243            // and tail.
2244            Token::LParen
2245                if matches!(
2246                    self.tokens.get(self.pos + 1),
2247                    Some(Token::Select | Token::LParen | Token::Values)
2248                ) =>
2249            {
2250                self.parse_select_stmt()
2251            }
2252            // v7.37.17 (17.6 siblings) — top-level bare VALUES
2253            // statement (`VALUES (1), (2) [ORDER BY …] [LIMIT …]`).
2254            // Lowers to the same UNION ALL chain the FROM-position
2255            // form uses, then reuses the shared SELECT tail.
2256            Token::Values => {
2257                self.advance(); // VALUES
2258                let mut head = self.parse_values_rows_body()?;
2259                self.parse_select_tail_into(&mut head)?;
2260                Ok(Statement::Select(head))
2261            }
2262            // SQL-standard `TABLE name` shorthand for
2263            // `SELECT * FROM name` — pg_dump never emits it, but
2264            // psql users and PG docs use it constantly. Set-op
2265            // chains and the ORDER BY/LIMIT tail compose like any
2266            // SELECT head.
2267            Token::Table
2268                if matches!(
2269                    self.tokens.get(self.pos + 1),
2270                    Some(Token::Ident(_) | Token::QuotedIdent(_))
2271                ) =>
2272            {
2273                let mut head = self.parse_table_shorthand()?;
2274                self.parse_setop_chain_into(&mut head)?;
2275                self.parse_select_tail_into(&mut head)?;
2276                Ok(Statement::Select(head))
2277            }
2278            // v7.9.27 — `DO $$ … $$ [LANGUAGE plpgsql]`. The
2279            // body is a dollar-quoted plpgsql block (lexer already
2280            // collapsed `$$…$$` into a single Token::String).
2281            // v7.16.2 — mailrs round-10 A.2: parse the body as a
2282            // real PlPgSqlBlock so the engine can EXECUTE it at
2283            // top level instead of silently swallowing. Pre-
2284            // v7.16.2 the parser threw the body away and the
2285            // engine returned CommandOk for the entire DO; that
2286            // turned `DO BEGIN … IF EXISTS ... THEN ALTER …; END
2287            // $$` into a SEV-1 silent no-op (the IF + the rename
2288            // were both invisible — mailrs's migrate-042 didn't
2289            // actually run). Now the body parses + executes;
2290            // EmbeddedSql inside the block runs immediately
2291            // against the engine (not deferred — we're at top
2292            // level, not inside a trigger row-write loop).
2293            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("do") => {
2294                self.advance();
2295                let body_text = match self.advance() {
2296                    Token::String(s) => s,
2297                    other => {
2298                        return Err(self.err(alloc::format!(
2299                            "expected dollar-quoted body after DO, got {other:?}"
2300                        )));
2301                    }
2302                };
2303                // Optional `LANGUAGE <name>` trailer (idents only).
2304                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("language")) {
2305                    self.advance();
2306                    let _ = self.expect_ident_like()?;
2307                }
2308                // Parse the body — same shape CREATE FUNCTION
2309                // uses for trigger function bodies. If the body
2310                // doesn't parse cleanly we surface the error
2311                // (better than silent no-op).
2312                let block = parse_plpgsql_body(&body_text)?;
2313                Ok(Statement::DoBlock(block))
2314            }
2315            // v4.11: `WITH name AS (SELECT ...) [, ...] SELECT ...`.
2316            // WITH isn't a reserved token in our lexer — comes through
2317            // as `Token::Ident("with")` (case-insensitive).
2318            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("with") => {
2319                self.advance();
2320                self.parse_with_cte_then_select()
2321            }
2322            // v4.26: `EXPLAIN [ANALYZE] <select>`. Comes through as
2323            // an identifier — not a reserved keyword.
2324            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("explain") => {
2325                self.advance();
2326                let mut analyze = false;
2327                let mut suggest = false;
2328                let mut costs_off = false;
2329                let mut buffers = false;
2330                let mut timing_off = false;
2331                let mut settings = false;
2332                let mut wal = false;
2333                let mut summary_off = false;
2334                let mut format = crate::ast::ExplainFormat::Text;
2335                // v6.8.3 + v7.37.7 — `EXPLAIN (option [, option…])`
2336                // syntax accepts SUGGEST + COSTS ON|OFF. Multiple
2337                // options are comma-separated. Booleans default to ON
2338                // when the value token is omitted (matches PG).
2339                if matches!(self.peek(), Token::LParen) {
2340                    self.advance();
2341                    loop {
2342                        let opt = match self.peek().clone() {
2343                            Token::Ident(s) | Token::QuotedIdent(s) => s,
2344                            other => {
2345                                return Err(self.err(format!(
2346                                    "expected option keyword inside EXPLAIN (…), got {other:?}"
2347                                )));
2348                            }
2349                        };
2350                        self.advance();
2351                        if opt.eq_ignore_ascii_case("suggest") {
2352                            suggest = true;
2353                            // SUGGEST takes no explicit value today.
2354                        } else if opt.eq_ignore_ascii_case("costs") {
2355                            // PG syntax: `COSTS [ON | OFF]`. Default
2356                            // when value omitted is ON, so plain
2357                            // `COSTS` is a no-op. `COSTS OFF` flips.
2358                            // `ON` lexes to `Token::On` (reserved
2359                            // keyword in JOIN ... ON contexts); accept
2360                            // it alongside the bare Ident form so the
2361                            // grammar matches PG verbatim.
2362                            let value = match self.peek().clone() {
2363                                Token::On => {
2364                                    self.advance();
2365                                    true
2366                                }
2367                                Token::Ident(v) | Token::QuotedIdent(v)
2368                                    if v.eq_ignore_ascii_case("off") =>
2369                                {
2370                                    self.advance();
2371                                    false
2372                                }
2373                                Token::Ident(v) | Token::QuotedIdent(v)
2374                                    if v.eq_ignore_ascii_case("true") =>
2375                                {
2376                                    self.advance();
2377                                    true
2378                                }
2379                                _ => true,
2380                            };
2381                            costs_off = !value;
2382                        } else if opt.eq_ignore_ascii_case("analyze")
2383                            || opt.eq_ignore_ascii_case("analyse")
2384                        {
2385                            // v7.37.22 — `EXPLAIN (ANALYZE [ON|OFF]) <S>`.
2386                            // Same default-ON rule as ANALYZE keyword form.
2387                            let value = match self.peek().clone() {
2388                                Token::On => {
2389                                    self.advance();
2390                                    true
2391                                }
2392                                Token::Ident(v) | Token::QuotedIdent(v)
2393                                    if v.eq_ignore_ascii_case("off") =>
2394                                {
2395                                    self.advance();
2396                                    false
2397                                }
2398                                Token::Ident(v) | Token::QuotedIdent(v)
2399                                    if v.eq_ignore_ascii_case("true") =>
2400                                {
2401                                    self.advance();
2402                                    true
2403                                }
2404                                _ => true,
2405                            };
2406                            analyze = value;
2407                        } else if opt.eq_ignore_ascii_case("buffers") {
2408                            // v7.37.22 — `BUFFERS [ON|OFF]`.
2409                            let value = match self.peek().clone() {
2410                                Token::On => {
2411                                    self.advance();
2412                                    true
2413                                }
2414                                Token::Ident(v) | Token::QuotedIdent(v)
2415                                    if v.eq_ignore_ascii_case("off") =>
2416                                {
2417                                    self.advance();
2418                                    false
2419                                }
2420                                Token::Ident(v) | Token::QuotedIdent(v)
2421                                    if v.eq_ignore_ascii_case("true") =>
2422                                {
2423                                    self.advance();
2424                                    true
2425                                }
2426                                _ => true,
2427                            };
2428                            buffers = value;
2429                        } else if opt.eq_ignore_ascii_case("timing") {
2430                            // v7.37.22 — `TIMING [ON|OFF]`. OFF strips
2431                            // the measured wall-clock annotation.
2432                            let value = match self.peek().clone() {
2433                                Token::On => {
2434                                    self.advance();
2435                                    true
2436                                }
2437                                Token::Ident(v) | Token::QuotedIdent(v)
2438                                    if v.eq_ignore_ascii_case("off") =>
2439                                {
2440                                    self.advance();
2441                                    false
2442                                }
2443                                Token::Ident(v) | Token::QuotedIdent(v)
2444                                    if v.eq_ignore_ascii_case("true") =>
2445                                {
2446                                    self.advance();
2447                                    true
2448                                }
2449                                _ => true,
2450                            };
2451                            timing_off = !value;
2452                        } else if opt.eq_ignore_ascii_case("settings") {
2453                            settings = true;
2454                        } else if opt.eq_ignore_ascii_case("wal") {
2455                            wal = true;
2456                        } else if opt.eq_ignore_ascii_case("summary") {
2457                            // v7.39 (round 227) — `SUMMARY [ON|OFF]` really
2458                            // gates the trailing Planning/Execution Time
2459                            // lines now (was accept-and-no-op).
2460                            let value = match self.peek().clone() {
2461                                Token::On => {
2462                                    self.advance();
2463                                    true
2464                                }
2465                                Token::Ident(v) | Token::QuotedIdent(v)
2466                                    if v.eq_ignore_ascii_case("off") =>
2467                                {
2468                                    self.advance();
2469                                    false
2470                                }
2471                                Token::Ident(v) | Token::QuotedIdent(v)
2472                                    if v.eq_ignore_ascii_case("true") =>
2473                                {
2474                                    self.advance();
2475                                    true
2476                                }
2477                                _ => true,
2478                            };
2479                            summary_off = !value;
2480                        } else if opt.eq_ignore_ascii_case("verbose")
2481                            || opt.eq_ignore_ascii_case("format")
2482                        {
2483                            // v7.37.22 — accept-but-no-op the remaining
2484                            // PG options so EXPLAIN-using clients
2485                            // (pgAdmin / DataGrip) don't see syntax
2486                            // errors. FORMAT takes a value (text /
2487                            // json / yaml / xml); skip the next token
2488                            // if it's an ident.
2489                            if opt.eq_ignore_ascii_case("format") {
2490                                if let Token::Ident(v) | Token::QuotedIdent(v) = self.peek().clone()
2491                                {
2492                                    self.advance();
2493                                    format = match v.to_ascii_lowercase().as_str() {
2494                                        "text" => crate::ast::ExplainFormat::Text,
2495                                        "json" => crate::ast::ExplainFormat::Json,
2496                                        "xml" => crate::ast::ExplainFormat::Xml,
2497                                        "yaml" => crate::ast::ExplainFormat::Yaml,
2498                                        other => {
2499                                            return Err(self.err(format!(
2500                                                "EXPLAIN (FORMAT …): unknown format {other:?}; \
2501                                                 supports text, json, xml, yaml"
2502                                            )));
2503                                        }
2504                                    };
2505                                }
2506                            } else {
2507                                // VERBOSE / SUMMARY take optional ON/OFF;
2508                                // consume if present.
2509                                if matches!(self.peek(), Token::On) {
2510                                    self.advance();
2511                                } else if let Token::Ident(v) | Token::QuotedIdent(v) =
2512                                    self.peek().clone()
2513                                    && (v.eq_ignore_ascii_case("off")
2514                                        || v.eq_ignore_ascii_case("true"))
2515                                {
2516                                    self.advance();
2517                                    let _ = v;
2518                                }
2519                            }
2520                        } else {
2521                            return Err(self.err(format!(
2522                                "unknown EXPLAIN option {opt:?}; supports ANALYZE, COSTS, BUFFERS, TIMING, SETTINGS, WAL, SUGGEST, VERBOSE, FORMAT, SUMMARY"
2523                            )));
2524                        }
2525                        if matches!(self.peek(), Token::Comma) {
2526                            self.advance();
2527                            continue;
2528                        }
2529                        break;
2530                    }
2531                    if !matches!(self.peek(), Token::RParen) {
2532                        return Err(self.err(format!(
2533                            "expected ')' after EXPLAIN options, got {:?}",
2534                            self.peek()
2535                        )));
2536                    }
2537                    self.advance();
2538                } else if let Token::Ident(s) | Token::QuotedIdent(s) = self.peek()
2539                    && (s.eq_ignore_ascii_case("analyze") || s.eq_ignore_ascii_case("analyse"))
2540                {
2541                    self.advance();
2542                    analyze = true;
2543                }
2544                // v7.39 (round 224) — the body may open with WITH (CTEs);
2545                // route through the same CTE-then-SELECT path the top-level
2546                // WITH statement uses. v7.39 (round 225) — DML bodies parse
2547                // too (PG explains INSERT / UPDATE / DELETE).
2548                let inner = match self.peek().clone() {
2549                    Token::Ident(s) if s.eq_ignore_ascii_case("with") => {
2550                        self.advance();
2551                        self.parse_with_cte_then_select()?
2552                    }
2553                    Token::Insert => self.parse_insert_stmt(false)?,
2554                    Token::Ident(s) if s.eq_ignore_ascii_case("update") => {
2555                        self.advance();
2556                        self.parse_update_after_keyword()?
2557                    }
2558                    Token::Ident(s) if s.eq_ignore_ascii_case("delete") => {
2559                        self.advance();
2560                        self.parse_delete_after_keyword()?
2561                    }
2562                    _ => self.parse_select_stmt()?,
2563                };
2564                if !matches!(
2565                    inner,
2566                    Statement::Select(_)
2567                        | Statement::Insert(_)
2568                        | Statement::Update(_)
2569                        | Statement::Delete(_)
2570                ) {
2571                    return Err(self.err(format!(
2572                        "EXPLAIN body must be SELECT / INSERT / UPDATE / DELETE, got {inner:?}"
2573                    )));
2574                }
2575                Ok(Statement::Explain(crate::ast::ExplainStatement {
2576                    analyze,
2577                    inner: Box::new(inner),
2578                    suggest,
2579                    costs_off,
2580                    buffers,
2581                    timing_off,
2582                    settings,
2583                    wal,
2584                    summary_off,
2585                    format,
2586                }))
2587            }
2588            Token::Create => self.parse_create_stmt(),
2589            Token::Insert => self.parse_insert_stmt(false),
2590            // MySQL `DESCRIBE t` / `DESC t` — the SHOW COLUMNS
2591            // spelling; route to the same handler. DESC is the
2592            // reserved ORDER BY token, so it gets its own arm.
2593            Token::Ident(s)
2594                if s.eq_ignore_ascii_case("describe")
2595                    && matches!(
2596                        self.tokens.get(self.pos + 1),
2597                        Some(Token::Ident(_) | Token::QuotedIdent(_))
2598                    ) =>
2599            {
2600                self.advance();
2601                let table = self.expect_ident_like()?;
2602                Ok(Statement::ShowColumns(table))
2603            }
2604            Token::Desc
2605                if matches!(
2606                    self.tokens.get(self.pos + 1),
2607                    Some(Token::Ident(_) | Token::QuotedIdent(_))
2608                ) =>
2609            {
2610                self.advance();
2611                let table = self.expect_ident_like()?;
2612                Ok(Statement::ShowColumns(table))
2613            }
2614            // `COPY table [(cols)] TO STDOUT` — the export half of
2615            // pg_dump's COPY pair (the FROM stdin half rides the
2616            // embed import path). Options need a format design and
2617            // error honestly.
2618            Token::Ident(s)
2619                if s.eq_ignore_ascii_case("copy")
2620                    && matches!(
2621                        self.tokens.get(self.pos + 1),
2622                        Some(Token::Ident(_) | Token::QuotedIdent(_))
2623                    ) =>
2624            {
2625                self.advance(); // COPY
2626                let table = self.expect_ident_like()?;
2627                let columns = if matches!(self.peek(), Token::LParen) {
2628                    self.advance();
2629                    let mut cols = alloc::vec![self.expect_ident_like()?];
2630                    while matches!(self.peek(), Token::Comma) {
2631                        self.advance();
2632                        cols.push(self.expect_ident_like()?);
2633                    }
2634                    if !matches!(self.peek(), Token::RParen) {
2635                        return Err(self.err(format!(
2636                            "expected ')' after COPY column list, got {:?}",
2637                            self.peek()
2638                        )));
2639                    }
2640                    self.advance();
2641                    Some(cols)
2642                } else {
2643                    None
2644                };
2645                // v7.39 (round 249) — `COPY t FROM '<path>'`: the file
2646                // endpoint. (FROM STDIN still rides the wire/import path —
2647                // its data arrives out of band.)
2648                if matches!(self.peek(), Token::From)
2649                    && matches!(self.tokens.get(self.pos + 1), Some(Token::String(_)))
2650                {
2651                    self.advance(); // FROM
2652                    let Token::String(path) = self.advance() else {
2653                        unreachable!()
2654                    };
2655                    let options = self.parse_copy_to_options()?;
2656                    return Ok(Statement::CopyFromFile {
2657                        table,
2658                        columns,
2659                        path,
2660                        options,
2661                    });
2662                }
2663                if !matches!(self.peek(), Token::To) {
2664                    return Err(self.err(format!(
2665                        "COPY: only TO STDOUT is supported here (FROM stdin \
2666                         rides the import path); got {:?}",
2667                        self.peek()
2668                    )));
2669                }
2670                self.advance();
2671                if matches!(self.peek(), Token::String(_)) {
2672                    let Token::String(path) = self.advance() else { unreachable!() };
2673                    let options = self.parse_copy_to_options()?;
2674                    return Ok(Statement::CopyToFile {
2675                        table,
2676                        columns,
2677                        query: None,
2678                        path,
2679                        options,
2680                    });
2681                }
2682                if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("stdout")) {
2683                    return Err(self.err(format!(
2684                        "COPY TO supports STDOUT only (no file endpoints), got {:?}",
2685                        self.peek()
2686                    )));
2687                }
2688                self.advance();
2689                let options = self.parse_copy_to_options()?;
2690                Ok(Statement::CopyTo {
2691                    table,
2692                    columns,
2693                    query: None,
2694                    options,
2695                })
2696            }
2697            // v7.39 (read01 round 94) — `COPY (<query>) TO STDOUT [WITH (…)]`.
2698            // The parens directly after COPY wrap a SELECT/VALUES/CTE whose
2699            // result set is streamed in COPY format (PG's query form).
2700            Token::Ident(s)
2701                if s.eq_ignore_ascii_case("copy")
2702                    && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen)) =>
2703            {
2704                self.advance(); // COPY
2705                self.advance(); // (
2706                let query = self.parse_select_stmt()?;
2707                if !matches!(self.peek(), Token::RParen) {
2708                    return Err(self.err(format!(
2709                        "expected ')' after COPY query, got {:?}",
2710                        self.peek()
2711                    )));
2712                }
2713                self.advance(); // )
2714                if !matches!(self.peek(), Token::To) {
2715                    return Err(self.err(format!(
2716                        "COPY (query): only TO STDOUT is supported, got {:?}",
2717                        self.peek()
2718                    )));
2719                }
2720                self.advance();
2721                if matches!(self.peek(), Token::String(_)) {
2722                    let Token::String(path) = self.advance() else { unreachable!() };
2723                    let options = self.parse_copy_to_options()?;
2724                    return Ok(Statement::CopyToFile {
2725                        table: String::new(),
2726                        columns: None,
2727                        query: Some(alloc::boxed::Box::new(query)),
2728                        path,
2729                        options,
2730                    });
2731                }
2732                if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("stdout")) {
2733                    return Err(self.err(format!(
2734                        "COPY (query): TO supports STDOUT only, got {:?}",
2735                        self.peek()
2736                    )));
2737                }
2738                self.advance();
2739                let options = self.parse_copy_to_options()?;
2740                Ok(Statement::CopyTo {
2741                    table: String::new(),
2742                    columns: None,
2743                    query: Some(alloc::boxed::Box::new(query)),
2744                    options,
2745                })
2746            }
2747            // MySQL `REPLACE INTO t …` — delete-then-insert upsert.
2748            // Shares the INSERT body; the replace flag lowers it
2749            // onto ON CONFLICT DO UPDATE with an empty assignment
2750            // list (engine: replace the whole row).
2751            Token::Ident(s)
2752                if s.eq_ignore_ascii_case("replace")
2753                    && matches!(self.tokens.get(self.pos + 1), Some(Token::Into)) =>
2754            {
2755                self.parse_insert_stmt(true)
2756            }
2757            Token::Begin => {
2758                self.advance();
2759                // v7.38 轴 4 / v7.39 (read01 round 118, B3) — PG-standard
2760                // `BEGIN [WORK|TRANSACTION] [ISOLATION LEVEL …] [READ ONLY|WRITE]
2761                // [[NOT] DEFERRABLE]`. The optional WORK/TRANSACTION noise word
2762                // is consumed first, then the trailing modes — including the
2763                // case where `ISOLATION LEVEL …` follows BEGIN directly (no
2764                // WORK/TRANSACTION). The explicit level, when present, rides the
2765                // statement so `exec_begin` applies it for this transaction.
2766                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("work") || s.eq_ignore_ascii_case("transaction"))
2767                {
2768                    self.advance();
2769                }
2770                let iso = self.parse_isolation_level_clauses()?;
2771                Ok(Statement::Begin(iso))
2772            }
2773            // v7.38 轴 4 — PG-standard `START TRANSACTION …` synonym
2774            // for BEGIN. START is contextual in PG too; pattern-match
2775            // on the ident here. Iso clauses are parse-and-ignored,
2776            // same as BEGIN above.
2777            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("start") => {
2778                self.advance();
2779                if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("transaction"))
2780                {
2781                    return Err(self.err(alloc::format!(
2782                        "expected TRANSACTION after START, got {:?}",
2783                        self.peek()
2784                    )));
2785                }
2786                self.advance();
2787                let iso = self.parse_isolation_level_clauses()?;
2788                Ok(Statement::Begin(iso))
2789            }
2790            Token::Commit => {
2791                self.advance();
2792                // PG: `COMMIT [WORK | TRANSACTION]`.
2793                if let Token::Ident(w) = self.peek()
2794                    && (w.eq_ignore_ascii_case("work") || w.eq_ignore_ascii_case("transaction"))
2795                {
2796                    self.advance();
2797                }
2798                Ok(Statement::Commit)
2799            }
2800            // r1066 (7.38 S5.1) — `END [WORK | TRANSACTION]` is PG's
2801            // COMMIT synonym; pgbench's builtin tpcb-like script closes
2802            // every transaction with `END;` and the drop-in aborted on
2803            // it. Only reachable at statement start (CASE … END lives
2804            // inside expressions), so no ambiguity.
2805            Token::Ident(s) if s.eq_ignore_ascii_case("end") => {
2806                self.advance();
2807                if let Token::Ident(w) = self.peek()
2808                    && (w.eq_ignore_ascii_case("work") || w.eq_ignore_ascii_case("transaction"))
2809                {
2810                    self.advance();
2811                }
2812                Ok(Statement::Commit)
2813            }
2814            Token::Rollback => {
2815                self.advance();
2816                // `ROLLBACK TO [SAVEPOINT] <name>` returns to that
2817                // savepoint without ending the transaction. Bare
2818                // `ROLLBACK` drops the whole TX.
2819                if matches!(self.peek(), Token::To) {
2820                    self.advance();
2821                    if matches!(self.peek(), Token::Savepoint) {
2822                        self.advance();
2823                    }
2824                    let name = self.expect_ident_like()?;
2825                    Ok(Statement::RollbackToSavepoint(name))
2826                } else {
2827                    Ok(Statement::Rollback)
2828                }
2829            }
2830            Token::Savepoint => {
2831                self.advance();
2832                let name = self.expect_ident_like()?;
2833                Ok(Statement::Savepoint(name))
2834            }
2835            Token::Release => {
2836                self.advance();
2837                // `RELEASE [SAVEPOINT] <name>` — the `SAVEPOINT` keyword
2838                // is optional in standard SQL.
2839                if matches!(self.peek(), Token::Savepoint) {
2840                    self.advance();
2841                }
2842                let name = self.expect_ident_like()?;
2843                Ok(Statement::ReleaseSavepoint(name))
2844            }
2845            Token::Show => {
2846                self.advance();
2847                // `SHOW TABLES` / `SHOW USERS` / `SHOW COLUMNS FROM <table>`.
2848                // v6.1.2 promoted TABLES to a reserved keyword (for
2849                // `CREATE PUBLICATION … FOR ALL TABLES`), so it now
2850                // arrives as `Token::Tables` rather than a bare ident.
2851                // USERS / COLUMNS remain bare idents.
2852                let target = match self.advance() {
2853                    Token::Tables => "tables".to_string(),
2854                    // v7.17.0 Phase 3.P0-59 — CREATE is a reserved
2855                    // keyword token; recognise it as the SHOW CREATE
2856                    // dispatch keyword too.
2857                    Token::Create => "create".to_string(),
2858                    // v7.17.0 Phase 3.P0-60 — INDEX is a reserved
2859                    // keyword too; let SHOW INDEX FROM parse.
2860                    Token::Index => "index".to_string(),
2861                    // v7.37.17 (17.6 sibling) — SHOW ALL. ALL is
2862                    // reserved (used in aggregate function calls);
2863                    // recognise it here so the parser dispatches
2864                    // to ShowParameter("all") — the engine returns
2865                    // the curated parameter inventory.
2866                    Token::All => "all".to_string(),
2867                    // v7.38.18 (C12) — `SHOW COUNT(*) WARNINGS`, MySQL's
2868                    // spelling for the size of the diagnostics area.
2869                    // MySQL-dialect only: PostgreSQL 18.4 answers this
2870                    // phrase with `syntax error at or near "("`, and a
2871                    // PG session must keep getting exactly that rather
2872                    // than a message about an unknown parameter.
2873                    // `COUNT` arrives as a bare ident; the `(*)` and the
2874                    // trailing keyword are consumed here so the whole
2875                    // form reaches the engine as one parameter name.
2876                    Token::Ident(ref c)
2877                        if self.mysql_dialect
2878                            && c.eq_ignore_ascii_case("count")
2879                            && matches!(self.peek(), Token::LParen) =>
2880                    {
2881                        self.advance();
2882                        if matches!(self.peek(), Token::Star) {
2883                            self.advance();
2884                        }
2885                        if matches!(self.peek(), Token::RParen) {
2886                            self.advance();
2887                        }
2888                        match self.advance() {
2889                            Token::Ident(w) if w.eq_ignore_ascii_case("warnings") => {
2890                                return Ok(Statement::ShowParameter(
2891                                    "count(*) warnings".to_string(),
2892                                ));
2893                            }
2894                            other => {
2895                                return Err(self.err(format!(
2896                                    "expected WARNINGS after SHOW COUNT(*), got {other:?}"
2897                                )));
2898                            }
2899                        }
2900                    }
2901                    Token::Ident(s) | Token::QuotedIdent(s) => s.to_ascii_lowercase(),
2902                    other => {
2903                        return Err(self.err(format!(
2904                            "expected SHOW target, got {other:?}"
2905                        )));
2906                    }
2907                };
2908                match target.as_str() {
2909                    "tables" => Ok(Statement::ShowTables),
2910                    "users" => Ok(Statement::ShowUsers),
2911                    // v7.38 轴 4 — `SHOW transaction_isolation`
2912                    // returns the currently-selected isolation level.
2913                    "transaction_isolation" => Ok(Statement::ShowParameter(
2914                        "transaction_isolation".to_string(),
2915                    )),
2916                    // v7.17.0 Phase 3.P0-59 — MySQL `SHOW CREATE
2917                    // TABLE <t>` returns a 2-column row: (Table,
2918                    // Create Table). mysqldump emits this for every
2919                    // table at scrape time; without it the dump
2920                    // round-trip stalls.
2921                    // v7.17.0 Phase 3.P0-60 — MySQL `SHOW INDEXES
2922                    // FROM <t>` (also spelled `SHOW INDEX` and
2923                    // `SHOW KEYS`). admin / mysqldump probes use
2924                    // it to list per-table indexes.
2925                    "indexes" | "index" | "keys" => {
2926                        if !matches!(self.peek(), Token::From) {
2927                            return Err(self.err(format!(
2928                                "expected FROM after SHOW INDEXES, got {:?}",
2929                                self.peek()
2930                            )));
2931                        }
2932                        self.advance();
2933                        let table = self.expect_ident_like()?;
2934                        Ok(Statement::ShowIndexes(table))
2935                    }
2936                    // v7.17.0 Phase 3.P0-61 — MySQL `SHOW STATUS` /
2937                    // `SHOW VARIABLES`. Both return a 2-column row
2938                    // set listing server-side state; clients probe
2939                    // them at connect time.
2940                    "status" => Ok(Statement::ShowStatus),
2941                    "variables" => {
2942                        // r1067 — `SHOW VARIABLES LIKE 'pat'`.
2943                        if matches!(self.peek(), Token::Like) {
2944                            self.advance();
2945                            let pat = match self.advance() {
2946                                Token::String(p) => p,
2947                                other => {
2948                                    return Err(self.err(format!(
2949                                        "SHOW VARIABLES LIKE expects a quoted pattern, got {other:?}"
2950                                    )));
2951                                }
2952                            };
2953                            return Ok(Statement::ShowVariablesLike(pat));
2954                        }
2955                        Ok(Statement::ShowVariables)
2956                    }
2957                    // v7.17.0 Phase 3.P0-62 — MySQL `SHOW PROCESSLIST`.
2958                    "processlist" => Ok(Statement::ShowProcesslist),
2959                    "create" => {
2960                        // SHOW CREATE TABLE / VIEW / DATABASE — only
2961                        // TABLE is supported in v7.17.
2962                        let kind = match self.advance() {
2963                            Token::Ident(s) | Token::QuotedIdent(s) => s,
2964                            Token::Table => "table".to_string(),
2965                            other => {
2966                                return Err(self.err(format!(
2967                                    "expected TABLE after SHOW CREATE, got {other:?}"
2968                                )));
2969                            }
2970                        };
2971                        if !kind.eq_ignore_ascii_case("table") {
2972                            return Err(self.err(format!(
2973                                "unsupported SHOW CREATE {kind:?}; v7.17 supports TABLE only"
2974                            )));
2975                        }
2976                        let name = self.expect_ident_like()?;
2977                        Ok(Statement::ShowCreateTable(name))
2978                    }
2979                    // v7.17.0 Phase 3.P0-58 — MySQL `SHOW DATABASES`
2980                    // (and `SHOW SCHEMAS` alias). The mysql client uses
2981                    // it to populate the database selector at connect
2982                    // time; without it `mysql -p` errors before the
2983                    // first user query.
2984                    "databases" | "schemas" => Ok(Statement::ShowDatabases),
2985                    // v6.1.3 — PUBLICATIONS plural is NOT a reserved
2986                    // keyword on its own; it lands here as a bare
2987                    // ident. Returning all publications + their
2988                    // scope summary.
2989                    "publications" => Ok(Statement::ShowPublications),
2990                    // v6.1.4 — same shape for SUBSCRIPTIONS plural.
2991                    "subscriptions" => Ok(Statement::ShowSubscriptions),
2992                    "columns" => {
2993                        if !matches!(self.peek(), Token::From) {
2994                            return Err(self.err(format!(
2995                                "expected FROM after SHOW COLUMNS, got {:?}",
2996                                self.peek()
2997                            )));
2998                        }
2999                        self.advance();
3000                        let table = self.expect_ident_like()?;
3001                        Ok(Statement::ShowColumns(table))
3002                    }
3003                    // v7.38 轴 4 surface — `SHOW <param>` for any
3004                    // remaining session / preset parameter name
3005                    // (server_version, search_path, client_encoding,
3006                    // …). The engine's ShowParameter handler does the
3007                    // dispatch; unrecognised names error there with
3008                    // a pointer to pg_settings, not at parse time —
3009                    // so a driver that issues `SHOW spam_setting`
3010                    // gets a clear runtime error instead of a
3011                    // confusing "unknown SHOW target".
3012                    other => {
3013                        // v7.38 (read01 P3.20) — a custom namespaced GUC
3014                        // (`SHOW app.foo`) arrives as `app` + `.` + `foo`;
3015                        // consume the dotted tail so it round-trips with
3016                        // `SET app.foo` / `current_setting('app.foo')`.
3017                        let mut full = other.to_string();
3018                        while matches!(self.peek(), Token::Dot) {
3019                            self.advance();
3020                            let seg = self.expect_ident_like()?;
3021                            full.push('.');
3022                            full.push_str(&seg.to_ascii_lowercase());
3023                        }
3024                        Ok(Statement::ShowParameter(full))
3025                    }
3026                }
3027            }
3028            // v6.1.2: `DROP` is now a reserved keyword (it dispatches
3029            // to DROP USER and DROP PUBLICATION today; DROP TABLE /
3030            // DROP INDEX are still SHOW-shaped admin ops). Pre-6.1.2
3031            // arrived as a bare ident; tokenising it dedicatedly
3032            // keeps the dispatch tree small.
3033            Token::Drop => {
3034                self.advance();
3035                match self.peek() {
3036                    // v7.37.17 (17.6 sibling) — DROP OWNED BY <role>
3037                    // [, ...] [CASCADE | RESTRICT]. pg_dumpall emits
3038                    // around DROP ROLE cleanup. SPG has no role-owner
3039                    // model, so consume to boundary as a no-op.
3040                    Token::Ident(s) | Token::QuotedIdent(s)
3041                        if s.eq_ignore_ascii_case("owned") =>
3042                    {
3043                        // v7.39 (round 696) — still a no-op (SPG has no
3044                        // role-owner model), but the ROLE is carried out so
3045                        // the engine can refuse one that does not exist,
3046                        // which is what PG18 does.
3047                        self.advance();
3048                        if self.peek_is_by() {
3049                            self.advance();
3050                        }
3051                        let names = self.take_comma_separated_names();
3052                        self.consume_until_statement_boundary();
3053                        Ok(Statement::ValidateOnly {
3054                            kind: crate::ast::ValidateOnlyKind::RoleName,
3055                            names,
3056                        })
3057                    }
3058                    // v7.39 (round 436) — MySQL's `DROP TEMPORARY TABLE t`.
3059                    // It drops only a TEMPORARY table, and name resolution
3060                    // already prefers the session's own, so the keyword is
3061                    // consumed and the ordinary DROP TABLE path runs.
3062                    Token::Ident(s) | Token::QuotedIdent(s)
3063                        if s.eq_ignore_ascii_case("temporary") || s.eq_ignore_ascii_case("temp") =>
3064                    {
3065                        self.advance();
3066                        if !matches!(self.peek(), Token::Table) {
3067                            return Err(self.err(alloc::format!(
3068                                "expected TABLE after DROP TEMPORARY, got {:?}",
3069                                self.peek()
3070                            )));
3071                        }
3072                        self.parse_drop_table_after_keyword()
3073                    }
3074                    Token::Publication => {
3075                        self.advance();
3076                        // v7.39 (round 754, F31-B4) — the round-753
3077                        // audit probe tripped over the missing
3078                        // `IF EXISTS` here (syntax error).
3079                        let if_exists = self.consume_if_exists();
3080                        let name = self.expect_ident_or_string()?;
3081                        Ok(Statement::DropPublication { name, if_exists })
3082                    }
3083                    Token::Subscription => {
3084                        self.advance();
3085                        let if_exists = self.consume_if_exists();
3086                        let name = self.expect_ident_or_string()?;
3087                        Ok(Statement::DropSubscription { name, if_exists })
3088                    }
3089                    Token::Ident(s) | Token::QuotedIdent(s)
3090                        if s.eq_ignore_ascii_case("user") || s.eq_ignore_ascii_case("role") =>
3091                    {
3092                        self.advance();
3093                        // v7.39 (read01 round 58) — DROP ROLE is DROP USER: a
3094                        // login user IS a role in PG, and SPG's store holds
3095                        // both. `IF EXISTS` is accepted on either spelling.
3096                        let if_exists = self.consume_if_exists();
3097                        let name = self.expect_ident_or_string()?;
3098                        Ok(Statement::DropUser { name, if_exists })
3099                    }
3100                    // v7.39 (round 806) — DROP DATABASE [IF EXISTS] <name>.
3101                    // CREATE DATABASE has parsed since v7.14 and this did
3102                    // not, so `DROP DATABASE IF EXISTS x` — what every
3103                    // teardown script and pg_dumpall preamble opens with —
3104                    // came back as a syntax error, which IF EXISTS cannot
3105                    // soften. The name is carried so the engine can answer
3106                    // the way PG does; PG never lets this succeed on a
3107                    // single-database server, since the name is either
3108                    // unknown ("database … does not exist", or a notice
3109                    // under IF EXISTS) or the one you are connected to
3110                    // ("cannot drop the currently open database").
3111                    Token::Ident(s) | Token::QuotedIdent(s)
3112                        if s.eq_ignore_ascii_case("database") =>
3113                    {
3114                        self.advance();
3115                        let if_exists = self.consume_if_exists();
3116                        let name = self.expect_ident_or_string()?;
3117                        self.consume_until_statement_boundary();
3118                        Ok(Statement::DropDatabase { name, if_exists })
3119                    }
3120                    // v7.12.4 — DROP TRIGGER [IF EXISTS] name ON table.
3121                    Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("trigger") => {
3122                        self.advance();
3123                        let if_exists = self.consume_if_exists();
3124                        let name = self.expect_ident_like()?;
3125                        // ON <table>
3126                        if !matches!(self.peek(), Token::On) {
3127                            return Err(self.err(alloc::format!(
3128                                "expected ON <table> after DROP TRIGGER {name:?}, got {:?}",
3129                                self.peek()
3130                            )));
3131                        }
3132                        self.advance();
3133                        let table = self.expect_ident_like()?;
3134                        Ok(Statement::DropTrigger {
3135                            name,
3136                            table,
3137                            if_exists,
3138                        })
3139                    }
3140                    // v7.39 (round 139) — DROP RULE [IF EXISTS] name ON table
3141                    // [CASCADE|RESTRICT]. Mirrors DROP TRIGGER's shape.
3142                    Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("rule") => {
3143                        self.advance();
3144                        let if_exists = self.consume_if_exists();
3145                        let name = self.expect_ident_like()?;
3146                        if !matches!(self.peek(), Token::On) {
3147                            return Err(self.err(alloc::format!(
3148                                "expected ON <table> after DROP RULE {name:?}, got {:?}",
3149                                self.peek()
3150                            )));
3151                        }
3152                        self.advance();
3153                        let table = self.expect_ident_like()?;
3154                        // Optional CASCADE / RESTRICT — accepted, no effect.
3155                        self.consume_until_statement_boundary();
3156                        Ok(Statement::DropRule {
3157                            name,
3158                            table,
3159                            if_exists,
3160                        })
3161                    }
3162                    // v7.12.4 — DROP FUNCTION [IF EXISTS] name [(args)].
3163                    // v7.12.4 ignores any optional arg-list (signature-
3164                    // based overload disambiguation lands in v7.12.5+).
3165                    Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("function") => {
3166                        self.advance();
3167                        let if_exists = self.consume_if_exists();
3168                        let name = self.expect_ident_like()?;
3169                        // v7.39 (read01 round 62) — the argument list identifies
3170                        // WHICH overload to drop, so it is captured, not
3171                        // discarded. `DROP FUNCTION f` (no list) is legal when
3172                        // the name is unambiguous; the engine enforces that.
3173                        let args = if matches!(self.peek(), Token::LParen) {
3174                            Some(self.parse_function_signature_types()?)
3175                        } else {
3176                            None
3177                        };
3178                        // v7.39 (round 621) — the `CASCADE` / `RESTRICT`
3179                        // trailer, which `DROP TABLE` and `DROP INDEX` have
3180                        // accepted since v7.14 and this one refused outright.
3181                        // pg_dump writes it, so refusing was a parse error in
3182                        // the middle of a restore. SPG drops the function
3183                        // either way — it tracks no dependents to cascade to —
3184                        // which is the same reading the other two give it.
3185                        self.consume_drop_behaviour();
3186                        Ok(Statement::DropFunction {
3187                            name,
3188                            args,
3189                            if_exists,
3190                        })
3191                    }
3192                    // v7.14.0 — DROP TABLE [IF EXISTS] name [, name…]
3193                    // [CASCADE|RESTRICT]. pg_dump and mysqldump both
3194                    // emit DROP TABLE IF EXISTS at the head of every
3195                    // CREATE TABLE block so re-importing a dump
3196                    // overwrites prior state. SPG accepts and removes
3197                    // matching tables; CASCADE/RESTRICT trailers
3198                    // accepted silently.
3199                    Token::Table => self.parse_drop_table_after_keyword(),
3200                    // v7.14.0 — DROP INDEX [IF EXISTS] name
3201                    // [CASCADE|RESTRICT]. PG / mysqldump emit this
3202                    // for partial-index renames and pgvector
3203                    // migrations. SPG removes the matching index;
3204                    // IF EXISTS makes the drop idempotent.
3205                    Token::Index => {
3206                        self.advance();
3207                        let if_exists_at = self.pos;
3208                        let if_exists = self.consume_if_exists();
3209                        let name = self.expect_ident_like()?;
3210                        // v7.39.7 — MySQL's own spelling, which SPG
3211                        // refused.
3212                        //
3213                        // `DROP INDEX i ON t` is how MySQL drops an
3214                        // index; its names live inside a table, so the
3215                        // statement names the table. Measured against
3216                        // MySQL 9.7.2: the form above works, and the
3217                        // bare `DROP INDEX i` PostgreSQL uses is a 1064
3218                        // there. SPG had it exactly backwards on the
3219                        // MySQL wire — the bare form accepted, MySQL's
3220                        // own a syntax error — so a migration that drops
3221                        // an index failed against the drop-in and not
3222                        // against the thing it replaces.
3223                        let table = if matches!(self.peek(), Token::On) {
3224                            self.advance();
3225                            Some(self.expect_ident_like()?)
3226                        } else {
3227                            None
3228                        };
3229                        if self.mysql_dialect {
3230                            // MySQL has no `IF EXISTS` here either:
3231                            // `DROP INDEX IF EXISTS i ON t` is a 1064.
3232                            if if_exists {
3233                                return Err(self.err_at(
3234                                    if_exists_at,
3235                                    "MySQL has no IF EXISTS on DROP INDEX".into(),
3236                                ));
3237                            }
3238                            if table.is_none() {
3239                                return Err(self.err("expected ON after the index name".into()));
3240                            }
3241                        }
3242                        if matches!(
3243                            self.peek(),
3244                            Token::Ident(s) if s.eq_ignore_ascii_case("cascade")
3245                                || s.eq_ignore_ascii_case("restrict")
3246                        ) {
3247                            self.advance();
3248                        }
3249                        Ok(Statement::DropIndex {
3250                            name,
3251                            if_exists,
3252                            table,
3253                        })
3254                    }
3255                    // v7.14.0 — DROP SCHEMA [IF EXISTS] name
3256                    // [CASCADE|RESTRICT]. SPG is single-database;
3257                    // v7.17.0 Phase 1.6 — DROP SCHEMA [IF EXISTS]
3258                    // name [, name…] [CASCADE | RESTRICT]. Real
3259                    // unregister (was silent no-op pre-v7.17).
3260                    Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("schema") => {
3261                        self.advance();
3262                        let if_exists = self.consume_if_exists();
3263                        let mut names = vec![self.expect_ident_like()?];
3264                        while matches!(self.peek(), Token::Comma) {
3265                            self.advance();
3266                            names.push(self.expect_ident_like()?);
3267                        }
3268                        if matches!(
3269                            self.peek(),
3270                            Token::Ident(s) if s.eq_ignore_ascii_case("cascade")
3271                                || s.eq_ignore_ascii_case("restrict")
3272                        ) {
3273                            self.advance();
3274                        }
3275                        Ok(Statement::DropSchema { names, if_exists })
3276                    }
3277                    // v7.17.0 Phase 1.4 — DROP TYPE [IF EXISTS]
3278                    // name [, name…] [CASCADE|RESTRICT].
3279                    Token::Ident(s) | Token::QuotedIdent(s)
3280                        if s.eq_ignore_ascii_case("type") =>
3281                    {
3282                        self.advance();
3283                        let if_exists = self.consume_if_exists();
3284                        let mut names = vec![self.expect_ident_like()?];
3285                        while matches!(self.peek(), Token::Comma) {
3286                            self.advance();
3287                            names.push(self.expect_ident_like()?);
3288                        }
3289                        if matches!(
3290                            self.peek(),
3291                            Token::Ident(s) if s.eq_ignore_ascii_case("cascade")
3292                                || s.eq_ignore_ascii_case("restrict")
3293                        ) {
3294                            self.advance();
3295                        }
3296                        Ok(Statement::DropType { names, if_exists })
3297                    }
3298                    // v7.17.0 Phase 1.5 — DROP DOMAIN [IF EXISTS]
3299                    // name [, name…] [CASCADE|RESTRICT].
3300                    Token::Ident(s) | Token::QuotedIdent(s)
3301                        if s.eq_ignore_ascii_case("domain") =>
3302                    {
3303                        self.advance();
3304                        let if_exists = self.consume_if_exists();
3305                        let mut names = vec![self.expect_ident_like()?];
3306                        while matches!(self.peek(), Token::Comma) {
3307                            self.advance();
3308                            names.push(self.expect_ident_like()?);
3309                        }
3310                        if matches!(
3311                            self.peek(),
3312                            Token::Ident(s) if s.eq_ignore_ascii_case("cascade")
3313                                || s.eq_ignore_ascii_case("restrict")
3314                        ) {
3315                            self.advance();
3316                        }
3317                        Ok(Statement::DropDomain { names, if_exists })
3318                    }
3319                    // v7.17.0 Phase 1.3 — DROP MATERIALIZED VIEW
3320                    // [IF EXISTS] name [, name…] [CASCADE|RESTRICT].
3321                    Token::Ident(s) | Token::QuotedIdent(s)
3322                        if s.eq_ignore_ascii_case("materialized") =>
3323                    {
3324                        self.advance();
3325                        let nxt = self.peek().clone();
3326                        if !matches!(&nxt, Token::Ident(s2) | Token::QuotedIdent(s2) if s2.eq_ignore_ascii_case("view"))
3327                        {
3328                            return Err(self.err(alloc::format!(
3329                                "expected VIEW after DROP MATERIALIZED, got {nxt:?}"
3330                            )));
3331                        }
3332                        self.advance();
3333                        let if_exists = self.consume_if_exists();
3334                        let mut names = vec![self.expect_ident_like()?];
3335                        while matches!(self.peek(), Token::Comma) {
3336                            self.advance();
3337                            names.push(self.expect_ident_like()?);
3338                        }
3339                        if matches!(
3340                            self.peek(),
3341                            Token::Ident(s) if s.eq_ignore_ascii_case("cascade")
3342                                || s.eq_ignore_ascii_case("restrict")
3343                        ) {
3344                            self.advance();
3345                        }
3346                        Ok(Statement::DropMaterializedView { names, if_exists })
3347                    }
3348                    // v7.17.0 Phase 1.2 — DROP VIEW [IF EXISTS]
3349                    // name [, name…] [CASCADE|RESTRICT].
3350                    Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("view") => {
3351                        self.advance();
3352                        let if_exists = self.consume_if_exists();
3353                        let mut names = vec![self.expect_ident_like()?];
3354                        while matches!(self.peek(), Token::Comma) {
3355                            self.advance();
3356                            names.push(self.expect_ident_like()?);
3357                        }
3358                        if matches!(
3359                            self.peek(),
3360                            Token::Ident(s) if s.eq_ignore_ascii_case("cascade")
3361                                || s.eq_ignore_ascii_case("restrict")
3362                        ) {
3363                            self.advance();
3364                        }
3365                        Ok(Statement::DropView { names, if_exists })
3366                    }
3367                    // v7.17.0 — DROP SEQUENCE [IF EXISTS] name [,name…]
3368                    // [CASCADE|RESTRICT]. Real removal from catalog
3369                    // (was a silent no-op pre-v7.17).
3370                    Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("sequence") => {
3371                        self.advance();
3372                        let if_exists = self.consume_if_exists();
3373                        let mut names = vec![self.expect_ident_like()?];
3374                        while matches!(self.peek(), Token::Comma) {
3375                            self.advance();
3376                            names.push(self.expect_ident_like()?);
3377                        }
3378                        if matches!(
3379                            self.peek(),
3380                            Token::Ident(s) if s.eq_ignore_ascii_case("cascade")
3381                                || s.eq_ignore_ascii_case("restrict")
3382                        ) {
3383                            self.advance();
3384                        }
3385                        Ok(Statement::DropSequence { names, if_exists })
3386                    }
3387                    // v7.39 (RLS) — DROP POLICY [IF EXISTS] name ON table.
3388                    Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("policy") => {
3389                        self.advance();
3390                        self.parse_drop_policy_after_keyword()
3391                    }
3392                    // v7.37.17 (17.6 siblings) — DROP <target> for
3393                    // targets SPG doesn't natively track. pg_dump
3394                    // emits DROP EXTENSION / DROP TYPE / DROP DOMAIN
3395                    // / DROP AGGREGATE / DROP OPERATOR / DROP CAST /
3396                    // DROP COLLATION / DROP LANGUAGE / DROP CONVERSION
3397                    // / DROP TEXT SEARCH / DROP FOREIGN * / DROP
3398                    // SERVER / DROP MATERIALIZED VIEW / DROP EVENT
3399                    // TRIGGER / DROP TABLESPACE / DROP RULE / DROP
3400                    // POLICY / DROP LARGE OBJECT / DROP ROLE / DROP
3401                    // ACCESS METHOD / DROP OPERATOR CLASS/FAMILY /
3402                    // etc. — accept + Empty-return so pg_dump tails
3403                    // load through. Materialized-view drop dispatches
3404                    // to the existing DropTable path when the token
3405                    // is Materialized-View-shaped (elsewhere in
3406                    // this parser).
3407                    Token::Ident(s) | Token::QuotedIdent(s)
3408                        if s.eq_ignore_ascii_case("text")
3409                            // The DROP dispatch matches on PEEK — `text` is
3410                            // not yet consumed, so SEARCH/CONFIGURATION sit
3411                            // at pos+1/pos+2 (the round-695 trap's mirror).
3412                            && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(k)) if k.eq_ignore_ascii_case("search"))
3413                            && matches!(self.tokens.get(self.pos + 2), Some(Token::Ident(k)) if k.eq_ignore_ascii_case("configuration")) =>
3414                    {
3415                        // v7.39 (round 709) — DROP TEXT SEARCH CONFIGURATION
3416                        // validates the name; DICTIONARY / PARSER / TEMPLATE
3417                        // stay in the noise arm below.
3418                        self.advance(); // TEXT
3419                        self.advance(); // SEARCH
3420                        self.advance(); // CONFIGURATION
3421                        let if_exists = self.consume_if_exists();
3422                        let names = self.take_comma_separated_names();
3423                        self.consume_until_statement_boundary();
3424                        if if_exists {
3425                            return Ok(Statement::Empty);
3426                        }
3427                        Ok(Statement::ValidateOnly {
3428                            kind: crate::ast::ValidateOnlyKind::TsConfigName,
3429                            names,
3430                        })
3431                    }
3432                    Token::Ident(s) | Token::QuotedIdent(s)
3433                        if matches!(
3434                            s.to_ascii_lowercase().as_str(),
3435                            "type"
3436                                | "domain"
3437                                | "operator"
3438                                | "cast"
3439                                // `text` = TEXT SEARCH DICTIONARY / PARSER /
3440                                // TEMPLATE (CONFIGURATION intercepted above).
3441                                | "text"
3442                                | "materialized"
3443                                | "large"
3444                                | "role"
3445                                | "access"
3446                                | "procedure"
3447                                | "routine"
3448                        ) =>
3449                    {
3450                        self.consume_until_statement_boundary();
3451                        Ok(Statement::Empty)
3452                    }
3453                    // v7.39 (round 709) — DROP COLLATION / EVENT TRIGGER /
3454                    // TABLESPACE / TEXT SEARCH CONFIGURATION validate their
3455                    // NAME; DROP SERVER / DROP FOREIGN TABLE join the
3456                    // foreign-data warning family (round 706) so a
3457                    // CREATE→DROP sequence in a dump stays consistent.
3458                    Token::Ident(s) | Token::QuotedIdent(s)
3459                        if s.eq_ignore_ascii_case("server")
3460                            || s.eq_ignore_ascii_case("foreign") =>
3461                    {
3462                        self.advance();
3463                        self.consume_until_statement_boundary();
3464                        Ok(Statement::ValidateOnly {
3465                            kind: crate::ast::ValidateOnlyKind::ForeignInfra,
3466                            names: Vec::new(),
3467                        })
3468                    }
3469                    Token::Ident(s) | Token::QuotedIdent(s)
3470                        if s.eq_ignore_ascii_case("collation")
3471                            || s.eq_ignore_ascii_case("tablespace") =>
3472                    {
3473                        let kind = if s.eq_ignore_ascii_case("collation") {
3474                            crate::ast::ValidateOnlyKind::CollationName
3475                        } else {
3476                            crate::ast::ValidateOnlyKind::TablespaceName
3477                        };
3478                        self.advance();
3479                        let if_exists = self.consume_if_exists();
3480                        let names = self.take_comma_separated_names();
3481                        self.consume_until_statement_boundary();
3482                        if if_exists {
3483                            return Ok(Statement::Empty);
3484                        }
3485                        Ok(Statement::ValidateOnly { kind, names })
3486                    }
3487                    Token::Ident(s) | Token::QuotedIdent(s)
3488                        if s.eq_ignore_ascii_case("event") =>
3489                    {
3490                        self.advance();
3491                        if matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("trigger"))
3492                        {
3493                            self.advance();
3494                        }
3495                        let if_exists = self.consume_if_exists();
3496                        let names = self.take_comma_separated_names();
3497                        self.consume_until_statement_boundary();
3498                        if if_exists {
3499                            return Ok(Statement::Empty);
3500                        }
3501                        Ok(Statement::ValidateOnly {
3502                            kind: crate::ast::ValidateOnlyKind::EventTriggerName,
3503                            names,
3504                        })
3505                    }
3506                    // v7.39 (round 708) — DROP CONVERSION / DROP LANGUAGE
3507                    // leave the noise list; see the ValidateOnly kinds.
3508                    Token::Ident(s) | Token::QuotedIdent(s)
3509                        if s.eq_ignore_ascii_case("conversion")
3510                            || s.eq_ignore_ascii_case("language")
3511                            // `DROP PROCEDURAL LANGUAGE` puts the modifier
3512                            // FIRST — the first draft looked for it after.
3513                            || s.eq_ignore_ascii_case("procedural") =>
3514                    {
3515                        let kind = if s.eq_ignore_ascii_case("conversion") {
3516                            crate::ast::ValidateOnlyKind::ConversionName
3517                        } else {
3518                            crate::ast::ValidateOnlyKind::LanguageName
3519                        };
3520                        self.advance();
3521                        if matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("language"))
3522                        {
3523                            self.advance();
3524                        }
3525                        let if_exists = self.consume_if_exists();
3526                        let names = self.take_comma_separated_names();
3527                        self.consume_until_statement_boundary();
3528                        if if_exists {
3529                            return Ok(Statement::Empty);
3530                        }
3531                        Ok(Statement::ValidateOnly { kind, names })
3532                    }
3533                    // v7.39 (round 707) — `DROP AGGREGATE [IF EXISTS]
3534                    // name(argtypes)[, …]`. Parsed for real so the engine
3535                    // can answer as PG does; see Statement::DropAggregate.
3536                    Token::Ident(s) | Token::QuotedIdent(s)
3537                        if s.eq_ignore_ascii_case("aggregate") =>
3538                    {
3539                        self.advance();
3540                        let if_exists = self.consume_if_exists();
3541                        let mut items: Vec<(String, Option<Vec<String>>)> = Vec::new();
3542                        loop {
3543                            let name = self.expect_ident_like()?;
3544                            if !matches!(self.peek(), Token::LParen) {
3545                                return Err(self.err(alloc::format!(
3546                                    "expected argument list after DROP AGGREGATE {name}"
3547                                )));
3548                            }
3549                            self.advance();
3550                            let mut args: Vec<String> = Vec::new();
3551                            let mut star = false;
3552                            loop {
3553                                match self.peek().clone() {
3554                                    Token::RParen => {
3555                                        self.advance();
3556                                        break;
3557                                    }
3558                                    Token::Star => {
3559                                        self.advance();
3560                                        star = true;
3561                                    }
3562                                    Token::Comma => {
3563                                        self.advance();
3564                                    }
3565                                    _ => {
3566                                        // A type name may be multi-token
3567                                        // (`double precision`); glue idents
3568                                        // until , or ).
3569                                        let mut t = self.expect_ident_like()?;
3570                                        while let Token::Ident(nx) = self.peek() {
3571                                            let nx = nx.clone();
3572                                            self.advance();
3573                                            t.push(' ');
3574                                            t.push_str(&nx);
3575                                        }
3576                                        args.push(t);
3577                                    }
3578                                }
3579                            }
3580                            items.push((name, if star { None } else { Some(args) }));
3581                            if matches!(self.peek(), Token::Comma) {
3582                                self.advance();
3583                            } else {
3584                                break;
3585                            }
3586                        }
3587                        self.consume_until_statement_boundary();
3588                        Ok(Statement::DropAggregate { if_exists, items })
3589                    }
3590                    // v7.39 (round 697) — `DROP EXTENSION [IF EXISTS] <e>
3591                    // [, …] [CASCADE|RESTRICT]`. PG refuses one that is not
3592                    // installed; `IF EXISTS` is the spelling that says do
3593                    // not, and it keeps the no-op.
3594                    Token::Ident(s) | Token::QuotedIdent(s)
3595                        if s.eq_ignore_ascii_case("extension") =>
3596                    {
3597                        self.advance();
3598                        let if_exists = self.consume_if_exists();
3599                        let names = self.take_comma_separated_names();
3600                        self.consume_until_statement_boundary();
3601                        if if_exists {
3602                            return Ok(Statement::Empty);
3603                        }
3604                        Ok(Statement::ValidateOnly {
3605                            kind: crate::ast::ValidateOnlyKind::ExtensionInstalled,
3606                            names,
3607                        })
3608                    }
3609                    Token::Ident(s) | Token::QuotedIdent(s)
3610                        if s.eq_ignore_ascii_case("statistics") =>
3611                    {
3612                        self.parse_drop_statistics_after_drop()
3613                    }
3614                    other => Err(self.err(format!(
3615                        "expected TABLE / INDEX / SCHEMA / SEQUENCE / USER / PUBLICATION / \
3616                         SUBSCRIPTION / TRIGGER / FUNCTION / STATISTICS after DROP, got {other:?}"
3617                    ))),
3618                }
3619            }
3620            // v7.17.0 Phase 1.3 — REFRESH MATERIALIZED VIEW name [WITH [NO] DATA].
3621            // v7.37.19 (19.8) — `CONCURRENTLY` modifier (PG 9.4+) parsed
3622            // and accepted before the view name. SPG materialised
3623            // views re-evaluate on read (always-fresh semantics), so
3624            // the CONCURRENTLY-vs-serial distinction has no runtime
3625            // effect — the refresh body does not block readers either
3626            // way. Same accept-and-no-op pattern as DETACH PARTITION
3627            // CONCURRENTLY (16.5).
3628            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("refresh") => {
3629                self.advance();
3630                let nxt = self.peek().clone();
3631                if !matches!(&nxt, Token::Ident(s2) | Token::QuotedIdent(s2) if s2.eq_ignore_ascii_case("materialized"))
3632                {
3633                    return Err(self.err(alloc::format!(
3634                        "expected MATERIALIZED after REFRESH, got {nxt:?}"
3635                    )));
3636                }
3637                self.advance();
3638                let nxt2 = self.peek().clone();
3639                if !matches!(&nxt2, Token::Ident(s2) | Token::QuotedIdent(s2) if s2.eq_ignore_ascii_case("view"))
3640                {
3641                    return Err(self.err(alloc::format!(
3642                        "expected VIEW after REFRESH MATERIALIZED, got {nxt2:?}"
3643                    )));
3644                }
3645                self.advance();
3646                // Optional CONCURRENTLY noise word — consumed without
3647                // changing semantics.
3648                if matches!(self.peek(), Token::Ident(s2) | Token::QuotedIdent(s2) if s2.eq_ignore_ascii_case("concurrently"))
3649                {
3650                    self.advance();
3651                }
3652                let name = self.expect_ident_like()?;
3653                let with_data = self.parse_optional_with_data(true)?;
3654                Ok(Statement::RefreshMaterializedView { name, with_data })
3655            }
3656            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("update") => {
3657                self.advance();
3658                self.parse_update_after_keyword()
3659            }
3660            // v7.37.17 (17.6 sibling) — TRUNCATE [TABLE] [ONLY]
3661            // <name> [, ...] [RESTART IDENTITY | CONTINUE IDENTITY]
3662            // [CASCADE | RESTRICT]. Clears every row from each named
3663            // table. Parses at the top level; the engine dispatcher
3664            // walks Statement::Truncate.
3665            // v7.39.9 — MySQL's top-level `RENAME TABLE a TO b [, c TO d]`.
3666            //
3667            // PostgreSQL renames a table through `ALTER TABLE … RENAME
3668            // TO`, which SPG already had, so this spelling answered 1064
3669            // — and it is what a MySQL migration writes. Measured on
3670            // 9.7.2: several pairs in one statement are accepted, and
3671            // renaming onto a name that exists is 1050.
3672            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("rename") => {
3673                self.advance();
3674                if matches!(self.peek(), Token::Table) {
3675                    self.advance();
3676                }
3677                let mut pairs: Vec<(String, String)> = Vec::new();
3678                loop {
3679                    let from = self.expect_ident_like()?;
3680                    if matches!(self.peek(), Token::To) {
3681                        self.advance();
3682                    } else {
3683                        self.expect_keyword_ident("to")?;
3684                    }
3685                    let to = self.expect_ident_like()?;
3686                    pairs.push((from, to));
3687                    if matches!(self.peek(), Token::Comma) {
3688                        self.advance();
3689                    } else {
3690                        break;
3691                    }
3692                }
3693                Ok(Statement::RenameTables(pairs))
3694            }
3695            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("truncate") => {
3696                self.advance();
3697                // Optional TABLE noise word — PG accepts both the reserved
3698                // token and the bare identifier spelling.
3699                if matches!(self.peek(), Token::Table)
3700                    || matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("table"))
3701                {
3702                    self.advance();
3703                }
3704                // v7.39 (round 647) — `TRUNCATE ONLY t` is carried now,
3705                // not absorbed. The lookahead keeps a table genuinely
3706                // called `only` working: the keyword is a keyword only
3707                // when a name follows it.
3708                let only = matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
3709                    if s.eq_ignore_ascii_case("only"))
3710                    && matches!(
3711                        self.tokens.get(self.pos + 1),
3712                        Some(Token::Ident(_) | Token::QuotedIdent(_))
3713                    );
3714                if only {
3715                    self.advance();
3716                }
3717                // Table names (comma-separated).
3718                let mut tables = Vec::new();
3719                loop {
3720                    tables.push(self.expect_ident_like()?);
3721                    if matches!(self.peek(), Token::Comma) {
3722                        self.advance();
3723                        continue;
3724                    }
3725                    break;
3726                }
3727                // Optional RESTART IDENTITY / CONTINUE IDENTITY.
3728                let mut restart_identity = false;
3729                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("restart"))
3730                {
3731                    self.advance();
3732                    if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("identity"))
3733                    {
3734                        self.advance();
3735                        restart_identity = true;
3736                    }
3737                } else if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("continue"))
3738                {
3739                    self.advance();
3740                    if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("identity"))
3741                    {
3742                        self.advance();
3743                    }
3744                }
3745                // Optional CASCADE / RESTRICT.
3746                let mut cascade = false;
3747                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("cascade"))
3748                {
3749                    self.advance();
3750                    cascade = true;
3751                } else if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("restrict"))
3752                {
3753                    self.advance();
3754                }
3755                Ok(Statement::Truncate {
3756                    tables,
3757                    restart_identity,
3758                    cascade,
3759                    only,
3760                })
3761            }
3762            // v7.37.17 (17.6 sibling) — REINDEX [(OPTION [, ...])]
3763            // [CONCURRENTLY] { INDEX | TABLE | SCHEMA | DATABASE |
3764            // SYSTEM } [IF EXISTS] <name>. SPG rebuilds indexes as
3765            // rows change so the index tree is always up-to-date;
3766            // REINDEX is a strict no-op. Accept the whole statement
3767            // shape to boundary for pg_dump round-trip compatibility.
3768            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("reindex") => {
3769                // v7.39 (round 535) — the target is CARRIED now. SPG has no
3770                // index bloat to rebuild, so the work stays a no-op, but PG
3771                // validates what it was pointed at and this swallowed the
3772                // name at parse time — `REINDEX TABLE typo` reported
3773                // success. Measured on PG18: INDEX / TABLE name a relation,
3774                // SCHEMA a schema, SYSTEM nothing.
3775                self.advance();
3776                self.parse_reindex_tail()
3777            }
3778            // v7.37.17 (17.6 sibling) — VACUUM [(OPTION [, ...])]
3779            // [FULL] [FREEZE] [VERBOSE] [ANALYZE] [<table> [(cols)]].
3780            // SPG has no MVCC bloat today (Phase D visibility map
3781            // queues with v7.38); the freezer collapses hot-tier
3782            // rows into cold segments automatically. VACUUM is a
3783            // no-op — pg_dump maintenance scripts and Discourse's
3784            // periodic-maintenance path both emit it.
3785            // v7.39 (round 169) — VACUUM is REAL now: with the in-place
3786            // MVCC gate ON (v7.37.15 flip), tombstoned versions are
3787            // actual bloat, so the pre-MVCC accept-and-ignore posture
3788            // became a silent no-op on a customer's manual reclaim.
3789            // Grammar: VACUUM [(opts)] [FULL] [FREEZE] [VERBOSE]
3790            // [ANALYZE] [<table> [(cols)]] — option words are absorbed,
3791            // ANALYZE is captured, the optional table name is captured.
3792            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("vacuum") => {
3793                self.advance();
3794                // Parenthesised option list: absorb it.
3795                if matches!(self.peek(), Token::LParen) {
3796                    let mut depth = 0usize;
3797                    loop {
3798                        match self.advance() {
3799                            Token::LParen => depth += 1,
3800                            Token::RParen => {
3801                                depth -= 1;
3802                                if depth == 0 {
3803                                    break;
3804                                }
3805                            }
3806                            Token::Eof => break,
3807                            _ => {}
3808                        }
3809                    }
3810                }
3811                let mut analyze = false;
3812                let mut table: Option<String> = None;
3813                loop {
3814                    match self.peek() {
3815                        // v7.39 (round 535) — `FULL` lexes as a keyword, not
3816                        // an identifier, so the loop below broke out on it and
3817                        // dropped the table name: `VACUUM FULL nosuch` was
3818                        // accepted where `VACUUM nosuch` was refused.
3819                        Token::Full => {
3820                            self.advance();
3821                        }
3822                        Token::Ident(w) | Token::QuotedIdent(w) => {
3823                            let wl = w.to_ascii_lowercase();
3824                            match wl.as_str() {
3825                                "full" | "freeze" | "verbose" => {
3826                                    self.advance();
3827                                }
3828                                "analyze" | "analyse" => {
3829                                    analyze = true;
3830                                    self.advance();
3831                                }
3832                                _ => {
3833                                    table = Some(self.expect_ident_like()?);
3834                                    break;
3835                                }
3836                            }
3837                        }
3838                        _ => break,
3839                    }
3840                }
3841                // Optional trailing column list / anything else to the
3842                // statement boundary (PG accepts per-column ANALYZE).
3843                self.consume_until_statement_boundary();
3844                Ok(Statement::Vacuum { table, analyze })
3845            }
3846            // v7.37.17 (17.6 sibling) — CLUSTER [VERBOSE] <table>
3847            // [USING <index>] / CLUSTER (VERBOSE) <table> USING
3848            // <index>. PG stores rows in physical order matching
3849            // an index; SPG's hot-tier is append-only + cold-tier
3850            // is segment-frozen, so clustering has no persistent
3851            // effect. Accept-and-no-op for pg_dump compat.
3852            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("cluster") => {
3853                // v7.39 (round 535) — same as REINDEX above: the relation is
3854                // carried so the engine can refuse one that does not exist.
3855                // A bare `CLUSTER [VERBOSE]` names nothing and is accepted.
3856                self.advance();
3857                self.parse_cluster_tail()
3858            }
3859            // v7.39 (round 222) — LISTEN / NOTIFY / UNLISTEN with real
3860            // delivery (was accept-and-drop since v7.37.17). NOTIFY takes an
3861            // optional string payload; UNLISTEN takes a channel or `*`.
3862            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("listen") => {
3863                self.advance();
3864                let ch = match self.advance() {
3865                    Token::Ident(c) | Token::QuotedIdent(c) => c,
3866                    other => {
3867                        return Err(self.err(format!(
3868                            "expected channel name after LISTEN, got {other:?}"
3869                        )));
3870                    }
3871                };
3872                Ok(Statement::Listen(ch))
3873            }
3874            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("notify") => {
3875                self.advance();
3876                let channel = match self.advance() {
3877                    Token::Ident(c) | Token::QuotedIdent(c) => c,
3878                    other => {
3879                        return Err(self.err(format!(
3880                            "expected channel name after NOTIFY, got {other:?}"
3881                        )));
3882                    }
3883                };
3884                let payload = if matches!(self.peek(), Token::Comma) {
3885                    self.advance();
3886                    match self.advance() {
3887                        Token::String(p) => Some(p),
3888                        other => {
3889                            return Err(self.err(format!(
3890                                "expected string payload after NOTIFY <channel>, got {other:?}"
3891                            )));
3892                        }
3893                    }
3894                } else {
3895                    None
3896                };
3897                Ok(Statement::Notify { channel, payload })
3898            }
3899            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("unlisten") => {
3900                self.advance();
3901                match self.advance() {
3902                    Token::Star => Ok(Statement::Unlisten(None)),
3903                    Token::Ident(c) | Token::QuotedIdent(c) => Ok(Statement::Unlisten(Some(c))),
3904                    other => Err(self.err(format!(
3905                        "expected channel name or * after UNLISTEN, got {other:?}"
3906                    ))),
3907                }
3908            }
3909            // v7.37.17 (17.6 sibling) — LOCK [TABLE] [ONLY] <table>
3910            // [IN <mode> MODE] [NOWAIT]. SPG's engine holds a
3911            // process-wide write lock today; explicit LOCK has no
3912            // effect. Accept-and-no-op for pg_dump / migration
3913            // compat.
3914            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("lock") => {
3915                self.advance();
3916                // v7.39 (round 696) — the LOCK still has no effect (SPG's
3917                // engine holds a process-wide write lock), but the TABLE
3918                // NAME is now carried out so the engine can refuse one that
3919                // does not exist, as PG18 does. MySQL's `LOCK TABLES …
3920                // READ|WRITE` is a different statement with the same first
3921                // word; it keeps the old no-op, because a MySQL dump's
3922                // bracket names tables it is about to create.
3923                let mysql_tables = matches!(self.peek(), Token::Ident(k)
3924                    if k.eq_ignore_ascii_case("tables"));
3925                if mysql_tables {
3926                    self.consume_until_statement_boundary();
3927                    return Ok(Statement::Empty);
3928                }
3929                if matches!(self.peek(), Token::Table) {
3930                    self.advance();
3931                }
3932                let names = self.take_comma_separated_names();
3933                self.consume_until_statement_boundary();
3934                Ok(Statement::ValidateOnly {
3935                    kind: crate::ast::ValidateOnlyKind::LockTable,
3936                    names,
3937                })
3938            }
3939            // v7.37.17 (17.6 sibling) — CHECKPOINT. Forces a WAL
3940            // durability marker + snapshot in PG. SPG has WAL
3941            // checkpointing on a byte / time schedule (v7.37.10
3942            // 60s / 4 MiB defaults). The bare statement parses to
3943            // `Statement::Empty` here (the no_std engine owns no
3944            // WAL / snapshot); v7.37 Epic Du wires the HOST
3945            // (embedded `Database::execute_buffered`, via
3946            // `sql_is_checkpoint`) to force an immediate synchronous
3947            // checkpoint through `Database::checkpoint` — a real
3948            // durability barrier, matching PG.
3949            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("checkpoint") => {
3950                self.advance();
3951                self.consume_until_statement_boundary();
3952                Ok(Statement::Empty)
3953            }
3954            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("delete") => {
3955                self.advance();
3956                self.parse_delete_after_keyword()
3957            }
3958            // v6.0.4: ALTER INDEX <name> REBUILD [WITH (encoding = ...)].
3959            // ALTER is not a reserved keyword in the lexer — handled
3960            // as a bare ident here.
3961            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("alter") => {
3962                self.advance();
3963                self.parse_alter_after_keyword()
3964            }
3965            // v6.1.7: WAIT FOR WAL POSITION <pos> [WITH TIMEOUT <ms>].
3966            // WAIT / POSITION / TIMEOUT are bare idents — no lexer
3967            // additions needed.
3968            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("wait") => {
3969                self.advance();
3970                self.parse_wait_after_keyword()
3971            }
3972            // v6.2.0: ANALYZE [<table>]. ANALYZE is a bare ident.
3973            // Bare ANALYZE → analyse every user table; ANALYZE
3974            // <name> → re-stats one. The argument is an optional
3975            // ident (or quoted ident); anything else is a parse
3976            // error.
3977            // v6.7.3 — `COMPACT COLD SEGMENTS`. No arguments, no
3978            // `WHERE` filter (carved out per V6_7_DESIGN.md
3979            // STABILITY). Lex order: identifier "compact" → "cold"
3980            // → "segments". Anything else after `COMPACT` is a
3981            // parse error.
3982            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("compact") => {
3983                self.advance();
3984                let next = self.peek().clone();
3985                let cold = match next {
3986                    Token::Ident(s) | Token::QuotedIdent(s) => s,
3987                    _ => {
3988                        return Err(
3989                            self.err(format!("expected COLD after COMPACT, got {:?}", self.peek()))
3990                        );
3991                    }
3992                };
3993                if !cold.eq_ignore_ascii_case("cold") {
3994                    return Err(self.err(format!("expected COLD after COMPACT, got {cold:?}")));
3995                }
3996                self.advance();
3997                let next = self.peek().clone();
3998                let segments = match next {
3999                    Token::Ident(s) | Token::QuotedIdent(s) => s,
4000                    _ => {
4001                        return Err(self.err(format!(
4002                            "expected SEGMENTS after COMPACT COLD, got {:?}",
4003                            self.peek()
4004                        )));
4005                    }
4006                };
4007                if !segments.eq_ignore_ascii_case("segments") {
4008                    return Err(self.err(format!(
4009                        "expected SEGMENTS after COMPACT COLD, got {segments:?}"
4010                    )));
4011                }
4012                self.advance();
4013                Ok(Statement::CompactColdSegments)
4014            }
4015            // v7.17.0 Phase 3.P0-42 — SQL:2003 / PG 15+ MERGE.
4016            // Parsed as a case-insensitive identifier since MERGE
4017            // isn't a reserved lexer keyword (collides with the
4018            // mysqldump `ALGORITHM = MERGE` view clause if it
4019            // were); the inner parser drives the rest of the
4020            // surface (USING / ON / WHEN [NOT] MATCHED / THEN).
4021            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("merge") => {
4022                self.advance();
4023                self.parse_merge_after_keyword()
4024            }
4025            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("analyze") => {
4026                self.advance();
4027                // v7.39.9 — MySQL spells it `ANALYZE TABLE t`. The
4028                // keyword is noise to the parse; what differs is the
4029                // ANSWER, which MySQL returns as a result set — see the
4030                // executor.
4031                let mysql_table_kw = matches!(self.peek(), Token::Table);
4032                if mysql_table_kw {
4033                    self.advance();
4034                }
4035                let target = match self.peek() {
4036                    Token::Eof | Token::Semicolon => None,
4037                    Token::Ident(_) | Token::QuotedIdent(_) => {
4038                        Some(self.expect_ident_like()?)
4039                    }
4040                    other => {
4041                        return Err(self.err(format!(
4042                            "expected table name or end of statement after ANALYZE, got {other:?}"
4043                        )));
4044                    }
4045                };
4046                // v7.39 (round 776, F31 J7) — the per-column form
4047                // (`ANALYZE t (x, y)`, PG-accepted) was a syntax error
4048                // here while the VACUUM arm already consumed it; SPG
4049                // analyzes whole tables, so the list parses and is
4050                // accepted like the VACUUM path's.
4051                if target.is_some() && matches!(self.peek(), Token::LParen) {
4052                    self.advance();
4053                    loop {
4054                        let _ = self.expect_ident_like()?;
4055                        match self.peek() {
4056                            Token::Comma => {
4057                                self.advance();
4058                            }
4059                            Token::RParen => {
4060                                self.advance();
4061                                break;
4062                            }
4063                            other => {
4064                                return Err(self.err(format!(
4065                                    "expected ',' or ')' in ANALYZE column list, got {other:?}"
4066                                )));
4067                            }
4068                        }
4069                    }
4070                }
4071                Ok(Statement::Analyze(target))
4072            }
4073            // v7.12.1 — `SET <name> [TO|=] <value>`. The
4074            // `default_text_search_config` parameter is consumed
4075            // by the FTS function dispatcher; other parameter
4076            // names are recorded but treated as a no-op so PG
4077            // dump output loads.
4078            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("set") => {
4079                self.advance();
4080                // PG allows `SET LOCAL` / `SET SESSION` qualifiers; MySQL
4081                // adds `SET GLOBAL` too (and the alias `SET @@global.name =
4082                // …` which the SessionVar path handles). `LOCAL` is the only
4083                // one that changes semantics — it scopes the change to the
4084                // current transaction — so capture it; SESSION / GLOBAL are
4085                // accepted and treated as the default session scope.
4086                let mut set_local = false;
4087                if let Token::Ident(s) | Token::QuotedIdent(s) = self.peek() {
4088                    let q = s.to_ascii_lowercase();
4089                    if q == "local" || q == "session" || q == "global" {
4090                        set_local = q == "local";
4091                        self.advance();
4092                    }
4093                }
4094                // 7.38.1 S5.2 — PG `SET [SESSION] AUTHORIZATION
4095                // { DEFAULT | <role> }`. pg_dump's ACL section switches
4096                // to the object owner with it. SPG maps it onto the
4097                // session-role machinery (recorded delta RD-10: PG moves
4098                // session_user too; SPG moves the effective role).
4099                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
4100                    if s.eq_ignore_ascii_case("authorization"))
4101                {
4102                    self.advance(); // AUTHORIZATION
4103                    let role = match self.peek().clone() {
4104                        Token::Default => {
4105                            self.advance();
4106                            None
4107                        }
4108                        Token::String(s) | Token::Ident(s) | Token::QuotedIdent(s) => {
4109                            self.advance();
4110                            Some(s)
4111                        }
4112                        _ => None,
4113                    };
4114                    return Ok(Statement::SetRole(role));
4115                }
4116                // v7.14.0 — MySQL `SET NAMES <charset> [COLLATE
4117                // <collation>]` — change the connection client
4118                // charset. SPG stores UTF-8 always and orders
4119                // bytewise; accept as a no-op.
4120                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("names"))
4121                {
4122                    self.advance();
4123                    // v7.39 — this used to parse the clause and throw it
4124                    // away ("SPG stores UTF-8 always and orders
4125                    // bytewise; accept as a no-op"). That sentence
4126                    // stopped being true when collations arrived, and
4127                    // once `collation_connection` began driving literal
4128                    // comparison, dropping the COLLATE clause became a
4129                    // silently wrong answer: `SET NAMES utf8mb4 COLLATE
4130                    // utf8mb4_general_ci` reported back
4131                    // `utf8mb4_0900_ai_ci` and compared as NO PAD.
4132                    //
4133                    // The charset name is emitted as `names` and the
4134                    // ENGINE expands it, because which collation a
4135                    // charset defaults to is MySQL semantics and belongs
4136                    // beside the rest of them, not in the parser.
4137                    let mut pairs = alloc::vec::Vec::new();
4138                    if matches!(
4139                        self.peek(),
4140                        Token::Ident(_) | Token::QuotedIdent(_) | Token::String(_)
4141                    ) {
4142                        let charset = match self.advance() {
4143                            Token::Ident(s) | Token::QuotedIdent(s) | Token::String(s) => s,
4144                            _ => unreachable!("peeked an ident-or-string"),
4145                        };
4146                        pairs.push((String::from("names"), crate::ast::SetValue::Ident(charset)));
4147                    }
4148                    // Optional `COLLATE <name>` — emitted AFTER `names`
4149                    // so it overrides the charset's default, which is
4150                    // what MySQL does.
4151                    if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("collate"))
4152                    {
4153                        self.advance();
4154                        if matches!(
4155                            self.peek(),
4156                            Token::Ident(_) | Token::QuotedIdent(_) | Token::String(_)
4157                        ) {
4158                            let coll = match self.advance() {
4159                                Token::Ident(s) | Token::QuotedIdent(s) | Token::String(s) => s,
4160                                _ => unreachable!("peeked an ident-or-string"),
4161                            };
4162                            pairs.push((
4163                                String::from("collation_connection"),
4164                                crate::ast::SetValue::Ident(coll),
4165                            ));
4166                        }
4167                    }
4168                    if pairs.is_empty() {
4169                        return Ok(Statement::Empty);
4170                    }
4171                    return Ok(Statement::SetParameterList(pairs));
4172                }
4173                // v7.37.17 (17.6 sibling) — PG `SET ROLE
4174                // { NONE | DEFAULT | <role_name> }`. pg_dump preamble
4175                // uses this to switch to the object owner before
4176                // recreating tables. SPG has no role system so this
4177                // is a no-op.
4178                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("role"))
4179                {
4180                    self.advance(); // ROLE
4181                    // v7.39 (RLS) — real session-role switch. NONE / DEFAULT
4182                    // reset to the login identity; a name / string sets the
4183                    // effective role that drives current_user + RLS.
4184                    let role = match self.peek().clone() {
4185                        Token::Default => {
4186                            self.advance();
4187                            None
4188                        }
4189                        Token::Ident(s) | Token::QuotedIdent(s)
4190                            if s.eq_ignore_ascii_case("none") =>
4191                        {
4192                            self.advance();
4193                            None
4194                        }
4195                        Token::String(s) | Token::Ident(s) | Token::QuotedIdent(s) => {
4196                            self.advance();
4197                            Some(s)
4198                        }
4199                        _ => None,
4200                    };
4201                    return Ok(Statement::SetRole(role));
4202                }
4203                // v7.37.17 (17.6 sibling) — PG `SET SESSION
4204                // CHARACTERISTICS AS TRANSACTION <mode>` (per PG
4205                // ISO SQL surface). pg_dump prepends this to fix
4206                // the isolation level for the restore session. SPG
4207                // defaults to READ COMMITTED and doesn't yet honor
4208                // session-set isolation across statements — accept
4209                // and no-op. SET (LOCAL/SESSION) TRANSACTION AS ...
4210                // per-tx form is handled elsewhere.
4211                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("characteristics"))
4212                {
4213                    self.advance(); // CHARACTERISTICS
4214                    if matches!(self.peek(), Token::As) {
4215                        self.advance();
4216                    }
4217                    if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("transaction")) {
4218                        self.advance();
4219                    }
4220                    // v7.39 — no longer a no-op. The note above said SPG
4221                    // "doesn't yet honor session-set isolation across
4222                    // statements"; it does now, through
4223                    // `default_transaction_isolation`, and measured on
4224                    // PG 18.6 this statement is exactly a way to set it:
4225                    //
4226                    //   SET SESSION CHARACTERISTICS AS TRANSACTION
4227                    //       ISOLATION LEVEL REPEATABLE READ;
4228                    //   current_setting('default_transaction_isolation')
4229                    //       -> repeatable read
4230                    //
4231                    // pg_dump prepends this to fix the level for a
4232                    // restore session, so accepting it and doing nothing
4233                    // meant the restore ran at a level nobody chose.
4234                    //
4235                    // The trailing READ ONLY / [NOT] DEFERRABLE modes are
4236                    // still consumed and dropped. `default_transaction_read_only`
4237                    // exists in the GUC inventory but nothing enforces it,
4238                    // and setting a value no code honours is the very
4239                    // defect this version is about — a session told it
4240                    // holds a guarantee it does not.
4241                    let modes = self.parse_isolation_level_clauses()?;
4242                    self.consume_until_statement_boundary();
4243                    let mut pairs: alloc::vec::Vec<(
4244                        alloc::string::String,
4245                        crate::ast::SetValue,
4246                    )> = alloc::vec::Vec::new();
4247                    if let Some(level) = modes.isolation {
4248                        pairs.push((
4249                            alloc::string::String::from("default_transaction_isolation"),
4250                            crate::ast::SetValue::String(alloc::string::String::from(
4251                                level.as_pg_str(),
4252                            )),
4253                        ));
4254                    }
4255                    if let Some(ro) = modes.read_only {
4256                        pairs.push((
4257                            alloc::string::String::from("default_transaction_read_only"),
4258                            crate::ast::SetValue::Ident(alloc::string::String::from(if ro {
4259                                "on"
4260                            } else {
4261                                "off"
4262                            })),
4263                        ));
4264                    }
4265                    return Ok(if pairs.is_empty() {
4266                        Statement::Empty
4267                    } else {
4268                        Statement::SetParameterList(pairs)
4269                    });
4270                }
4271                // v7.37.17 (17.6 sibling) — PG `SET CONSTRAINTS
4272                // { ALL | <name>[, ...] } { DEFERRED | IMMEDIATE }`.
4273                // pg_dump emits this to control the deferrability of
4274                // FK / UNIQUE constraints across a bulk restore. SPG
4275                // has no deferrable-constraint machinery today; the
4276                // FK checker is strict-immediate. Accept-and-no-op
4277                // for pg_dump round-trip compatibility.
4278                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("constraints"))
4279                {
4280                    self.advance(); // CONSTRAINTS
4281                    // v7.39 (round 288) — no longer a no-op: the trailing
4282                    // DEFERRED / IMMEDIATE sets the transaction's timing.
4283                    // v7.39 (round 308, V29) — and the names are kept.
4284                    // They used to be skipped over on the way to the
4285                    // DEFERRED keyword, so a named form silently behaved
4286                    // as ALL: `SET CONSTRAINTS fk_a DEFERRED` deferred
4287                    // every deferrable constraint in the transaction.
4288                    let mut names: alloc::vec::Vec<alloc::string::String> =
4289                        alloc::vec::Vec::new();
4290                    if matches!(self.peek(), Token::All) {
4291                        self.advance();
4292                    } else {
4293                        loop {
4294                            let mut n = self.expect_ident_like()?;
4295                            // A schema-qualified name (`public.fk_a`)
4296                            // identifies the same constraint; PG resolves
4297                            // it by the trailing segment.
4298                            while matches!(self.peek(), Token::Dot) {
4299                                self.advance();
4300                                n = self.expect_ident_like()?;
4301                            }
4302                            names.push(n);
4303                            if matches!(self.peek(), Token::Comma) {
4304                                self.advance();
4305                            } else {
4306                                break;
4307                            }
4308                        }
4309                    }
4310                    let deferred = match self.peek() {
4311                        Token::Ident(s) | Token::QuotedIdent(s)
4312                            if s.eq_ignore_ascii_case("deferred") =>
4313                        {
4314                            true
4315                        }
4316                        Token::Ident(s) | Token::QuotedIdent(s)
4317                            if s.eq_ignore_ascii_case("immediate") =>
4318                        {
4319                            false
4320                        }
4321                        other => {
4322                            return Err(self.err(alloc::format!(
4323                                "expected DEFERRED or IMMEDIATE after SET CONSTRAINTS, got {other:?}"
4324                            )));
4325                        }
4326                    };
4327                    self.advance();
4328                    return Ok(Statement::SetConstraints { names, deferred });
4329                }
4330                // v7.16.2 — PG `SET [SESSION] AUTHORIZATION
4331                // { DEFAULT | '<role>' | <ident> }` (mailrs
4332                // round-10 A.1). pg_dump preamble emits the
4333                // `DEFAULT` form to reset session authorization.
4334                //
4335                // v7.39 (round 697) — this said "SPG has no role system so
4336                // this is a strict no-op". SPG has had one since round 58;
4337                // the comment outlived it, and with it the reason a name
4338                // that is not a role was accepted here. It still switches
4339                // no authorization — what it does now is refuse a role
4340                // that does not exist, as PG18 does. PG also accepts `RESET SESSION
4341                // AUTHORIZATION` (handled by the RESET parser
4342                // elsewhere). Reference:
4343                // <https://www.postgresql.org/docs/current/sql-set-session-authorization.html>
4344                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("authorization"))
4345                {
4346                    self.advance(); // AUTHORIZATION
4347                    match self.peek().clone() {
4348                        Token::Default => {
4349                            self.advance();
4350                        }
4351                        Token::String(r) | Token::Ident(r) | Token::QuotedIdent(r) => {
4352                            self.advance();
4353                            return Ok(Statement::ValidateOnly {
4354                                kind: crate::ast::ValidateOnlyKind::RoleName,
4355                                names: alloc::vec![r],
4356                            });
4357                        }
4358                        other => {
4359                            return Err(self.err(alloc::format!(
4360                                "expected DEFAULT / '<role>' / <ident> after SET SESSION AUTHORIZATION, got {other:?}"
4361                            )));
4362                        }
4363                    }
4364                    return Ok(Statement::Empty);
4365                }
4366                // v7.38 轴 4 — `SET [SESSION] TRANSACTION
4367                // ISOLATION LEVEL { READ COMMITTED | READ
4368                // UNCOMMITTED | REPEATABLE READ | SERIALIZABLE }
4369                // [, READ {ONLY|WRITE}] [, [NOT] DEFERRABLE]`.
4370                // PG-standard surface. v7.37.8 accepts the syntax
4371                // and tracks the selected level on
4372                // `Engine::current_isolation_level()`; the actual
4373                // MVCC / SSI semantics implementation lands in
4374                // the 轴 4 isolation framework (separate train).
4375                // PG itself maps READ UNCOMMITTED to READ COMMITTED
4376                // internally; SPG behaves the same (effectively
4377                // READ COMMITTED at every level today).
4378                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("transaction"))
4379                {
4380                    self.advance(); // TRANSACTION
4381                    let modes = self.parse_isolation_level_clauses()?;
4382                    return Ok(Statement::SetTransaction { modes });
4383                }
4384                // v7.14.0 — MySQL `SET CHARACTER SET <charset>`
4385                // alias — same accept-as-no-op as SET NAMES.
4386                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("character"))
4387                    && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("set"))
4388                {
4389                    self.advance(); // CHARACTER
4390                    self.advance(); // SET
4391                    if matches!(
4392                        self.peek(),
4393                        Token::Ident(_) | Token::QuotedIdent(_) | Token::String(_)
4394                    ) {
4395                        self.advance();
4396                    }
4397                    return Ok(Statement::Empty);
4398                }
4399                // v7.39 (GUC) — PG spells the timezone GUC as two
4400                // keywords: `SET [LOCAL|SESSION] TIME ZONE <value>`,
4401                // where <value> is a string/ident or the LOCAL /
4402                // DEFAULT keyword (both mean "back to the default").
4403                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("time"))
4404                    && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("zone"))
4405                {
4406                    self.advance(); // TIME
4407                    self.advance(); // ZONE
4408                    let value = match self.peek().clone() {
4409                        Token::Ident(s)
4410                            if s.eq_ignore_ascii_case("local")
4411                                || s.eq_ignore_ascii_case("default") =>
4412                        {
4413                            self.advance();
4414                            crate::ast::SetValue::Default
4415                        }
4416                        Token::Default => {
4417                            self.advance();
4418                            crate::ast::SetValue::Default
4419                        }
4420                        _ => self.parse_set_value()?,
4421                    };
4422                    return Ok(Statement::SetParameter {
4423                        name: "timezone".into(),
4424                        value,
4425                        local: set_local,
4426                    });
4427                }
4428                // v7.39 (round 430) — `SET @x = <expr> [, @y := <expr>]` is a
4429                // MySQL USER-variable assignment: its own per-session
4430                // namespace, an arbitrary expression on the right, and `:=`
4431                // as a second spelling of `=`. It used to fall into the
4432                // session-PARAMETER list below, whose values are literals and
4433                // whose store nothing reads back under a `@` name — so the
4434                // assignment reported success and vanished.
4435                //
4436                // A `@@`-prefixed LHS is a real engine setting and keeps the
4437                // old path.
4438                if matches!(self.peek(), Token::SessionVar(s) if !s.starts_with("@@")) {
4439                    return self.parse_set_user_vars();
4440                }
4441                // v7.14.0 — multi-assignment form
4442                // `SET a = 1, b = 2, …`. Single-assignment is the
4443                // 1-element case. Each LHS may be a regular ident
4444                // or a SessionVar (`@VAR` / `@@VAR`).
4445                let mut pairs: Vec<(String, crate::ast::SetValue)> = Vec::new();
4446                loop {
4447                    let lhs = match self.peek().clone() {
4448                        Token::SessionVar(s) => {
4449                            self.advance();
4450                            s
4451                        }
4452                        Token::Ident(_) | Token::QuotedIdent(_) => self.parse_set_param_name()?,
4453                        other => {
4454                            return Err(self.err(format!(
4455                                "expected parameter name after SET, got {other:?}"
4456                            )));
4457                        }
4458                    };
4459                    // Accept either `=` or the bare `TO` keyword.
4460                    match self.peek() {
4461                        Token::Eq => {
4462                            self.advance();
4463                        }
4464                        Token::To => {
4465                            self.advance();
4466                        }
4467                        other => {
4468                            return Err(self.err(format!(
4469                                "expected `=` or TO after SET {lhs}, got {other:?}"
4470                            )));
4471                        }
4472                    }
4473                    let mut value = self.parse_set_value()?;
4474                    // v7.39 (GUC) — disambiguate the comma: `, name =` /
4475                    // `, name TO` continues a MySQL-style multi-assign,
4476                    // anything else is a PG list VALUE
4477                    // (`SET search_path = myschema, public`) folded into
4478                    // one comma-joined string.
4479                    while matches!(self.peek(), Token::Comma) {
4480                        let is_assign = matches!(
4481                            self.tokens.get(self.pos + 1),
4482                            Some(Token::Ident(_) | Token::QuotedIdent(_) | Token::SessionVar(_))
4483                        ) && matches!(
4484                            self.tokens.get(self.pos + 2),
4485                            Some(Token::Eq | Token::To)
4486                        );
4487                        if is_assign {
4488                            break;
4489                        }
4490                        self.advance(); // comma
4491                        let next = self.parse_set_value()?;
4492                        let joined = alloc::format!(
4493                            "{}, {}",
4494                            set_value_text(&value),
4495                            set_value_text(&next)
4496                        );
4497                        value = crate::ast::SetValue::String(joined);
4498                    }
4499                    pairs.push((lhs, value));
4500                    if matches!(self.peek(), Token::Comma) {
4501                        self.advance();
4502                        continue;
4503                    }
4504                    break;
4505                }
4506                if pairs.len() == 1 {
4507                    let (name, value) = pairs.into_iter().next().unwrap();
4508                    Ok(Statement::SetParameter {
4509                        name,
4510                        value,
4511                        local: set_local,
4512                    })
4513                } else {
4514                    Ok(Statement::SetParameterList(pairs))
4515                }
4516            }
4517            // v7.12.1 — `RESET <name>` / `RESET ALL`.
4518            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("reset") => {
4519                self.advance();
4520                match self.peek().clone() {
4521                    Token::All => {
4522                        self.advance();
4523                        Ok(Statement::ResetParameter(None))
4524                    }
4525                    Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("all") => {
4526                        self.advance();
4527                        Ok(Statement::ResetParameter(None))
4528                    }
4529                    // v7.39 (RLS) — `RESET ROLE` clears the session role.
4530                    Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("role") => {
4531                        self.advance();
4532                        Ok(Statement::SetRole(None))
4533                    }
4534                    // 7.38.1 S5.2 — `RESET SESSION AUTHORIZATION`
4535                    // (pg_dump's return from the owner switch).
4536                    Token::Ident(s) | Token::QuotedIdent(s)
4537                        if s.eq_ignore_ascii_case("session")
4538                            && matches!(
4539                                self.tokens.get(self.pos + 1),
4540                                Some(Token::Ident(a) | Token::QuotedIdent(a))
4541                                    if a.eq_ignore_ascii_case("authorization")
4542                            ) =>
4543                    {
4544                        self.advance(); // SESSION
4545                        self.advance(); // AUTHORIZATION
4546                        Ok(Statement::SetRole(None))
4547                    }
4548                    _ => {
4549                        let name = self.parse_set_param_name()?;
4550                        Ok(Statement::ResetParameter(Some(name)))
4551                    }
4552                }
4553            }
4554            // v7.39 (round 218) — server-side cursors.
4555            Token::Ident(s) if s.eq_ignore_ascii_case("declare") => self.parse_declare_cursor(),
4556            Token::Ident(s) if s.eq_ignore_ascii_case("fetch") => self.parse_fetch_or_move(false),
4557            Token::Ident(s) if s.eq_ignore_ascii_case("move") => self.parse_fetch_or_move(true),
4558            Token::Ident(s) if s.eq_ignore_ascii_case("close") => {
4559                self.advance();
4560                match self.peek().clone() {
4561                    Token::All => {
4562                        self.advance();
4563                        Ok(Statement::CloseCursor { name: None })
4564                    }
4565                    Token::Ident(s) if s.eq_ignore_ascii_case("all") => {
4566                        self.advance();
4567                        Ok(Statement::CloseCursor { name: None })
4568                    }
4569                    Token::Ident(n) | Token::QuotedIdent(n) => {
4570                        self.advance();
4571                        Ok(Statement::CloseCursor { name: Some(n) })
4572                    }
4573                    other => Err(self.err(format!(
4574                        "expected cursor name or ALL after CLOSE, got {other:?}"
4575                    ))),
4576                }
4577            }
4578            other => Err(self.err(format!(
4579                "expected SELECT / CREATE / DROP / INSERT / UPDATE / DELETE / ALTER / BEGIN / COMMIT / \
4580                 ROLLBACK / SAVEPOINT / RELEASE / SHOW at start of statement, got {other:?}"
4581            ))),
4582        }
4583    }
4584
4585    /// v7.39 (round 218) — `DECLARE <name> [BINARY] [INSENSITIVE] [ASENSITIVE]
4586    /// [[NO] SCROLL] CURSOR [{WITH|WITHOUT} HOLD] FOR <select>`. BINARY /
4587    /// (IN|A)SENSITIVE are accepted and ignored (SPG cursors materialize at
4588    /// DECLARE, which is INSENSITIVE — PG's only actual behaviour too).
4589    fn parse_declare_cursor(&mut self) -> Result<Statement, ParseError> {
4590        self.advance(); // DECLARE
4591        let name = match self.advance() {
4592            Token::Ident(n) | Token::QuotedIdent(n) => n,
4593            other => {
4594                return Err(self.err(format!("expected cursor name after DECLARE, got {other:?}")));
4595            }
4596        };
4597        let mut scroll: Option<bool> = None;
4598        loop {
4599            match self.peek() {
4600                Token::Ident(s)
4601                    if s.eq_ignore_ascii_case("binary")
4602                        || s.eq_ignore_ascii_case("insensitive")
4603                        || s.eq_ignore_ascii_case("asensitive") =>
4604                {
4605                    self.advance();
4606                }
4607                Token::Ident(s) if s.eq_ignore_ascii_case("scroll") => {
4608                    self.advance();
4609                    scroll = Some(true);
4610                }
4611                Token::Not | Token::Ident(_) if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("no")) =>
4612                {
4613                    self.advance(); // NO
4614                    if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("scroll")) {
4615                        return Err(self.err(format!(
4616                            "expected SCROLL after NO in DECLARE, got {:?}",
4617                            self.peek()
4618                        )));
4619                    }
4620                    self.advance();
4621                    scroll = Some(false);
4622                }
4623                _ => break,
4624            }
4625        }
4626        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("cursor")) {
4627            return Err(self.err(format!("expected CURSOR in DECLARE, got {:?}", self.peek())));
4628        }
4629        self.advance();
4630        let mut hold = false;
4631        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("with")) {
4632            self.advance();
4633            if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("hold")) {
4634                return Err(self.err(format!(
4635                    "expected HOLD after WITH in DECLARE, got {:?}",
4636                    self.peek()
4637                )));
4638            }
4639            self.advance();
4640            hold = true;
4641        } else if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("without")) {
4642            self.advance();
4643            if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("hold")) {
4644                return Err(self.err(format!(
4645                    "expected HOLD after WITHOUT in DECLARE, got {:?}",
4646                    self.peek()
4647                )));
4648            }
4649            self.advance();
4650        }
4651        if !matches!(self.peek(), Token::For) {
4652            return Err(self.err(format!(
4653                "expected FOR before the cursor query, got {:?}",
4654                self.peek()
4655            )));
4656        }
4657        self.advance();
4658        let query = self.parse_one_statement()?;
4659        Ok(Statement::DeclareCursor {
4660            name,
4661            scroll,
4662            hold,
4663            query: alloc::boxed::Box::new(query),
4664        })
4665    }
4666
4667    /// v7.39 (round 218) — `FETCH`/`MOVE` `[<direction>] [FROM|IN] <name>`.
4668    /// Direction: NEXT | PRIOR | FIRST | LAST | ABSOLUTE n | RELATIVE n | n |
4669    /// ALL | FORWARD [n|ALL] | BACKWARD [n|ALL]; bare `FETCH <name>` = NEXT.
4670    fn parse_fetch_or_move(&mut self, is_move: bool) -> Result<Statement, ParseError> {
4671        use crate::ast::CursorDirection as D;
4672        self.advance(); // FETCH / MOVE
4673        let mut signed_count = |this: &mut Self| -> Result<i64, ParseError> {
4674            let neg = if matches!(this.peek(), Token::Minus) {
4675                this.advance();
4676                true
4677            } else {
4678                false
4679            };
4680            match this.advance() {
4681                Token::Integer(v) => Ok(if neg { -v } else { v }),
4682                other => Err(this.err(format!("expected count, got {other:?}"))),
4683            }
4684        };
4685        let direction = match self.peek().clone() {
4686            Token::Ident(s) if s.eq_ignore_ascii_case("next") => {
4687                self.advance();
4688                D::Next
4689            }
4690            Token::Ident(s) if s.eq_ignore_ascii_case("prior") => {
4691                self.advance();
4692                D::Prior
4693            }
4694            Token::Ident(s) if s.eq_ignore_ascii_case("first") => {
4695                self.advance();
4696                D::First
4697            }
4698            Token::Ident(s) if s.eq_ignore_ascii_case("last") => {
4699                self.advance();
4700                D::Last
4701            }
4702            Token::Ident(s) if s.eq_ignore_ascii_case("absolute") => {
4703                self.advance();
4704                D::Absolute(signed_count(self)?)
4705            }
4706            Token::Ident(s) if s.eq_ignore_ascii_case("relative") => {
4707                self.advance();
4708                D::Relative(signed_count(self)?)
4709            }
4710            Token::Ident(s) if s.eq_ignore_ascii_case("forward") => {
4711                self.advance();
4712                match self.peek().clone() {
4713                    Token::All => {
4714                        self.advance();
4715                        D::All
4716                    }
4717                    Token::Ident(s) if s.eq_ignore_ascii_case("all") => {
4718                        self.advance();
4719                        D::All
4720                    }
4721                    Token::Integer(_) | Token::Minus => D::Count(signed_count(self)?),
4722                    _ => D::Next, // bare FORWARD = FORWARD 1
4723                }
4724            }
4725            Token::Ident(s) if s.eq_ignore_ascii_case("backward") => {
4726                self.advance();
4727                match self.peek().clone() {
4728                    Token::All => {
4729                        self.advance();
4730                        D::BackwardAll
4731                    }
4732                    Token::Ident(s) if s.eq_ignore_ascii_case("all") => {
4733                        self.advance();
4734                        D::BackwardAll
4735                    }
4736                    Token::Integer(_) | Token::Minus => D::Backward(signed_count(self)?),
4737                    _ => D::Backward(1), // bare BACKWARD = BACKWARD 1
4738                }
4739            }
4740            Token::All => {
4741                self.advance();
4742                D::All
4743            }
4744            Token::Ident(s) if s.eq_ignore_ascii_case("all") => {
4745                self.advance();
4746                D::All
4747            }
4748            Token::Integer(_) | Token::Minus => D::Count(signed_count(self)?),
4749            // Bare `FETCH <name>` — direction defaults to NEXT.
4750            _ => D::Next,
4751        };
4752        // Optional FROM / IN.
4753        if matches!(self.peek(), Token::From)
4754            || matches!(self.peek(), Token::In)
4755            || matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("in"))
4756        {
4757            self.advance();
4758        }
4759        let name = match self.advance() {
4760            Token::Ident(n) | Token::QuotedIdent(n) => n,
4761            other => {
4762                return Err(self.err(format!("expected cursor name, got {other:?}")));
4763            }
4764        };
4765        Ok(if is_move {
4766            Statement::MoveCursor { name, direction }
4767        } else {
4768            Statement::FetchCursor { name, direction }
4769        })
4770    }
4771
4772    /// v7.39 (round 280) — `CREATE STATISTICS [IF NOT EXISTS] <name>
4773    /// [(kind, …)] ON <col>, … FROM <table>`.
4774    fn parse_create_statistics_after_create(&mut self) -> Result<Statement, ParseError> {
4775        self.advance(); // STATISTICS
4776        // `IF` / `EXISTS` lex as plain identifiers; only NOT is a keyword.
4777        let mut if_not_exists = false;
4778        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("if"))
4779            && matches!(self.tokens.get(self.pos + 1), Some(Token::Not))
4780        {
4781            self.advance();
4782            self.advance();
4783            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("exists")) {
4784                self.advance();
4785                if_not_exists = true;
4786            }
4787        }
4788        let name = self.expect_ident_like()?;
4789        let mut kinds = Vec::new();
4790        if matches!(self.peek(), Token::LParen) {
4791            self.advance();
4792            loop {
4793                let k = self.expect_ident_like()?;
4794                // PG stores the single letters; accept the spelled-out
4795                // names the SQL uses and record what PG records.
4796                kinds.push(match k.to_ascii_lowercase().as_str() {
4797                    "ndistinct" => String::from("d"),
4798                    "dependencies" => String::from("f"),
4799                    "mcv" => String::from("m"),
4800                    other => {
4801                        return Err(
4802                            self.err(alloc::format!("unrecognized statistics kind \"{other}\""))
4803                        );
4804                    }
4805                });
4806                match self.advance() {
4807                    Token::Comma => {}
4808                    Token::RParen => break,
4809                    other => {
4810                        return Err(self.err(alloc::format!(
4811                            "expected ',' or ')' in statistics kind list, got {other:?}"
4812                        )));
4813                    }
4814                }
4815            }
4816        }
4817        if !matches!(self.peek(), Token::On) {
4818            return Err(self.err(alloc::format!(
4819                "expected ON in CREATE STATISTICS, got {:?}",
4820                self.peek()
4821            )));
4822        }
4823        self.advance();
4824        let mut columns = Vec::new();
4825        loop {
4826            columns.push(self.expect_ident_like()?);
4827            if matches!(self.peek(), Token::Comma) {
4828                self.advance();
4829            } else {
4830                break;
4831            }
4832        }
4833        if !matches!(self.peek(), Token::From) {
4834            return Err(self.err(alloc::format!(
4835                "expected FROM in CREATE STATISTICS, got {:?}",
4836                self.peek()
4837            )));
4838        }
4839        self.advance();
4840        let table = self.expect_ident_like()?;
4841        Ok(Statement::CreateStatistics {
4842            name,
4843            if_not_exists,
4844            kinds,
4845            columns,
4846            table,
4847        })
4848    }
4849
4850    /// v7.39 (round 280) — `DROP STATISTICS [IF EXISTS] <name>`.
4851    /// v7.39 (round 436) — the body of `DROP TABLE [IF EXISTS] a[, b] …`,
4852    /// entered with the `TABLE` keyword still unconsumed. Extracted so
4853    /// `DROP TEMPORARY TABLE` (MySQL) runs the identical grammar instead of
4854    /// a second copy — the parser cannot rewind, so re-dispatch has to be a
4855    /// forward call.
4856    fn parse_drop_table_after_keyword(&mut self) -> Result<Statement, ParseError> {
4857        self.advance(); // TABLE
4858        let if_exists = self.consume_if_exists();
4859        let mut names: Vec<String> = Vec::new();
4860        loop {
4861            names.push(self.expect_ident_like()?);
4862            if matches!(self.peek(), Token::Comma) {
4863                self.advance();
4864                continue;
4865            }
4866            break;
4867        }
4868        if matches!(
4869            self.peek(),
4870            Token::Ident(s) if s.eq_ignore_ascii_case("cascade")
4871                || s.eq_ignore_ascii_case("restrict")
4872        ) {
4873            self.advance();
4874        }
4875        Ok(Statement::DropTable { names, if_exists })
4876    }
4877
4878    fn parse_drop_statistics_after_drop(&mut self) -> Result<Statement, ParseError> {
4879        self.advance(); // STATISTICS
4880        let mut if_exists = false;
4881        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("if"))
4882            && matches!(self.tokens.get(self.pos + 1),
4883                        Some(Token::Ident(e)) if e.eq_ignore_ascii_case("exists"))
4884        {
4885            self.advance();
4886            self.advance();
4887            if_exists = true;
4888        }
4889        let name = self.expect_ident_like()?;
4890        Ok(Statement::DropStatistics { name, if_exists })
4891    }
4892
4893    fn parse_create_stmt(&mut self) -> Result<Statement, ParseError> {
4894        debug_assert!(matches!(self.peek(), Token::Create));
4895        self.advance();
4896        match self.peek() {
4897            Token::Table => self.parse_create_table_stmt_after_create(),
4898            Token::Index => self.parse_create_index_stmt_after_create(false),
4899            // v7.39 (round 280) — CREATE STATISTICS is a real catalog
4900            // object now. It used to be consumed by the CREATE-noise
4901            // arm, so a pg_dump that declares extended statistics
4902            // restored silently without them and reflection showed
4903            // nothing.
4904            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("statistics") => {
4905                self.parse_create_statistics_after_create()
4906            }
4907            // v7.9.29 — `CREATE UNIQUE INDEX … [WHERE pred]`.
4908            // The `UNIQUE` modifier turns a partial index into a
4909            // partial-uniqueness invariant (only rows matching the
4910            // WHERE predicate are checked for duplicates). mailrs
4911            // K1 (3 hits: email_templates default, calendar_events
4912            // master, calendar_events instance).
4913            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("unique") => {
4914                self.advance();
4915                if !matches!(self.peek(), Token::Index) {
4916                    return Err(self.err(alloc::format!(
4917                        "expected INDEX after CREATE UNIQUE, got {:?}",
4918                        self.peek()
4919                    )));
4920                }
4921                self.parse_create_index_stmt_after_create(true)
4922            }
4923            Token::Publication => {
4924                self.advance();
4925                self.parse_create_publication_after_keyword()
4926            }
4927            Token::Subscription => {
4928                self.advance();
4929                self.parse_create_subscription_after_keyword()
4930            }
4931            // v4.1: CREATE USER 'name' WITH PASSWORD 'pw' [ROLE 'role'].
4932            // USER isn't a reserved keyword — we look for the bare
4933            // identifier so the lexer doesn't have to grow a token.
4934            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("user") => {
4935                self.advance();
4936                self.parse_create_user_after_keyword(true)
4937            }
4938            // v7.39 (read01 round 58) — `CREATE ROLE name [WITH] [options]`.
4939            // PG's CREATE USER *is* CREATE ROLE … LOGIN; the only difference is
4940            // the default of the LOGIN attribute.
4941            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("role") => {
4942                self.advance();
4943                self.parse_create_user_after_keyword(false)
4944            }
4945            // v7.39 (RLS) — `CREATE POLICY name ON table …`.
4946            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("policy") => {
4947                self.advance();
4948                self.parse_create_policy_after_keyword()
4949            }
4950            // v7.9.15 — `CREATE EXTENSION [IF NOT EXISTS] <name>
4951            // [WITH SCHEMA …] [VERSION '…'] [CASCADE]` as a
4952            // no-op. mailrs follow-up F3.
4953            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("extension") => {
4954                self.advance();
4955                self.parse_create_extension_after_keyword()
4956            }
4957            // v7.12.4 — `CREATE [OR REPLACE] FUNCTION …` and
4958            // `CREATE [OR REPLACE] TRIGGER …`. `OR REPLACE` is
4959            // optional; absorb it here and forward to the
4960            // per-kind parsers with the flag. OR is a reserved
4961            // keyword token.
4962            Token::Or => {
4963                self.advance();
4964                let next = self.peek();
4965                let (Token::Ident(s2) | Token::QuotedIdent(s2)) = next else {
4966                    return Err(self.err(alloc::format!(
4967                        "expected REPLACE after CREATE OR, got {next:?}"
4968                    )));
4969                };
4970                if !s2.eq_ignore_ascii_case("replace") {
4971                    return Err(self.err(alloc::format!(
4972                        "expected REPLACE after CREATE OR, got {s2:?}"
4973                    )));
4974                }
4975                self.advance();
4976                self.parse_create_function_or_trigger_after_or_replace(true)
4977            }
4978            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("function") => {
4979                self.advance();
4980                self.parse_create_function_after_keyword(false)
4981            }
4982            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("trigger") => {
4983                self.advance();
4984                self.parse_create_trigger_after_keyword(false)
4985            }
4986            // v7.39 (round 139) — CREATE RULE …
4987            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("rule") => {
4988                self.advance();
4989                self.parse_create_rule_after_keyword(false)
4990            }
4991            // v7.39 (read01 round 82) — CREATE CONSTRAINT TRIGGER. A constraint
4992            // trigger is a row-level AFTER trigger that additionally carries
4993            // DEFERRABLE / INITIALLY DEFERRED timing; the `parse_create_trigger`
4994            // path already tolerates and skips those clauses, so consuming the
4995            // CONSTRAINT keyword and reusing it makes the statement parse and the
4996            // trigger fire. (The deferral timing itself is not yet honoured —
4997            // SPG fires it as a plain AFTER trigger, which is correct behaviour
4998            // for every non-deferred use.)
4999            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("constraint") => {
5000                self.advance();
5001                if !matches!(self.peek(), Token::Ident(t) | Token::QuotedIdent(t)
5002                    if t.eq_ignore_ascii_case("trigger"))
5003                {
5004                    return Err(self.err(alloc::format!(
5005                        "expected TRIGGER after CREATE CONSTRAINT, got {:?}",
5006                        self.peek()
5007                    )));
5008                }
5009                self.advance();
5010                self.parse_create_trigger_after_keyword(false)
5011            }
5012            // v7.17.0 — CREATE [TEMPORARY] SEQUENCE …
5013            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("sequence") => {
5014                self.advance();
5015                self.parse_create_sequence_after_keyword(false)
5016            }
5017            // v7.17.0 Phase 1.2 — CREATE [TEMPORARY] VIEW …
5018            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("view") => {
5019                self.advance();
5020                self.parse_create_view_after_keyword(false, false, false)
5021            }
5022            // v7.17.0 Phase 2.6 — MySQL view prefix clauses
5023            // `ALGORITHM = {UNDEFINED|MERGE|TEMPTABLE}` /
5024            // `DEFINER = <user>` / `SQL SECURITY {DEFINER|INVOKER}`
5025            // appear (in any order) between `CREATE` and `VIEW` in
5026            // every mysqldump-emitted view. Pre-2.6 the parser
5027            // rejected the prefix and the customer's whole view
5028            // backup failed on the first view. The hints are pure
5029            // planner / permission metadata; SPG's view-rewrite
5030            // path is semantically equivalent for all three
5031            // algorithms in v7.17 (TEMPTABLE differs only in
5032            // perf for huge views — out of v7.17 scope), and
5033            // DEFINER / SQL SECURITY are pure single-user
5034            // permissioning that SPG ignores by design.
5035            Token::Ident(s) | Token::QuotedIdent(s)
5036                if s.eq_ignore_ascii_case("algorithm")
5037                    || s.eq_ignore_ascii_case("definer")
5038                    || s.eq_ignore_ascii_case("sql") =>
5039            {
5040                self.consume_mysql_view_prefix()?;
5041                // After absorbing ALGORITHM / DEFINER / SQL SECURITY
5042                // (in any order, in any combination), the next
5043                // keyword must be VIEW. mysqldump never emits these
5044                // prefixes on non-view statements.
5045                let next = self.peek().clone();
5046                if matches!(&next, Token::Ident(s2) | Token::QuotedIdent(s2)
5047                    if s2.eq_ignore_ascii_case("view"))
5048                {
5049                    self.advance();
5050                    self.parse_create_view_after_keyword(false, false, false)
5051                } else {
5052                    Err(self.err(alloc::format!(
5053                        "expected VIEW after MySQL view prefix (ALGORITHM/DEFINER/SQL SECURITY), got {next:?}"
5054                    )))
5055                }
5056            }
5057            // v7.17.0 Phase 1.4 — CREATE TYPE name AS ENUM (…).
5058            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("type") => {
5059                self.advance();
5060                self.parse_create_type_after_keyword()
5061            }
5062            // v7.17.0 Phase 1.5 — CREATE DOMAIN name AS base
5063            // [DEFAULT expr] [NOT NULL] [CHECK (expr)]*.
5064            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("domain") => {
5065                self.advance();
5066                self.parse_create_domain_after_keyword()
5067            }
5068            // v7.17.0 Phase 1.6 — CREATE SCHEMA [IF NOT EXISTS]
5069            // name [AUTHORIZATION user]. Real catalog registry
5070            // (was silent-no-op'd pre-v7.17).
5071            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("schema") => {
5072                self.advance();
5073                let if_not_exists = self.parse_if_not_exists();
5074                let name = self.expect_ident_like()?;
5075                // Optional `AUTHORIZATION <user>` trailer — accepted,
5076                // ignored (single-user catalog).
5077                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
5078                    if s.eq_ignore_ascii_case("authorization"))
5079                {
5080                    self.advance();
5081                    let _ = self.expect_ident_like()?;
5082                }
5083                Ok(Statement::CreateSchema { name, if_not_exists })
5084            }
5085            // v7.17.0 Phase 1.3 — CREATE MATERIALIZED VIEW …
5086            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("materialized") => {
5087                self.advance();
5088                let next = self.peek().clone();
5089                if matches!(&next, Token::Ident(s2) | Token::QuotedIdent(s2) if s2.eq_ignore_ascii_case("view"))
5090                {
5091                    self.advance();
5092                    self.parse_create_materialized_view_after_keyword()
5093                } else {
5094                    Err(self.err(alloc::format!(
5095                        "expected VIEW after CREATE MATERIALIZED, got {next:?}"
5096                    )))
5097                }
5098            }
5099            // v7.38 (read01 P6.57) — CREATE UNLOGGED TABLE. Unlike TEMP (a
5100            // no-op below), an UNLOGGED table is a real, fully-usable table in
5101            // PG — it only skips WAL. SPG creates a normal table (the WAL-skip
5102            // durability optimisation is a follow-up), so a dump / app that
5103            // declares UNLOGGED tables works instead of failing to parse.
5104            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("unlogged") => {
5105                self.advance(); // UNLOGGED
5106                if matches!(self.peek(), Token::Table) {
5107                    self.parse_create_table_stmt_after_create()
5108                } else {
5109                    Err(self.err(format!(
5110                        "expected TABLE after CREATE UNLOGGED, got {:?}",
5111                        self.peek()
5112                    )))
5113                }
5114            }
5115            Token::Ident(s) | Token::QuotedIdent(s)
5116                if s.eq_ignore_ascii_case("temporary") || s.eq_ignore_ascii_case("temp") =>
5117            {
5118                self.advance();
5119                // TEMPORARY/TEMP followed by SEQUENCE / VIEW.
5120                let next = self.peek().clone();
5121                if matches!(&next, Token::Ident(s2) | Token::QuotedIdent(s2) if s2.eq_ignore_ascii_case("sequence"))
5122                {
5123                    self.advance();
5124                    self.parse_create_sequence_after_keyword(true)
5125                } else if matches!(&next, Token::Ident(s2) | Token::QuotedIdent(s2) if s2.eq_ignore_ascii_case("view"))
5126                {
5127                    self.advance();
5128                    self.parse_create_view_after_keyword(false, false, true)
5129                } else {
5130                    // v7.39 (round 436) — `CREATE TEMPORARY TABLE` used to be
5131                    // consumed and answered OK while creating nothing, so
5132                    // every statement that touched the table afterwards failed
5133                    // with "table not found" — the DDL itself lied. It is a
5134                    // real CREATE TABLE now, marked temporary so the executor
5135                    // puts it in the session's own namespace. An optional
5136                    // TABLE keyword may or may not be present (`CREATE TEMP t`
5137                    // is not legal, but the keyword is consumed by the
5138                    // CREATE TABLE parser itself).
5139                    let stmt = self.parse_create_table_stmt_after_create()?;
5140                    match stmt {
5141                        Statement::CreateTable(mut c) => {
5142                            c.temporary = true;
5143                            Ok(Statement::CreateTable(c))
5144                        }
5145                        // `CREATE TEMPORARY TABLE x AS <select>` lowers to the
5146                        // CTAS node, which needs the same session namespace.
5147                        Statement::CreateMaterializedView(mut m) if m.as_plain_table => {
5148                            m.temporary = true;
5149                            Ok(Statement::CreateMaterializedView(m))
5150                        }
5151                        other => Ok(other),
5152                    }
5153                }
5154            }
5155            // v7.17.0 Phase 4.2 — MySQL `CREATE PROCEDURE name (…)
5156            // BEGIN <body> END`. The body may reference `@var`
5157            // session variables, SET statements, internal `;`
5158            // terminators, etc. SPG has no procedure runtime, so
5159            // consume the whole `CREATE PROCEDURE … END` block as
5160            // a no-op so mysqldump scripts that include stored
5161            // routines load through. The matching-END consumer
5162            // tracks BEGIN/END nesting depth to handle nested
5163            // BEGIN blocks correctly.
5164            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("procedure") => {
5165                self.consume_mysql_routine_body();
5166                Ok(Statement::Empty)
5167            }
5168            // v7.14.0 — pg_dump / mysqldump emit
5169            // `CREATE SCHEMA / VIEW / MATERIALIZED VIEW /
5170            // TYPE / DOMAIN / DATABASE / ROLE / POLICY / OPERATOR`.
5171            // SPG is single-schema / single-database; these have
5172            // no behavioural effect, so consume + return Empty.
5173            // v7.17.0 NOTE: SEQUENCE / VIEW / MATERIALIZED VIEW /
5174            // TYPE / DOMAIN / SCHEMA were here pre-v7.17; all
5175            // moved up to real parser branches. DATABASE / ROLE /
5176            // POLICY / OPERATOR stay no-op forever
5177            // (single-database, hardcoded roles).
5178            Token::Ident(s) | Token::QuotedIdent(s)
5179                if matches!(
5180                    s.to_ascii_lowercase().as_str(),
5181                    "database"
5182                        | "role"
5183                        | "operator"
5184                        | "cast"
5185                        | "aggregate"
5186                        | "language"
5187                        | "collation"
5188                        | "conversion"
5189                        // v7.17.0 Phase 8 (audit N6) — rarely-
5190                        // emitted pg_dump shapes that should
5191                        // load through without a parser error.
5192                        // SPG has no planner statistics catalog,
5193                        // no event-trigger hooks, no foreign-
5194                        // data-wrapper infrastructure; consume
5195                        // + return Empty.
5196                        | "statistics"
5197                        | "event"
5198                        // v7.37.17 (17.6 siblings) — additional CREATE
5199                        // targets pg_dump / operator install scripts
5200                        // may emit that SPG has no matching machinery
5201                        // for. Consume + Empty-return.
5202                        | "text"
5203                        | "tablespace"
5204                        | "access"
5205                        | "large"
5206                ) =>
5207            {
5208                // DATABASE is the one member of this list PG refuses
5209                // inside a transaction block; the rest (ROLE, CAST,
5210                // TABLESPACE, …) it runs there quite happily, so only
5211                // this one is named. Still a no-op otherwise — SPG is
5212                // single-database.
5213                let is_database = s.eq_ignore_ascii_case("database");
5214                // The name is the first token after DATABASE, past an
5215                // `IF NOT EXISTS`.
5216                let name = if is_database {
5217                    self.scan_database_name()
5218                } else {
5219                    None
5220                };
5221                let collation = if is_database {
5222                    self.scan_database_collation_until_boundary()
5223                } else {
5224                    self.consume_until_statement_boundary();
5225                    None
5226                };
5227                if is_database {
5228                    return Ok(Statement::NoOpPreventedInTransaction {
5229                        what: String::from("CREATE DATABASE"),
5230                        collation,
5231                        name,
5232                    });
5233                }
5234                Ok(Statement::Empty)
5235            }
5236            // v7.39 (round 706) — the foreign-data family leaves the silent
5237            // list: `CREATE SERVER …`, `CREATE FOREIGN TABLE …`, `CREATE
5238            // FOREIGN DATA WRAPPER …` are still consumed whole (SPG has no
5239            // FDW machinery), but the ENGINE now warns, so a restore log
5240            // says what will not function instead of reporting success.
5241            Token::Ident(s) | Token::QuotedIdent(s)
5242                if s.eq_ignore_ascii_case("server") || s.eq_ignore_ascii_case("foreign") =>
5243            {
5244                self.consume_until_statement_boundary();
5245                Ok(Statement::ValidateOnly {
5246                    kind: crate::ast::ValidateOnlyKind::ForeignInfra,
5247                    names: Vec::new(),
5248                })
5249            }
5250            other => Err(self.err(format!(
5251                "expected TABLE / INDEX / USER / EXTENSION / PUBLICATION / SUBSCRIPTION / FUNCTION / TRIGGER / SEQUENCE / SCHEMA / VIEW / TYPE / DOMAIN [OR REPLACE …] after CREATE, got {other:?}"
5252            ))),
5253        }
5254    }
5255
5256    /// v7.12.4 — `CREATE OR REPLACE` already consumed; the next
5257    /// keyword decides whether we parse a function or trigger
5258    /// body. PG accepts other `OR REPLACE`-able objects (VIEW,
5259    /// PROCEDURE) — those land in later releases.
5260    fn parse_create_function_or_trigger_after_or_replace(
5261        &mut self,
5262        or_replace: bool,
5263    ) -> Result<Statement, ParseError> {
5264        let tok = self.peek();
5265        let (Token::Ident(s) | Token::QuotedIdent(s)) = tok else {
5266            return Err(self.err(alloc::format!(
5267                "expected FUNCTION / TRIGGER / RULE / VIEW after CREATE OR REPLACE, got {tok:?}"
5268            )));
5269        };
5270        if s.eq_ignore_ascii_case("function") {
5271            self.advance();
5272            self.parse_create_function_after_keyword(or_replace)
5273        } else if s.eq_ignore_ascii_case("trigger") {
5274            self.advance();
5275            self.parse_create_trigger_after_keyword(or_replace)
5276        } else if s.eq_ignore_ascii_case("rule") {
5277            // v7.39 (round 143) — CREATE OR REPLACE RULE name AS ON …
5278            self.advance();
5279            self.parse_create_rule_after_keyword(or_replace)
5280        } else if s.eq_ignore_ascii_case("view") {
5281            // v7.17.0 Phase 1.2 — CREATE OR REPLACE VIEW name AS SELECT …
5282            self.advance();
5283            self.parse_create_view_after_keyword(or_replace, false, false)
5284        } else if s.eq_ignore_ascii_case("temporary") || s.eq_ignore_ascii_case("temp") {
5285            // CREATE OR REPLACE TEMPORARY VIEW … (rare but legal).
5286            self.advance();
5287            let nxt = self.peek().clone();
5288            if matches!(&nxt, Token::Ident(n) | Token::QuotedIdent(n) if n.eq_ignore_ascii_case("view"))
5289            {
5290                self.advance();
5291                self.parse_create_view_after_keyword(or_replace, false, true)
5292            } else {
5293                Err(self.err(alloc::format!(
5294                    "expected VIEW after CREATE OR REPLACE TEMPORARY, got {nxt:?}"
5295                )))
5296            }
5297        } else {
5298            Err(self.err(alloc::format!(
5299                "expected FUNCTION / TRIGGER / RULE / VIEW after CREATE OR REPLACE, got {s:?}"
5300            )))
5301        }
5302    }
5303
5304    /// v7.9.15 — accept and discard `CREATE EXTENSION` DDL.
5305    /// SPG doesn't have a registry; pgvector / similar are
5306    /// either builtin (VECTOR(N) ↔ pgvector) or n/a. Parsing
5307    /// the syntax lets dual-target schemas keep the line.
5308    fn parse_create_extension_after_keyword(&mut self) -> Result<Statement, ParseError> {
5309        // Optional `IF NOT EXISTS`.
5310        self.consume_if_not_exists();
5311        let name = self.expect_ident_like()?;
5312        // Drain optional WITH SCHEMA <ident> / VERSION '<v>' /
5313        // CASCADE / FROM '<v>' clauses; we don't model them.
5314        loop {
5315            match self.peek() {
5316                Token::Ident(s) if s.eq_ignore_ascii_case("with") => {
5317                    self.advance();
5318                    continue;
5319                }
5320                Token::Ident(s) if s.eq_ignore_ascii_case("schema") => {
5321                    self.advance();
5322                    let _ = self.expect_ident_like()?;
5323                    continue;
5324                }
5325                Token::Ident(s) if s.eq_ignore_ascii_case("version") => {
5326                    self.advance();
5327                    // String or ident literal.
5328                    let _ = self.advance();
5329                    continue;
5330                }
5331                Token::Ident(s) if s.eq_ignore_ascii_case("from") => {
5332                    self.advance();
5333                    let _ = self.advance();
5334                    continue;
5335                }
5336                Token::Ident(s) if s.eq_ignore_ascii_case("cascade") => {
5337                    self.advance();
5338                    continue;
5339                }
5340                _ => break,
5341            }
5342        }
5343        // v7.39 (round 697) — the NAME is checked now. `CREATE EXTENSION
5344        // nosuch` reported success and `pg_extension` then did not list it,
5345        // which is the accept-and-do-nothing shape F31 exists to find.
5346        Ok(Statement::ValidateOnly {
5347            kind: crate::ast::ValidateOnlyKind::ExtensionAvailable,
5348            names: alloc::vec![name],
5349        })
5350    }
5351
5352    /// v7.12.4 — body of `CREATE [OR REPLACE] FUNCTION`. The
5353    /// `[OR REPLACE]` flag (and the `FUNCTION` keyword) have
5354    /// already been consumed by the caller. Grammar accepted:
5355    ///
5356    ///   name `(` arg-list `)`
5357    ///   `RETURNS` return-type
5358    ///   [ `LANGUAGE` ident ]
5359    ///   `AS` $$ body $$
5360    ///   [ `LANGUAGE` ident ]
5361    ///
5362    /// Either `LANGUAGE` position is allowed; PG accepts both.
5363    fn parse_create_function_after_keyword(
5364        &mut self,
5365        or_replace: bool,
5366    ) -> Result<Statement, ParseError> {
5367        let name = self.expect_ident_like()?;
5368        // Argument list. v7.12.4 commonly sees the empty `()`
5369        // (trigger functions); typed args parse and round-trip
5370        // but the executor only invokes nullary functions.
5371        if !matches!(self.peek(), Token::LParen) {
5372            return Err(self.err(alloc::format!(
5373                "expected '(' after function name {name:?}, got {:?}",
5374                self.peek()
5375            )));
5376        }
5377        self.advance();
5378        let args = self.parse_function_arg_list()?;
5379        // RETURNS clause.
5380        let tok = self.peek();
5381        let (Token::Ident(s) | Token::QuotedIdent(s)) = tok else {
5382            return Err(self.err(alloc::format!(
5383                "expected RETURNS after function arg list, got {tok:?}"
5384            )));
5385        };
5386        if !s.eq_ignore_ascii_case("returns") {
5387            return Err(self.err(alloc::format!(
5388                "expected RETURNS after function arg list, got {s:?}"
5389            )));
5390        }
5391        self.advance();
5392        let returns = self.parse_function_return()?;
5393        // Optional LANGUAGE clause (PG also accepts after AS — we'll
5394        // re-check after the body too).
5395        let mut language: Option<String> = self.parse_optional_language()?;
5396        // v7.39 (round 322, V46) — attribute clauses. PG allows them on
5397        // either side of the body and in any order, interleaved with
5398        // LANGUAGE; `CREATE FUNCTION f() RETURNS int LANGUAGE sql
5399        // IMMUTABLE STRICT AS $$…$$` used to be a parse error, which meant
5400        // PG's own pg_dump output did not restore.
5401        let mut attrs = FunctionAttrs::default();
5402        loop {
5403            let before = self.pos;
5404            self.parse_function_attrs_into(&mut attrs)?;
5405            if language.is_none() {
5406                language = self.parse_optional_language()?;
5407            }
5408            if self.pos == before {
5409                break;
5410            }
5411        }
5412        // `AS` followed by a $$-quoted body (lexer already
5413        // collapses both `$$…$$` and `$tag$…$tag$` to a single
5414        // Token::String). AS is a reserved keyword (Token::As).
5415        if !matches!(self.peek(), Token::As) {
5416            return Err(self.err(alloc::format!(
5417                "expected AS before function body, got {:?}",
5418                self.peek()
5419            )));
5420        }
5421        self.advance();
5422        let body_text = match self.peek() {
5423            Token::String(s) => {
5424                let body = s.clone();
5425                self.advance();
5426                body
5427            }
5428            other => {
5429                return Err(self.err(alloc::format!(
5430                    "expected $$-quoted function body after AS, got {other:?}"
5431                )));
5432            }
5433        };
5434        // Trailing clauses — PG's other accepted position for both the
5435        // LANGUAGE and the attributes.
5436        loop {
5437            let before = self.pos;
5438            self.parse_function_attrs_into(&mut attrs)?;
5439            if language.is_none() {
5440                language = self.parse_optional_language()?;
5441            }
5442            if self.pos == before {
5443                break;
5444            }
5445        }
5446        let language = language.unwrap_or_else(|| String::from("sql"));
5447        // PL/pgSQL bodies get structure-parsed. Other languages
5448        // (or PL/pgSQL bodies the v7.12.4 parser doesn't yet
5449        // recognise) round-trip as Raw text — the executor errors
5450        // when invoked with a clear unsupported message.
5451        let body = if language.eq_ignore_ascii_case("plpgsql") {
5452            match parse_plpgsql_body(&body_text) {
5453                Ok(block) => FunctionBody::PlPgSql(block),
5454                // Best-effort: if the body parser doesn't yet
5455                // support a construct used inside, fall back to
5456                // raw — keeps `CREATE FUNCTION` itself working
5457                // (catalogue accepts), executor errors on
5458                // invocation only.
5459                Err(_) => FunctionBody::Raw(body_text),
5460            }
5461        } else {
5462            FunctionBody::Raw(body_text)
5463        };
5464        Ok(Statement::CreateFunction(CreateFunctionStatement {
5465            name,
5466            or_replace,
5467            args,
5468            returns,
5469            language,
5470            body,
5471            attrs,
5472        }))
5473    }
5474
5475    /// v7.39 (round 322, V46) — consume any run of `CREATE FUNCTION`
5476    /// attribute clauses into `attrs`, stopping at the first token that
5477    /// is not one. Measured against PG 18.4, which accepts them in any
5478    /// order and on either side of the body.
5479    fn parse_function_attrs_into(&mut self, attrs: &mut FunctionAttrs) -> Result<(), ParseError> {
5480        loop {
5481            let word = match self.peek() {
5482                Token::Ident(w) | Token::QuotedIdent(w) => w.to_ascii_lowercase(),
5483                // NOT LEAKPROOF — NOT is a reserved keyword token.
5484                Token::Not
5485                    if matches!(
5486                        self.tokens.get(self.pos + 1),
5487                        Some(Token::Ident(w)) if w.eq_ignore_ascii_case("leakproof")
5488                    ) =>
5489                {
5490                    self.advance();
5491                    self.advance();
5492                    attrs.leakproof = false;
5493                    continue;
5494                }
5495                _ => return Ok(()),
5496            };
5497            match word.as_str() {
5498                "immutable" => {
5499                    self.advance();
5500                    attrs.volatility = FunctionVolatility::Immutable;
5501                }
5502                "stable" => {
5503                    self.advance();
5504                    attrs.volatility = FunctionVolatility::Stable;
5505                }
5506                "volatile" => {
5507                    self.advance();
5508                    attrs.volatility = FunctionVolatility::Volatile;
5509                }
5510                "strict" => {
5511                    self.advance();
5512                    attrs.strict = true;
5513                }
5514                "leakproof" => {
5515                    self.advance();
5516                    attrs.leakproof = true;
5517                }
5518                // RETURNS NULL ON NULL INPUT / CALLED ON NULL INPUT — the
5519                // spelled-out forms of STRICT and its opposite.
5520                "returns" | "called" => {
5521                    let strict = word == "returns";
5522                    let mut probe = self.pos + 1;
5523                    if strict {
5524                        // RETURNS *NULL* ON NULL INPUT; a bare RETURNS here
5525                        // is not ours.
5526                        match self.tokens.get(probe) {
5527                            Some(Token::Null) => probe += 1,
5528                            Some(Token::Ident(w)) if w.eq_ignore_ascii_case("null") => probe += 1,
5529                            _ => return Ok(()),
5530                        }
5531                    }
5532                    let ok = matches!(self.tokens.get(probe), Some(Token::On))
5533                        || matches!(self.tokens.get(probe), Some(Token::Ident(w)) if w.eq_ignore_ascii_case("on"));
5534                    if !ok {
5535                        return Ok(());
5536                    }
5537                    probe += 1;
5538                    match self.tokens.get(probe) {
5539                        Some(Token::Null) => probe += 1,
5540                        Some(Token::Ident(w)) if w.eq_ignore_ascii_case("null") => probe += 1,
5541                        _ => return Ok(()),
5542                    }
5543                    match self.tokens.get(probe) {
5544                        Some(Token::Ident(w)) if w.eq_ignore_ascii_case("input") => probe += 1,
5545                        _ => return Ok(()),
5546                    }
5547                    self.pos = probe;
5548                    attrs.strict = strict;
5549                }
5550                "security" | "external" => {
5551                    // [EXTERNAL] SECURITY { INVOKER | DEFINER }
5552                    let mut probe = self.pos + 1;
5553                    if word == "external" {
5554                        match self.tokens.get(probe) {
5555                            Some(Token::Ident(w)) if w.eq_ignore_ascii_case("security") => {
5556                                probe += 1;
5557                            }
5558                            _ => return Ok(()),
5559                        }
5560                    }
5561                    let definer = match self.tokens.get(probe) {
5562                        Some(Token::Ident(w)) if w.eq_ignore_ascii_case("definer") => true,
5563                        Some(Token::Ident(w)) if w.eq_ignore_ascii_case("invoker") => false,
5564                        _ => return Ok(()),
5565                    };
5566                    self.pos = probe + 1;
5567                    attrs.security_definer = definer;
5568                }
5569                "parallel" => {
5570                    let level = match self.tokens.get(self.pos + 1) {
5571                        Some(Token::Ident(w)) if w.eq_ignore_ascii_case("safe") => {
5572                            FunctionParallel::Safe
5573                        }
5574                        Some(Token::Ident(w)) if w.eq_ignore_ascii_case("restricted") => {
5575                            FunctionParallel::Restricted
5576                        }
5577                        Some(Token::Ident(w)) if w.eq_ignore_ascii_case("unsafe") => {
5578                            FunctionParallel::Unsafe
5579                        }
5580                        _ => return Ok(()),
5581                    };
5582                    self.pos += 2;
5583                    attrs.parallel = level;
5584                }
5585                "cost" | "rows" => {
5586                    let Some(n) = self.peek_number_at(self.pos + 1) else {
5587                        return Ok(());
5588                    };
5589                    self.pos += 2;
5590                    if word == "cost" {
5591                        attrs.cost = Some(n);
5592                    } else {
5593                        attrs.rows = Some(n);
5594                    }
5595                }
5596                _ => return Ok(()),
5597            }
5598        }
5599    }
5600
5601    /// The numeric literal at `idx`, if there is one.
5602    fn peek_number_at(&self, idx: usize) -> Option<f64> {
5603        match self.tokens.get(idx)? {
5604            Token::Integer(n) => Some(*n as f64),
5605            Token::Float(f) => Some(*f),
5606            Token::Numeric(t) => t.parse::<f64>().ok(),
5607            _ => None,
5608        }
5609    }
5610
5611    /// Closing `)`-terminated argument list. v7.12.4 commonly
5612    /// sees the empty `()`; typed args round-trip but the
5613    /// executor (yet) doesn't invoke them.
5614    /// v7.39 (round 344) — consume a `( n [, m] )` type modifier and throw
5615    /// it away, which is what PG does with one on a function parameter.
5616    fn skip_type_modifier(&mut self) {
5617        if !matches!(self.peek(), Token::LParen) {
5618            return;
5619        }
5620        // Only a numeric modifier — anything else is not one, and eating
5621        // it would swallow real grammar.
5622        let mut i = self.pos + 1;
5623        let mut seen_number = false;
5624        loop {
5625            match self.tokens.get(i) {
5626                Some(Token::Integer(_)) => seen_number = true,
5627                Some(Token::Comma) => {}
5628                Some(Token::RParen) => break,
5629                _ => return,
5630            }
5631            i += 1;
5632        }
5633        if !seen_number {
5634            return;
5635        }
5636        while self.pos <= i {
5637            self.advance();
5638        }
5639    }
5640
5641    fn parse_function_arg_list(&mut self) -> Result<Vec<FunctionArg>, ParseError> {
5642        let mut args: Vec<FunctionArg> = Vec::new();
5643        if matches!(self.peek(), Token::RParen) {
5644            self.advance();
5645            return Ok(args);
5646        }
5647        loop {
5648            // Optional `IN` / `OUT` / `INOUT` mode keyword. IN is
5649            // a reserved token; OUT / INOUT are bare idents.
5650            let mode = if matches!(self.peek(), Token::In) {
5651                self.advance();
5652                FunctionArgMode::In
5653            } else if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("out"))
5654            {
5655                self.advance();
5656                FunctionArgMode::Out
5657            } else if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("inout"))
5658            {
5659                self.advance();
5660                FunctionArgMode::InOut
5661            } else {
5662                FunctionArgMode::In
5663            };
5664            // Optional name. The next token is either a name
5665            // (followed by a type ident) or the type itself.
5666            // Disambiguate by peeking ahead: if the token after
5667            // the next ident is also an ident, we treat the
5668            // first as the name.
5669            // v7.39 (round 315, V19) — take EVERY ident-like word up to
5670            // the comma or paren, then decide. Reading at most two of
5671            // them could not spell `x double precision` at all, and
5672            // silently mis-read the bare `double precision` as a
5673            // parameter named "double" — which is what made the same
5674            // signature key two different ways.
5675            let (name, ty_token) = {
5676                let mut words: Vec<String> = alloc::vec![self.expect_ident_like()?];
5677                while matches!(self.peek(), Token::Ident(_) | Token::QuotedIdent(_)) {
5678                    words.push(self.expect_ident_like()?);
5679                }
5680                // v7.39 (round 344) — a length / precision modifier on the
5681                // type: `f(character varying(9))`, `f(numeric(10,2))`. PG
5682                // accepts it and DROPS it — `pg_get_function_arguments`
5683                // reports plain `character varying` / `numeric`, measured on
5684                // 18.4 — but SPG raised `syntax error at or near "("`,
5685                // because the modifier's parens were never consumed.
5686                self.skip_type_modifier();
5687                // r1049 — `f(v bigint[])`. The array suffix parsed in
5688                // the column position, the cast position and (r1038)
5689                // the RETURNS position, but not here: the fifth
5690                // member of the same family, reported by sentori as
5691                // presumably the same code. It is now.
5692                let array_suffix = self.consume_array_suffix();
5693                let whole = words.join(" ");
5694                let (name, mut ty_token) = if words.len() >= 2 && !is_multiword_type_phrase(&whole)
5695                {
5696                    (Some(words[0].clone()), words[1..].join(" "))
5697                } else {
5698                    (None, whole)
5699                };
5700                ty_token.push_str(&array_suffix);
5701                (name, ty_token)
5702            };
5703            // Type — try to map to ColumnTypeName, else Raw.
5704            let ty = match map_type_ident_to_column_type_name(&ty_token) {
5705                Some(t) => FunctionArgType::Typed(t),
5706                None => FunctionArgType::Raw(ty_token),
5707            };
5708            args.push(FunctionArg { mode, name, ty });
5709            match self.peek() {
5710                Token::Comma => {
5711                    self.advance();
5712                    continue;
5713                }
5714                Token::RParen => {
5715                    self.advance();
5716                    return Ok(args);
5717                }
5718                other => {
5719                    return Err(self.err(alloc::format!(
5720                        "expected , or ) in function arg list, got {other:?}"
5721                    )));
5722                }
5723            }
5724        }
5725    }
5726
5727    fn parse_function_return(&mut self) -> Result<FunctionReturn, ParseError> {
5728        // v7.39 (read01 round 65) — `RETURNS TABLE(col type, …)`: a set-returning
5729        // function whose row shape is named inline.
5730        if matches!(self.peek(), Token::Table)
5731            && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
5732        {
5733            self.advance(); // TABLE
5734            self.advance(); // (
5735            let mut cols: Vec<String> = Vec::new();
5736            loop {
5737                let cname = self.expect_ident_like()?;
5738                let mut ty: Vec<String> = Vec::new();
5739                loop {
5740                    match self.peek() {
5741                        Token::Comma | Token::RParen | Token::Eof => break,
5742                        _ => {}
5743                    }
5744                    match self.advance() {
5745                        Token::Ident(w) | Token::QuotedIdent(w) => ty.push(w),
5746                        other => {
5747                            if let Some(w) = unreserved_keyword_text(&other) {
5748                                ty.push(w);
5749                            }
5750                        }
5751                    }
5752                }
5753                cols.push(alloc::format!("{cname} {}", ty.join(" ")));
5754                if matches!(self.peek(), Token::Comma) {
5755                    self.advance();
5756                } else {
5757                    break;
5758                }
5759            }
5760            if matches!(self.peek(), Token::RParen) {
5761                self.advance();
5762            }
5763            return Ok(FunctionReturn::Other(alloc::format!(
5764                "TABLE({})",
5765                cols.join(", ")
5766            )));
5767        }
5768        let ident = self.expect_ident_like()?;
5769        // v7.39 (read01 round 65) — `RETURNS SETOF <type>`.
5770        if ident.eq_ignore_ascii_case("setof") {
5771            let inner = self.expect_ident_like()?;
5772            let inner = alloc::format!("{inner}{}", self.consume_array_suffix());
5773            return Ok(FunctionReturn::Other(alloc::format!("SETOF {inner}")));
5774        }
5775        if ident.eq_ignore_ascii_case("trigger") {
5776            return Ok(FunctionReturn::Trigger);
5777        }
5778        if ident.eq_ignore_ascii_case("void") {
5779            return Ok(FunctionReturn::Void);
5780        }
5781        // r1038 — `RETURNS bigint[]`. An array COLUMN type parsed; the
5782        // RETURN position did not, so the `[` was a syntax error and the
5783        // whole migration stopped. sentori worked around it by returning
5784        // zero-padded text.
5785        let suffix = self.consume_array_suffix();
5786        if !suffix.is_empty() {
5787            return Ok(FunctionReturn::Other(alloc::format!("{ident}{suffix}")));
5788        }
5789        match map_type_ident_to_column_type_name(&ident) {
5790            Some(t) => Ok(FunctionReturn::Type(t)),
5791            None => Ok(FunctionReturn::Other(ident)),
5792        }
5793    }
5794
5795    /// Consume any `[]` / `[N]` array markers after a type name and give
5796    /// back their text. Empty when there are none.
5797    fn consume_array_suffix(&mut self) -> String {
5798        let mut out = String::new();
5799        while matches!(self.peek(), Token::LBracket) {
5800            self.advance();
5801            // `[N]` is accepted and, as in PG, the length is not enforced.
5802            if let Token::Integer(n) = self.peek().clone() {
5803                self.advance();
5804                out.push_str(&alloc::format!("[{n}]"));
5805            } else {
5806                out.push_str("[]");
5807            }
5808            if matches!(self.peek(), Token::RBracket) {
5809                self.advance();
5810            }
5811        }
5812        out
5813    }
5814
5815    fn parse_optional_language(&mut self) -> Result<Option<String>, ParseError> {
5816        match self.peek() {
5817            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("language") => {
5818                self.advance();
5819                let lang = self.expect_ident_like()?;
5820                Ok(Some(lang.to_ascii_lowercase()))
5821            }
5822            _ => Ok(None),
5823        }
5824    }
5825
5826    /// v7.17.0 Phase 1.5 — body of `CREATE DOMAIN name AS
5827    /// base_type [DEFAULT expr] [NOT NULL | NULL] [CHECK
5828    /// (expr)]*`. The `DOMAIN` keyword has already been
5829    /// consumed. PG allows the trailing constraints in any
5830    /// order; we approximate with a small loop.
5831    fn parse_create_domain_after_keyword(&mut self) -> Result<Statement, ParseError> {
5832        let name = self.expect_ident_like()?;
5833        // Optional `AS`.
5834        if matches!(self.peek(), Token::As) {
5835            self.advance();
5836        }
5837        // v7.39 (round 259) — keep the raw type NAME when the base is not
5838        // a builtin: it is how `CREATE DOMAIN child AS parent` records its
5839        // parent domain.
5840        let (base_type, _, _, base_user_ref, _, _, _, _, _, _, _, _, _, _) =
5841            self.parse_type_with_implied_flags()?;
5842        let mut default: Option<Expr> = None;
5843        let mut not_null = false;
5844        let mut checks: Vec<Expr> = Vec::new();
5845        loop {
5846            match self.peek() {
5847                Token::Default => {
5848                    if default.is_some() {
5849                        return Err(self.err("DOMAIN DEFAULT specified twice".into()));
5850                    }
5851                    self.advance();
5852                    default = Some(self.parse_expr(0)?);
5853                }
5854                Token::Not => {
5855                    self.advance();
5856                    if !matches!(self.peek(), Token::Null) {
5857                        return Err(self.err(alloc::format!(
5858                            "expected NULL after NOT in DOMAIN, got {:?}",
5859                            self.peek()
5860                        )));
5861                    }
5862                    self.advance();
5863                    not_null = true;
5864                }
5865                Token::Null => {
5866                    self.advance();
5867                    // v7.39 (round 761, F31 tranche 2 #31) — bare NULL
5868                    // is the default-nullable marker (PG accepts it),
5869                    // but AFTER a NOT NULL it is a conflict PG refuses
5870                    // (`conflicting NULL/NOT NULL constraints`,
5871                    // PG18-measured); the old arm no-opped both ways.
5872                    if not_null {
5873                        return Err(self.err(alloc::string::String::from(
5874                            "conflicting NULL/NOT NULL constraints",
5875                        )));
5876                    }
5877                }
5878                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("check") => {
5879                    self.advance();
5880                    if !matches!(self.peek(), Token::LParen) {
5881                        return Err(self.err(alloc::format!(
5882                            "expected '(' after CHECK in DOMAIN, got {:?}",
5883                            self.peek()
5884                        )));
5885                    }
5886                    self.advance();
5887                    let expr = self.parse_expr(0)?;
5888                    if !matches!(self.peek(), Token::RParen) {
5889                        return Err(self.err(alloc::format!(
5890                            "expected ')' after CHECK expr, got {:?}",
5891                            self.peek()
5892                        )));
5893                    }
5894                    self.advance();
5895                    checks.push(expr);
5896                }
5897                // CONSTRAINT <name> CHECK (…) — PG accepts a name
5898                // prefix on the constraint; we drop the name and
5899                // recurse into the constraint parsing.
5900                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("constraint") => {
5901                    self.advance();
5902                    let _ = self.expect_ident_like()?;
5903                }
5904                _ => break,
5905            }
5906        }
5907        Ok(Statement::CreateDomain(crate::ast::CreateDomainStatement {
5908            name,
5909            base_type,
5910            base_domain: base_user_ref,
5911            default,
5912            not_null,
5913            checks,
5914        }))
5915    }
5916
5917    /// v7.17.0 Phase 1.4 — body of `CREATE TYPE name AS ENUM
5918    /// ('a', 'b', …)`. The `TYPE` keyword has already been
5919    /// consumed.
5920    fn parse_create_type_after_keyword(&mut self) -> Result<Statement, ParseError> {
5921        let name = self.expect_ident_like()?;
5922        // Required `AS`.
5923        if !matches!(self.peek(), Token::As) {
5924            return Err(self.err(alloc::format!(
5925                "expected AS after CREATE TYPE {name:?}, got {:?}",
5926                self.peek()
5927            )));
5928        }
5929        self.advance();
5930        // v7.37.x (ζ-B composite Phase 1) — `AS (` is the composite-
5931        // type shape: `CREATE TYPE foo AS (a INT, b TEXT)`. Branch
5932        // on the next token: `(` = composite, ident `ENUM` = enum.
5933        if matches!(self.peek(), Token::LParen) {
5934            self.advance();
5935            let mut fields: Vec<(String, ColumnTypeName)> = Vec::new();
5936            let mut field_user_types: Vec<Option<String>> = Vec::new();
5937            // v7.39 (round 769, F31 tranche 5 #140) — `CREATE TYPE x AS ()`
5938            // is legal PG (an attribute-less composite; measured — the old
5939            // e2e note claimed PG requires at least one attribute).
5940            if matches!(self.peek(), Token::RParen) {
5941                self.advance();
5942                return Ok(Statement::CreateType(crate::ast::CreateTypeStatement {
5943                    name,
5944                    kind: crate::ast::TypeKind::Composite {
5945                        fields,
5946                        field_user_types,
5947                    },
5948                }));
5949            }
5950            loop {
5951                let field_name = self.expect_ident_like()?;
5952                // v7.39 (round 264) — keep the raw type name when it is not
5953                // a builtin: that is how a NESTED composite field records
5954                // which composite it holds.
5955                let (field_type, _, _, field_user_ref, _, _, _, _, _, _, _, _, _, _) =
5956                    self.parse_type_with_implied_flags()?;
5957                fields.push((field_name, field_type));
5958                field_user_types.push(field_user_ref);
5959                if matches!(self.peek(), Token::Comma) {
5960                    self.advance();
5961                    continue;
5962                }
5963                if matches!(self.peek(), Token::RParen) {
5964                    self.advance();
5965                    break;
5966                }
5967                return Err(self.err(alloc::format!(
5968                    "expected , or ) in composite field list, got {:?}",
5969                    self.peek()
5970                )));
5971            }
5972            if fields.is_empty() {
5973                return Err(self.err("CREATE TYPE … AS (…) must declare at least one field".into()));
5974            }
5975            return Ok(Statement::CreateType(crate::ast::CreateTypeStatement {
5976                name,
5977                kind: crate::ast::TypeKind::Composite {
5978                    fields,
5979                    field_user_types,
5980                },
5981            }));
5982        }
5983        // Required `ENUM` ident.
5984        let kind_ident = match self.peek().clone() {
5985            Token::Ident(s) | Token::QuotedIdent(s) => s,
5986            other => {
5987                return Err(self.err(alloc::format!(
5988                    "expected ENUM or '(' after CREATE TYPE {name:?} AS, got {other:?}"
5989                )));
5990            }
5991        };
5992        if !kind_ident.eq_ignore_ascii_case("enum") {
5993            return Err(self.err(alloc::format!(
5994                "Phase 1.4 only supports ENUM or composite '(…)'; got {kind_ident:?}"
5995            )));
5996        }
5997        self.advance();
5998        if !matches!(self.peek(), Token::LParen) {
5999            return Err(self.err(alloc::format!(
6000                "expected '(' after ENUM, got {:?}",
6001                self.peek()
6002            )));
6003        }
6004        self.advance();
6005        let mut labels: Vec<String> = Vec::new();
6006        loop {
6007            match self.peek().clone() {
6008                Token::String(s) => {
6009                    self.advance();
6010                    labels.push(s);
6011                }
6012                other => {
6013                    return Err(
6014                        self.err(alloc::format!("expected enum label string, got {other:?}"))
6015                    );
6016                }
6017            }
6018            if matches!(self.peek(), Token::Comma) {
6019                self.advance();
6020                continue;
6021            }
6022            if matches!(self.peek(), Token::RParen) {
6023                self.advance();
6024                break;
6025            }
6026            return Err(self.err(alloc::format!(
6027                "expected , or ) in ENUM label list, got {:?}",
6028                self.peek()
6029            )));
6030        }
6031        if labels.is_empty() {
6032            return Err(self.err("CREATE TYPE … AS ENUM must declare at least one label".into()));
6033        }
6034        Ok(Statement::CreateType(crate::ast::CreateTypeStatement {
6035            name,
6036            kind: crate::ast::TypeKind::Enum { labels },
6037        }))
6038    }
6039
6040    /// v7.17.0 Phase 1.3 — body of `CREATE MATERIALIZED VIEW
6041    /// [IF NOT EXISTS] name [(col, …)] AS <SELECT …> [WITH [NO] DATA]`.
6042    /// The `CREATE MATERIALIZED VIEW` keywords have already been
6043    /// consumed.
6044    fn parse_create_materialized_view_after_keyword(&mut self) -> Result<Statement, ParseError> {
6045        let if_not_exists = self.parse_if_not_exists();
6046        let name = self.expect_ident_like()?;
6047        let mut columns: Vec<String> = Vec::new();
6048        if matches!(self.peek(), Token::LParen) {
6049            self.advance();
6050            loop {
6051                let c = self.expect_ident_like()?;
6052                columns.push(c);
6053                if matches!(self.peek(), Token::Comma) {
6054                    self.advance();
6055                    continue;
6056                }
6057                if matches!(self.peek(), Token::RParen) {
6058                    self.advance();
6059                    break;
6060                }
6061                return Err(self.err(alloc::format!(
6062                    "expected , or ) in MATERIALIZED VIEW column list, got {:?}",
6063                    self.peek()
6064                )));
6065            }
6066        }
6067        if !matches!(self.peek(), Token::As) {
6068            return Err(self.err(alloc::format!(
6069                "expected AS <SELECT …> after CREATE MATERIALIZED VIEW {name:?}, got {:?}",
6070                self.peek()
6071            )));
6072        }
6073        self.advance();
6074        // v7.39 (round 151) — a WITH-headed body is legal (read-only
6075        // CTEs only; the engine rejects data-modifying ones with PG's
6076        // message). A trailing `WITH [NO] DATA` can't START the body,
6077        // so WITH here heads the query.
6078        let body = if self.peek_is_with_kw() {
6079            self.advance();
6080            self.parse_nested_with_select()?
6081        } else {
6082            let body_stmt = self.parse_select_stmt()?;
6083            let Statement::Select(body) = body_stmt else {
6084                return Err(self.err(alloc::format!(
6085                    "CREATE MATERIALIZED VIEW body must be a SELECT, got {body_stmt:?}"
6086                )));
6087            };
6088            body
6089        };
6090        // Optional trailing `WITH [NO] DATA`.
6091        let with_data = self.parse_optional_with_data(true)?;
6092        Ok(Statement::CreateMaterializedView(
6093            crate::ast::CreateMaterializedViewStatement {
6094                temporary: false,
6095                name,
6096                if_not_exists,
6097                columns,
6098                body,
6099                with_data,
6100                as_plain_table: false,
6101            },
6102        ))
6103    }
6104
6105    /// v7.17.0 Phase 1.3 — `WITH [NO] DATA` trailer.
6106    /// `default_when_absent` is what to return if the tail is
6107    /// missing (CREATE defaults to WITH DATA, REFRESH defaults to
6108    /// WITH DATA).
6109    fn parse_optional_with_data(&mut self, default_when_absent: bool) -> Result<bool, ParseError> {
6110        let save = self.pos;
6111        // `WITH` is an Ident (not reserved in the lexer).
6112        let is_with = match self.peek() {
6113            Token::Ident(s) | Token::QuotedIdent(s) => s.eq_ignore_ascii_case("with"),
6114            _ => false,
6115        };
6116        if !is_with {
6117            return Ok(default_when_absent);
6118        }
6119        self.advance();
6120        // Optional `NO`.
6121        let mut with_data = true;
6122        let is_no = match self.peek() {
6123            Token::Ident(s) | Token::QuotedIdent(s) => s.eq_ignore_ascii_case("no"),
6124            _ => false,
6125        };
6126        if is_no {
6127            self.advance();
6128            with_data = false;
6129        }
6130        // Required `DATA` ident.
6131        let is_data = match self.peek() {
6132            Token::Ident(s) | Token::QuotedIdent(s) => s.eq_ignore_ascii_case("data"),
6133            _ => false,
6134        };
6135        if is_data {
6136            self.advance();
6137            Ok(with_data)
6138        } else {
6139            // Caller's WITH wasn't WITH-DATA — rewind so the outer
6140            // parser can interpret it.
6141            self.pos = save;
6142            Ok(default_when_absent)
6143        }
6144    }
6145
6146    /// v7.17.0 Phase 1.2 — body of `CREATE [OR REPLACE]
6147    /// [TEMPORARY] VIEW [IF NOT EXISTS] name [(col, …)] AS <SELECT>`.
6148    /// All keyword prefixes have already been consumed; the flags
6149    /// say which were present.
6150    fn parse_create_view_after_keyword(
6151        &mut self,
6152        or_replace: bool,
6153        _materialized_unused: bool,
6154        temporary: bool,
6155    ) -> Result<Statement, ParseError> {
6156        let if_not_exists = self.parse_if_not_exists();
6157        let name = self.expect_ident_like()?;
6158        // Optional `(col, col, …)` rename list.
6159        let mut columns: Vec<String> = Vec::new();
6160        if matches!(self.peek(), Token::LParen) {
6161            self.advance();
6162            loop {
6163                let c = self.expect_ident_like()?;
6164                columns.push(c);
6165                if matches!(self.peek(), Token::Comma) {
6166                    self.advance();
6167                    continue;
6168                }
6169                if matches!(self.peek(), Token::RParen) {
6170                    self.advance();
6171                    break;
6172                }
6173                return Err(self.err(alloc::format!(
6174                    "expected , or ) in VIEW column list, got {:?}",
6175                    self.peek()
6176                )));
6177            }
6178        }
6179        // Required `AS`.
6180        if !matches!(self.peek(), Token::As) {
6181            return Err(self.err(alloc::format!(
6182                "expected AS <SELECT …> after CREATE VIEW {name:?}, got {:?}",
6183                self.peek()
6184            )));
6185        }
6186        self.advance();
6187        // Body: a regular SELECT statement. v7.39 (round 151) — a
6188        // WITH-headed body is legal too (read-only CTEs only; the
6189        // engine rejects data-modifying ones with PG's message).
6190        // Disambiguation vs `WITH CHECK OPTION`: a body can't START
6191        // with the check-option clause, so WITH here heads the query.
6192        let body = if self.peek_is_with_kw() {
6193            self.advance();
6194            self.parse_nested_with_select()?
6195        } else {
6196            let body_stmt = self.parse_select_stmt()?;
6197            let Statement::Select(body) = body_stmt else {
6198                return Err(self.err(alloc::format!(
6199                    "CREATE VIEW body must be a SELECT statement, got {body_stmt:?}"
6200                )));
6201            };
6202            body
6203        };
6204        // v7.39 (round 132) — optional `WITH [ LOCAL | CASCADED ] CHECK OPTION`.
6205        // The SELECT parser stops before a trailing WITH, so it lands here.
6206        let check_option = if matches!(self.peek(),
6207            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("with"))
6208        {
6209            self.advance(); // WITH
6210            let opt = match self.peek() {
6211                Token::Ident(s) if s.eq_ignore_ascii_case("local") => {
6212                    self.advance();
6213                    crate::ast::ViewCheckOption::Local
6214                }
6215                Token::Ident(s) if s.eq_ignore_ascii_case("cascaded") => {
6216                    self.advance();
6217                    crate::ast::ViewCheckOption::Cascaded
6218                }
6219                // Bare `WITH CHECK OPTION` defaults to CASCADED (PG).
6220                _ => crate::ast::ViewCheckOption::Cascaded,
6221            };
6222            if !matches!(self.peek(),
6223                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("check"))
6224            {
6225                return Err(self.err(alloc::format!(
6226                    "expected CHECK in CREATE VIEW … WITH [LOCAL|CASCADED] CHECK OPTION, got {:?}",
6227                    self.peek()
6228                )));
6229            }
6230            self.advance(); // CHECK
6231            if !matches!(self.peek(),
6232                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("option"))
6233            {
6234                return Err(self.err(alloc::format!(
6235                    "expected OPTION after WITH CHECK in CREATE VIEW, got {:?}",
6236                    self.peek()
6237                )));
6238            }
6239            self.advance(); // OPTION
6240            Some(opt)
6241        } else {
6242            None
6243        };
6244        Ok(Statement::CreateView(crate::ast::CreateViewStatement {
6245            name,
6246            or_replace,
6247            if_not_exists,
6248            temporary,
6249            columns,
6250            body,
6251            check_option,
6252        }))
6253    }
6254
6255    /// v7.17.0 — body of `CREATE [TEMPORARY] SEQUENCE`. The
6256    /// `[TEMPORARY]` and `SEQUENCE` tokens have already been
6257    /// consumed; `temporary` carries whether TEMPORARY was seen.
6258    fn parse_create_sequence_after_keyword(
6259        &mut self,
6260        temporary: bool,
6261    ) -> Result<Statement, ParseError> {
6262        let if_not_exists = self.parse_if_not_exists();
6263        let name = self.expect_ident_like()?;
6264        // Optional `AS data_type`.
6265        let data_type = if matches!(self.peek(), Token::As) {
6266            self.advance();
6267            Some(self.parse_sequence_data_type()?)
6268        } else {
6269            None
6270        };
6271        let options = self.parse_sequence_options(/* allow_restart = */ false)?;
6272        Ok(Statement::CreateSequence(
6273            crate::ast::CreateSequenceStatement {
6274                name,
6275                if_not_exists,
6276                temporary,
6277                data_type,
6278                options,
6279            },
6280        ))
6281    }
6282
6283    /// v7.17.0 — body of `ALTER SEQUENCE`. The `ALTER` keyword has
6284    /// already been consumed; this is reached after `SEQUENCE`.
6285    /// v7.39 (round 260) — `ALTER DOMAIN name <action>`.
6286    fn parse_alter_domain_after_keyword(&mut self) -> Result<Statement, ParseError> {
6287        use crate::ast::AlterDomainAction as A;
6288        let name = self.expect_ident_like()?;
6289        // DROP / SET / ADD lex as reserved keyword tokens, not idents.
6290        let kw = match self.peek() {
6291            Token::Ident(s) | Token::QuotedIdent(s) => s.to_ascii_lowercase(),
6292            Token::Drop => alloc::string::String::from("drop"),
6293            Token::Default => alloc::string::String::from("default"),
6294            other => {
6295                return Err(self.err(alloc::format!(
6296                    "expected an ALTER DOMAIN action, got {other:?}"
6297                )));
6298            }
6299        };
6300        let action = match kw.as_str() {
6301            "add" => {
6302                self.advance();
6303                let cname = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("constraint"))
6304                {
6305                    self.advance();
6306                    Some(self.expect_ident_like()?)
6307                } else {
6308                    None
6309                };
6310                if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("check")) {
6311                    return Err(self.err(alloc::format!(
6312                        "ALTER DOMAIN ADD supports CHECK only, got {:?}",
6313                        self.peek()
6314                    )));
6315                }
6316                self.advance();
6317                if !matches!(self.peek(), Token::LParen) {
6318                    return Err(self.err("expected '(' after CHECK".into()));
6319                }
6320                self.advance();
6321                let check = self.parse_expr(0)?;
6322                if !matches!(self.peek(), Token::RParen) {
6323                    return Err(self.err("expected ')' after CHECK expression".into()));
6324                }
6325                self.advance();
6326                A::AddConstraint { name: cname, check }
6327            }
6328            "drop" => {
6329                self.advance();
6330                match self.peek() {
6331                    Token::Ident(s) if s.eq_ignore_ascii_case("constraint") => {
6332                        self.advance();
6333                        let if_exists = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("if"))
6334                        {
6335                            self.advance();
6336                            if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("exists"))
6337                            {
6338                                return Err(self.err("expected EXISTS after IF".into()));
6339                            }
6340                            self.advance();
6341                            true
6342                        } else {
6343                            false
6344                        };
6345                        let cn = self.expect_ident_like()?;
6346                        A::DropConstraint {
6347                            name: cn,
6348                            if_exists,
6349                        }
6350                    }
6351                    Token::Default => {
6352                        self.advance();
6353                        A::DropDefault
6354                    }
6355                    Token::Not => {
6356                        self.advance();
6357                        if !matches!(self.peek(), Token::Null) {
6358                            return Err(self.err("expected NULL after NOT".into()));
6359                        }
6360                        self.advance();
6361                        A::DropNotNull
6362                    }
6363                    other => {
6364                        return Err(self.err(alloc::format!(
6365                            "ALTER DOMAIN DROP expects CONSTRAINT / DEFAULT / NOT NULL, got {other:?}"
6366                        )));
6367                    }
6368                }
6369            }
6370            "set" => {
6371                self.advance();
6372                match self.peek() {
6373                    Token::Default => {
6374                        self.advance();
6375                        A::SetDefault(self.parse_expr(0)?)
6376                    }
6377                    Token::Not => {
6378                        self.advance();
6379                        if !matches!(self.peek(), Token::Null) {
6380                            return Err(self.err("expected NULL after NOT".into()));
6381                        }
6382                        self.advance();
6383                        A::SetNotNull
6384                    }
6385                    other => {
6386                        return Err(self.err(alloc::format!(
6387                            "ALTER DOMAIN SET expects DEFAULT / NOT NULL, got {other:?}"
6388                        )));
6389                    }
6390                }
6391            }
6392            "rename" => {
6393                self.advance();
6394                if !matches!(self.peek(), Token::To) {
6395                    return Err(self.err("expected TO after RENAME".into()));
6396                }
6397                self.advance();
6398                A::RenameTo(self.expect_ident_like()?)
6399            }
6400            other => {
6401                return Err(self.err(alloc::format!("unsupported ALTER DOMAIN action {other:?}")));
6402            }
6403        };
6404        Ok(Statement::AlterDomain { name, action })
6405    }
6406
6407    fn parse_alter_sequence_after_keyword(&mut self) -> Result<Statement, ParseError> {
6408        let if_exists = self.parse_if_exists();
6409        let name = self.expect_ident_like()?;
6410        // v7.39 (read01 round 49) — `RENAME TO new`; mutually exclusive with
6411        // the option list (PG allows only one or the other).
6412        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("rename")) {
6413            self.advance();
6414            if matches!(self.peek(), Token::To) {
6415                self.advance();
6416            } else {
6417                self.expect_keyword_ident("to")?;
6418            }
6419            let new = self.expect_ident_like()?;
6420            return Ok(Statement::AlterSequence(
6421                crate::ast::AlterSequenceStatement {
6422                    name,
6423                    if_exists,
6424                    options: crate::ast::SequenceOptions::default(),
6425                    rename_to: Some(new),
6426                },
6427            ));
6428        }
6429        let options = self.parse_sequence_options(/* allow_restart = */ true)?;
6430        Ok(Statement::AlterSequence(
6431            crate::ast::AlterSequenceStatement {
6432                name,
6433                if_exists,
6434                options,
6435                rename_to: None,
6436            },
6437        ))
6438    }
6439
6440    fn parse_sequence_data_type(&mut self) -> Result<crate::ast::SequenceDataType, ParseError> {
6441        let kw = self.expect_ident_like()?;
6442        match kw.to_ascii_lowercase().as_str() {
6443            "smallint" | "int2" => Ok(crate::ast::SequenceDataType::SmallInt),
6444            "integer" | "int" | "int4" => Ok(crate::ast::SequenceDataType::Int),
6445            "bigint" | "int8" => Ok(crate::ast::SequenceDataType::BigInt),
6446            other => Err(self.err(alloc::format!(
6447                "expected SMALLINT / INTEGER / BIGINT after SEQUENCE AS, got {other:?}"
6448            ))),
6449        }
6450    }
6451
6452    fn parse_sequence_options(
6453        &mut self,
6454        allow_restart: bool,
6455    ) -> Result<crate::ast::SequenceOptions, ParseError> {
6456        use crate::ast::{SeqBound, SequenceOptions, SequenceOwnedBy};
6457        let mut opts = SequenceOptions::default();
6458        #[allow(clippy::while_let_loop)]
6459        loop {
6460            // Match an ident; stop at any non-ident token (sentinel,
6461            // semicolon, end of statement).
6462            let kw_lc = match self.peek() {
6463                Token::Ident(s) | Token::QuotedIdent(s) => s.to_ascii_lowercase(),
6464                _ => break,
6465            };
6466            match kw_lc.as_str() {
6467                "increment" => {
6468                    self.advance();
6469                    // Optional BY.
6470                    if self.peek_is_by() {
6471                        self.advance();
6472                    }
6473                    opts.increment = Some(self.expect_signed_int()?);
6474                }
6475                "minvalue" => {
6476                    self.advance();
6477                    opts.min_value = Some(SeqBound::Value(self.expect_signed_int()?));
6478                }
6479                "maxvalue" => {
6480                    self.advance();
6481                    opts.max_value = Some(SeqBound::Value(self.expect_signed_int()?));
6482                }
6483                "no" => {
6484                    self.advance();
6485                    let what = self.expect_ident_like()?;
6486                    match what.to_ascii_lowercase().as_str() {
6487                        "minvalue" => opts.min_value = Some(SeqBound::NoBound),
6488                        "maxvalue" => opts.max_value = Some(SeqBound::NoBound),
6489                        "cycle" => opts.cycle = Some(false),
6490                        other => {
6491                            return Err(self.err(alloc::format!(
6492                                "expected MINVALUE / MAXVALUE / CYCLE after NO, got {other:?}"
6493                            )));
6494                        }
6495                    }
6496                }
6497                "start" => {
6498                    self.advance();
6499                    // Optional WITH.
6500                    if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
6501                        if s.eq_ignore_ascii_case("with"))
6502                    {
6503                        self.advance();
6504                    }
6505                    opts.start = Some(self.expect_signed_int()?);
6506                }
6507                "restart" if allow_restart => {
6508                    self.advance();
6509                    // Optional WITH n; bare RESTART means restart at START.
6510                    let mut with_val: Option<i64> = None;
6511                    if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
6512                        if s.eq_ignore_ascii_case("with"))
6513                    {
6514                        self.advance();
6515                        with_val = Some(self.expect_signed_int()?);
6516                    } else if matches!(self.peek(), Token::Integer(_) | Token::Minus) {
6517                        with_val = Some(self.expect_signed_int()?);
6518                    }
6519                    opts.restart = Some(with_val);
6520                }
6521                "cache" => {
6522                    self.advance();
6523                    opts.cache = Some(self.expect_signed_int()?);
6524                }
6525                "cycle" => {
6526                    self.advance();
6527                    opts.cycle = Some(true);
6528                }
6529                "owned" => {
6530                    self.advance();
6531                    match self.peek() {
6532                        Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("by") => {
6533                            self.advance();
6534                        }
6535                        other => {
6536                            return Err(
6537                                self.err(alloc::format!("expected BY after OWNED, got {other:?}"))
6538                            );
6539                        }
6540                    }
6541                    // OWNED BY {NONE | tab.col}. Read just one ident
6542                    // (NOT expect_ident_like which would auto-strip
6543                    // a schema prefix and consume the `.col` we need).
6544                    let first = match self.advance() {
6545                        Token::Ident(s) | Token::QuotedIdent(s) => s,
6546                        other => {
6547                            return Err(self.err(alloc::format!(
6548                                "expected identifier or NONE after OWNED BY, got {other:?}"
6549                            )));
6550                        }
6551                    };
6552                    if first.eq_ignore_ascii_case("none") {
6553                        opts.owned_by = Some(SequenceOwnedBy::None);
6554                    } else if matches!(self.peek(), Token::Dot) {
6555                        self.advance();
6556                        let second = match self.advance() {
6557                            Token::Ident(s) | Token::QuotedIdent(s) => s,
6558                            other => {
6559                                return Err(self.err(alloc::format!(
6560                                    "expected column name after OWNED BY {first}., got {other:?}"
6561                                )));
6562                            }
6563                        };
6564                        // v7.17 dump-compat fix — pg_dump emits
6565                        // OWNED BY clauses as
6566                        // `schema.table.column` (three segments).
6567                        // If a third `.<ident>` follows, treat the
6568                        // first ident as schema (drop it; SPG is
6569                        // single-schema) and the middle / last
6570                        // pair as table.column. Otherwise it's
6571                        // the two-segment form table.column.
6572                        if matches!(self.peek(), Token::Dot) {
6573                            self.advance();
6574                            let third = match self.advance() {
6575                                Token::Ident(s) | Token::QuotedIdent(s) => s,
6576                                other => {
6577                                    return Err(self.err(alloc::format!(
6578                                        "expected column name after OWNED BY {first}.{second}., got {other:?}"
6579                                    )));
6580                                }
6581                            };
6582                            let _ = first; // schema prefix discarded
6583                            opts.owned_by = Some(SequenceOwnedBy::Column {
6584                                table: second,
6585                                column: third,
6586                            });
6587                        } else {
6588                            opts.owned_by = Some(SequenceOwnedBy::Column {
6589                                table: first,
6590                                column: second,
6591                            });
6592                        }
6593                    } else {
6594                        return Err(self.err(alloc::format!(
6595                            "expected table.column or NONE after OWNED BY, got {first:?}"
6596                        )));
6597                    }
6598                }
6599                _ => break,
6600            }
6601        }
6602        Ok(opts)
6603    }
6604
6605    fn expect_signed_int(&mut self) -> Result<i64, ParseError> {
6606        let neg = if matches!(self.peek(), Token::Minus) {
6607            self.advance();
6608            true
6609        } else {
6610            false
6611        };
6612        match self.peek() {
6613            Token::Integer(n) => {
6614                let v = *n;
6615                self.advance();
6616                Ok(if neg { -v } else { v })
6617            }
6618            other => Err(self.err(alloc::format!("expected signed integer, got {other:?}"))),
6619        }
6620    }
6621
6622    /// v7.17.0 Phase 3.1 — absorb `[NOT] DEFERRABLE [INITIALLY
6623    /// {DEFERRED | IMMEDIATE}]` constraint-timing clauses. Each
6624    /// clause is fully accepted and discarded — SPG always runs
6625    /// constraint checks immediately (single-writer model). The
6626    /// loop allows DEFERRABLE and the INITIALLY suffix to appear
6627    /// in either order (per the SQL spec they're independent),
6628    /// though pg_dump always emits them in the canonical
6629    /// `[NOT] DEFERRABLE INITIALLY {DEFERRED|IMMEDIATE}` shape.
6630    /// Stops at the first token that isn't part of the clause.
6631    fn consume_optional_deferrable_clauses(&mut self) -> Result<(), ParseError> {
6632        self.consume_deferrable_clauses_timed().map(|_| ())
6633    }
6634
6635    /// v7.39 (round 288) — the same scan, but reporting what it saw:
6636    /// `(deferrable, initially_deferred)`. The clauses were parsed and
6637    /// dropped, so `DEFERRABLE INITIALLY DEFERRED` on an FK behaved as
6638    /// NOT DEFERRABLE and a circular-FK migration could not load.
6639    fn consume_deferrable_clauses_timed(&mut self) -> Result<(bool, bool), ParseError> {
6640        let mut deferrable = false;
6641        let mut initially_deferred = false;
6642        loop {
6643            // Bare `DEFERRABLE` (Phase 3.1 — was hard-error pre-3.1).
6644            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("deferrable")) {
6645                self.advance();
6646                deferrable = true;
6647                if self.consume_optional_initially_clause()? {
6648                    initially_deferred = true;
6649                }
6650                continue;
6651            }
6652            // `NOT DEFERRABLE` — already worked pre-3.1.
6653            if matches!(self.peek(), Token::Not) {
6654                let look = self.tokens.get(self.pos + 1);
6655                if matches!(look, Some(Token::Ident(s)) if s.eq_ignore_ascii_case("deferrable")) {
6656                    self.advance(); // NOT
6657                    self.advance(); // DEFERRABLE
6658                    deferrable = false;
6659                    initially_deferred = false;
6660                    let _ = self.consume_optional_initially_clause()?;
6661                    continue;
6662                }
6663                break;
6664            }
6665            // Standalone `INITIALLY {DEFERRED|IMMEDIATE}` — PG
6666            // accepts this without a leading [NOT] DEFERRABLE
6667            // (the timing keyword alone). pg_dump occasionally
6668            // emits it on FK constraints that inherit timing.
6669            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("initially")) {
6670                if self.consume_optional_initially_clause()? {
6671                    initially_deferred = true;
6672                    // PG: a bare `INITIALLY DEFERRED` implies DEFERRABLE.
6673                    deferrable = true;
6674                }
6675                continue;
6676            }
6677            break;
6678        }
6679        Ok((deferrable, initially_deferred))
6680    }
6681
6682    /// Helper for [`consume_optional_deferrable_clauses`]. When the
6683    /// next token is `INITIALLY`, consume it plus the required
6684    /// `DEFERRED` | `IMMEDIATE` trailer. No-op otherwise.
6685    /// Returns true when the timing seen was `DEFERRED`.
6686    fn consume_optional_initially_clause(&mut self) -> Result<bool, ParseError> {
6687        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("initially")) {
6688            return Ok(false);
6689        }
6690        self.advance(); // INITIALLY
6691        match self.advance() {
6692            Token::Ident(s)
6693                if s.eq_ignore_ascii_case("deferred") || s.eq_ignore_ascii_case("immediate") =>
6694            {
6695                Ok(s.eq_ignore_ascii_case("deferred"))
6696            }
6697            other => Err(self.err(alloc::format!(
6698                "expected DEFERRED or IMMEDIATE after INITIALLY, got {other:?}"
6699            ))),
6700        }
6701    }
6702
6703    /// v7.17.0 Phase 4.2 — consume a MySQL `CREATE PROCEDURE` body
6704    /// in its entirety so the parser returns Empty without
6705    /// touching the runtime. The CREATE+PROCEDURE keywords are
6706    /// already consumed; this swallows everything from the
6707    /// procedure name through the matching `END`, including
6708    /// nested `BEGIN`/`END` blocks, internal `;` terminators
6709    /// (DELIMITER `//` makes the script splitter forward the
6710    /// whole block as one statement), `@var` session-variable
6711    /// references, and the trailing terminator.
6712    ///
6713    /// Tracks nesting depth so:
6714    ///   BEGIN
6715    ///     IF cond THEN
6716    ///       BEGIN ... END;
6717    ///     END IF;
6718    ///   END
6719    /// terminates at the outer END.
6720    fn consume_mysql_routine_body(&mut self) {
6721        // Outer skeleton: name, (...), optional clauses, BEGIN
6722        // <body> END [;]. Scan for the first BEGIN — anything
6723        // before it is signature decoration we don't care about.
6724        // Once inside BEGIN, count up on BEGIN, down on END.
6725        let mut depth: i32 = 0;
6726        let mut started = false;
6727        loop {
6728            match self.peek().clone() {
6729                Token::Begin => {
6730                    self.advance();
6731                    depth += 1;
6732                    started = true;
6733                }
6734                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("end") => {
6735                    self.advance();
6736                    if started {
6737                        depth -= 1;
6738                        if depth <= 0 {
6739                            // Optional trailing ident (`END IF`,
6740                            // `END LOOP`, `END WHILE`, `END CASE`,
6741                            // `END label_name`) — eat the next
6742                            // ident if present so we don't
6743                            // mistake `END IF;` for the outer
6744                            // close.
6745                            if matches!(self.peek(), Token::Ident(_) | Token::QuotedIdent(_)) {
6746                                // If the next token is one of the
6747                                // PL/SQL block-closer keywords,
6748                                // the END belongs to an inner
6749                                // block; bump depth back up.
6750                                let is_inner_close = matches!(
6751                                    self.peek(),
6752                                    Token::Ident(s) | Token::QuotedIdent(s)
6753                                        if matches!(
6754                                            s.to_ascii_lowercase().as_str(),
6755                                            "if" | "loop" | "while" | "case" | "repeat"
6756                                        )
6757                                );
6758                                if is_inner_close {
6759                                    self.advance();
6760                                    depth += 1;
6761                                    continue;
6762                                }
6763                            }
6764                            // Eat optional trailing `;`.
6765                            if matches!(self.peek(), Token::Semicolon) {
6766                                self.advance();
6767                            }
6768                            return;
6769                        }
6770                    }
6771                }
6772                Token::Eof => return,
6773                _ => {
6774                    self.advance();
6775                }
6776            }
6777        }
6778    }
6779
6780    /// v7.17.0 Phase 2.6 — absorb the MySQL view-prefix clauses
6781    /// that appear between `CREATE` and `VIEW` in mysqldump output:
6782    ///
6783    /// * `ALGORITHM = {UNDEFINED|MERGE|TEMPTABLE}`
6784    /// * `DEFINER = <user>`  (user may be a quoted string, a bare
6785    ///   ident, or `ident @ ident-or-quoted-string` host form)
6786    /// * `SQL SECURITY {DEFINER|INVOKER}`
6787    ///
6788    /// Each clause may appear at most once but in any order.
6789    /// The hints are pure planner / permission metadata that
6790    /// SPG's view-rewrite engine handles uniformly; we accept
6791    /// and discard. Returns `Ok(())` once a non-clause token is
6792    /// peeked (the caller then checks for the `VIEW` keyword).
6793    fn consume_mysql_view_prefix(&mut self) -> Result<(), ParseError> {
6794        loop {
6795            match self.peek().clone() {
6796                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("algorithm") => {
6797                    self.advance(); // ALGORITHM
6798                    // Optional `=`. MySQL spec requires it but be
6799                    // generous.
6800                    if matches!(self.peek(), Token::Eq) {
6801                        self.advance();
6802                    }
6803                    // UNDEFINED / MERGE / TEMPTABLE — accept any
6804                    // bare ident; unknown values still parse so
6805                    // future MySQL versions don't break.
6806                    if matches!(
6807                        self.peek(),
6808                        Token::Ident(_) | Token::QuotedIdent(_) | Token::String(_)
6809                    ) {
6810                        self.advance();
6811                    }
6812                }
6813                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("definer") => {
6814                    self.advance(); // DEFINER
6815                    if matches!(self.peek(), Token::Eq) {
6816                        self.advance();
6817                    }
6818                    // User: quoted string, ident, OR ident @ host
6819                    // (host may itself be quoted or bare).
6820                    match self.peek().clone() {
6821                        Token::String(_) | Token::Ident(_) | Token::QuotedIdent(_) => {
6822                            self.advance();
6823                            // Optional `@host`.
6824                            if matches!(self.peek(), Token::At) {
6825                                self.advance();
6826                                if matches!(
6827                                    self.peek(),
6828                                    Token::Ident(_) | Token::QuotedIdent(_) | Token::String(_)
6829                                ) {
6830                                    self.advance();
6831                                }
6832                            }
6833                        }
6834                        _ => {}
6835                    }
6836                }
6837                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("sql") => {
6838                    // `SQL SECURITY {DEFINER|INVOKER}`. Only honoured
6839                    // when followed by SECURITY — the dispatcher must
6840                    // not consume a bare `SQL` token (it's not a
6841                    // legal CREATE prefix on its own).
6842                    let save = self.pos;
6843                    self.advance(); // SQL
6844                    if matches!(self.peek(), Token::Ident(s2) | Token::QuotedIdent(s2)
6845                        if s2.eq_ignore_ascii_case("security"))
6846                    {
6847                        self.advance(); // SECURITY
6848                        // DEFINER / INVOKER trailing ident.
6849                        if matches!(self.peek(), Token::Ident(_) | Token::QuotedIdent(_)) {
6850                            self.advance();
6851                        }
6852                    } else {
6853                        // Not a SQL SECURITY clause — roll back and
6854                        // bail; the caller will error out cleanly.
6855                        self.pos = save;
6856                        return Ok(());
6857                    }
6858                }
6859                _ => return Ok(()),
6860            }
6861        }
6862    }
6863
6864    fn parse_if_not_exists(&mut self) -> bool {
6865        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("if"))
6866        {
6867            let save = self.pos;
6868            self.advance();
6869            if matches!(self.peek(), Token::Not) {
6870                self.advance();
6871                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("exists"))
6872                {
6873                    self.advance();
6874                    return true;
6875                }
6876            }
6877            self.pos = save;
6878        }
6879        false
6880    }
6881
6882    fn parse_if_exists(&mut self) -> bool {
6883        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("if"))
6884        {
6885            let save = self.pos;
6886            self.advance();
6887            if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("exists"))
6888            {
6889                self.advance();
6890                return true;
6891            }
6892            self.pos = save;
6893        }
6894        false
6895    }
6896
6897    /// v7.12.4 — body of `CREATE [OR REPLACE] TRIGGER`. The
6898    /// `[OR REPLACE]` flag and the `TRIGGER` keyword have already
6899    /// been consumed.
6900    fn parse_create_trigger_after_keyword(
6901        &mut self,
6902        or_replace: bool,
6903    ) -> Result<Statement, ParseError> {
6904        let name = self.expect_ident_like()?;
6905        let timing = {
6906            let ident = self.expect_ident_like()?;
6907            if ident.eq_ignore_ascii_case("before") {
6908                TriggerTiming::Before
6909            } else if ident.eq_ignore_ascii_case("after") {
6910                TriggerTiming::After
6911            } else if ident.eq_ignore_ascii_case("instead") {
6912                let next = self.expect_ident_like()?;
6913                if !next.eq_ignore_ascii_case("of") {
6914                    return Err(self.err(alloc::format!(
6915                        "expected OF after INSTEAD in trigger timing, got {next:?}"
6916                    )));
6917                }
6918                TriggerTiming::InsteadOf
6919            } else {
6920                return Err(self.err(alloc::format!(
6921                    "expected BEFORE / AFTER / INSTEAD OF in trigger timing, got {ident:?}"
6922                )));
6923            }
6924        };
6925        // Events: INSERT [ OR UPDATE [ OR DELETE [ OR TRUNCATE ] ] ].
6926        // OR is a reserved keyword token (Token::Or), not an Ident.
6927        // v7.13.0 — after an UPDATE event we may optionally see
6928        // `OF col, col, …` (mailrs round-5 G7). Columns are
6929        // captured into `update_columns` once across the whole
6930        // events list; multiple `UPDATE OF` clauses are rejected.
6931        let mut events: Vec<TriggerEvent> = Vec::new();
6932        let mut update_columns: Vec<String> = Vec::new();
6933        let (first_ev, first_cols) = self.parse_trigger_event_with_optional_of()?;
6934        events.push(first_ev);
6935        if !first_cols.is_empty() {
6936            update_columns = first_cols;
6937        }
6938        while matches!(self.peek(), Token::Or) {
6939            self.advance();
6940            let (ev, cols) = self.parse_trigger_event_with_optional_of()?;
6941            events.push(ev);
6942            if !cols.is_empty() {
6943                if !update_columns.is_empty() {
6944                    return Err(
6945                        self.err("CREATE TRIGGER: `UPDATE OF cols` may appear at most once".into())
6946                    );
6947                }
6948                update_columns = cols;
6949            }
6950        }
6951        // ON <table>
6952        let tok = self.peek();
6953        let Token::On = tok else {
6954            return Err(self.err(alloc::format!(
6955                "expected ON after trigger events, got {tok:?}"
6956            )));
6957        };
6958        self.advance();
6959        let table = self.expect_ident_like()?;
6960        // v7.39 (read01 round 82) — a CONSTRAINT TRIGGER may carry `FROM
6961        // reftable` and `[NOT] DEFERRABLE [INITIALLY {DEFERRED|IMMEDIATE}]`
6962        // between the table and FOR EACH ROW. Accept and skip them: SPG fires
6963        // the trigger as a plain AFTER trigger (correct for every non-deferred
6964        // use; deferral timing is not yet honoured).
6965        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
6966            if s.eq_ignore_ascii_case("from"))
6967        {
6968            self.advance();
6969            let _reftable = self.expect_ident_like()?;
6970        }
6971        self.consume_optional_deferrable_clauses()?;
6972        // FOR EACH ROW / FOR EACH STATEMENT. FOR is a reserved
6973        // keyword (Token::For); EACH / ROW / STATEMENT are bare
6974        // idents.
6975        if !matches!(self.peek(), Token::For) {
6976            return Err(self.err(alloc::format!(
6977                "expected FOR EACH ROW / STATEMENT, got {:?}",
6978                self.peek()
6979            )));
6980        }
6981        self.advance();
6982        let for_each = {
6983            let e = self.expect_ident_like()?;
6984            if !e.eq_ignore_ascii_case("each") {
6985                return Err(self.err(alloc::format!("expected EACH after FOR, got {e:?}")));
6986            }
6987            let unit = self.expect_ident_like()?;
6988            if unit.eq_ignore_ascii_case("row") {
6989                TriggerForEach::Row
6990            } else if unit.eq_ignore_ascii_case("statement") {
6991                TriggerForEach::Statement
6992            } else {
6993                return Err(self.err(alloc::format!(
6994                    "expected ROW / STATEMENT after FOR EACH, got {unit:?}"
6995                )));
6996            }
6997        };
6998        // v7.39 (round 138) — optional `WHEN ( condition )` before EXECUTE.
6999        let when_condition = if matches!(self.peek(),
7000            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("when"))
7001        {
7002            self.advance();
7003            Some(self.parse_paren_expr("WHEN")?)
7004        } else {
7005            None
7006        };
7007        // EXECUTE FUNCTION/PROCEDURE name(...)
7008        let exec = self.expect_ident_like()?;
7009        if !exec.eq_ignore_ascii_case("execute") {
7010            return Err(self.err(alloc::format!(
7011                "expected EXECUTE FUNCTION/PROCEDURE in CREATE TRIGGER, got {exec:?}"
7012            )));
7013        }
7014        let fn_or_proc = self.expect_ident_like()?;
7015        if !(fn_or_proc.eq_ignore_ascii_case("function")
7016            || fn_or_proc.eq_ignore_ascii_case("procedure"))
7017        {
7018            return Err(self.err(alloc::format!(
7019                "expected FUNCTION / PROCEDURE after EXECUTE, got {fn_or_proc:?}"
7020            )));
7021        }
7022        let function = self.expect_ident_like()?;
7023        // Optional empty arg list `()`.
7024        if matches!(self.peek(), Token::LParen) {
7025            self.advance();
7026            if !matches!(self.peek(), Token::RParen) {
7027                return Err(self.err(alloc::format!(
7028                    "v7.12.4 trigger function calls take no args; got {:?}",
7029                    self.peek()
7030                )));
7031            }
7032            self.advance();
7033        }
7034        Ok(Statement::CreateTrigger(CreateTriggerStatement {
7035            name,
7036            or_replace,
7037            timing,
7038            events,
7039            table,
7040            for_each,
7041            function,
7042            update_columns,
7043            when_condition,
7044        }))
7045    }
7046
7047    /// v7.39 (round 139) — `CREATE RULE <name> AS ON <event> TO <table>
7048    /// [WHERE <cond>] DO [ALSO|INSTEAD] { NOTHING | cmd | ( cmd; … ) }`.
7049    fn parse_create_rule_after_keyword(
7050        &mut self,
7051        or_replace: bool,
7052    ) -> Result<Statement, ParseError> {
7053        let name = self.expect_ident_like()?;
7054        if !matches!(self.peek(), Token::As) {
7055            return Err(self.err(alloc::format!(
7056                "expected AS in CREATE RULE, got {:?}",
7057                self.peek()
7058            )));
7059        }
7060        self.advance();
7061        if !matches!(self.peek(), Token::On) {
7062            return Err(self.err(alloc::format!(
7063                "expected ON in CREATE RULE, got {:?}",
7064                self.peek()
7065            )));
7066        }
7067        self.advance();
7068        let event = self.parse_rule_event()?;
7069        if !matches!(self.peek(), Token::To)
7070            && !matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("to"))
7071        {
7072            return Err(self.err(alloc::format!(
7073                "expected TO after rule event, got {:?}",
7074                self.peek()
7075            )));
7076        }
7077        self.advance();
7078        let table = self.expect_ident_like()?;
7079        // Optional `WHERE <cond>` (no parentheses, unlike a trigger WHEN).
7080        let when_condition = if matches!(self.peek(), Token::Where) {
7081            self.advance();
7082            Some(self.parse_expr(0)?)
7083        } else {
7084            None
7085        };
7086        if !matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("do"))
7087        {
7088            return Err(self.err(alloc::format!(
7089                "expected DO in CREATE RULE, got {:?}",
7090                self.peek()
7091            )));
7092        }
7093        self.advance();
7094        // `DO [ ALSO | INSTEAD ]` — ALSO is the default when neither is written.
7095        let instead = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("instead"))
7096        {
7097            self.advance();
7098            true
7099        } else if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("also")) {
7100            self.advance();
7101            false
7102        } else {
7103            false
7104        };
7105        // `NOTHING` | `( cmd; … )` | `cmd`.
7106        let commands = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("nothing"))
7107        {
7108            self.advance();
7109            Vec::new()
7110        } else if matches!(self.peek(), Token::LParen) {
7111            self.advance();
7112            let mut cmds = Vec::new();
7113            loop {
7114                cmds.push(self.parse_one_statement()?);
7115                if matches!(self.peek(), Token::Semicolon) {
7116                    self.advance();
7117                    if matches!(self.peek(), Token::RParen) {
7118                        break;
7119                    }
7120                    continue;
7121                }
7122                break;
7123            }
7124            if !matches!(self.peek(), Token::RParen) {
7125                return Err(self.err(alloc::format!(
7126                    "expected ) closing the CREATE RULE command list, got {:?}",
7127                    self.peek()
7128                )));
7129            }
7130            self.advance();
7131            cmds
7132        } else {
7133            alloc::vec![self.parse_one_statement()?]
7134        };
7135        Ok(Statement::CreateRule(crate::ast::CreateRuleStatement {
7136            name,
7137            or_replace,
7138            event,
7139            table,
7140            instead,
7141            when_condition,
7142            commands,
7143        }))
7144    }
7145
7146    /// v7.39 (round 139) — a rule event keyword → uppercase string.
7147    fn parse_rule_event(&mut self) -> Result<alloc::string::String, ParseError> {
7148        if matches!(self.peek(), Token::Insert) {
7149            self.advance();
7150            return Ok(alloc::string::String::from("INSERT"));
7151        }
7152        if matches!(self.peek(), Token::Select) {
7153            self.advance();
7154            return Ok(alloc::string::String::from("SELECT"));
7155        }
7156        match self.peek() {
7157            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("update") => {
7158                self.advance();
7159                Ok(alloc::string::String::from("UPDATE"))
7160            }
7161            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("delete") => {
7162                self.advance();
7163                Ok(alloc::string::String::from("DELETE"))
7164            }
7165            other => Err(self.err(alloc::format!(
7166                "expected INSERT / UPDATE / DELETE / SELECT in CREATE RULE, got {other:?}"
7167            ))),
7168        }
7169    }
7170
7171    /// v7.13.0 — parse one trigger event, then optionally consume
7172    /// `OF col, col, …` after `UPDATE` (mailrs round-5 G7). Other
7173    /// events (INSERT/DELETE/TRUNCATE) don't accept the OF tail.
7174    fn parse_trigger_event_with_optional_of(
7175        &mut self,
7176    ) -> Result<(TriggerEvent, Vec<String>), ParseError> {
7177        let ev = self.parse_trigger_event()?;
7178        if !matches!(ev, TriggerEvent::Update) {
7179            return Ok((ev, Vec::new()));
7180        }
7181        // `OF` is a bare ident.
7182        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("of")) {
7183            return Ok((ev, Vec::new()));
7184        }
7185        self.advance(); // OF
7186        let mut cols: Vec<String> = Vec::new();
7187        loop {
7188            cols.push(self.expect_ident_like()?);
7189            if matches!(self.peek(), Token::Comma) {
7190                self.advance();
7191                continue;
7192            }
7193            break;
7194        }
7195        if cols.is_empty() {
7196            return Err(
7197                self.err("CREATE TRIGGER: `UPDATE OF` requires at least one column name".into())
7198            );
7199        }
7200        Ok((ev, cols))
7201    }
7202
7203    /// v7.12.4 — `BEGIN stmt; stmt; … END[;]` PL/pgSQL block.
7204    /// v7.12.6 — optional `DECLARE var TYPE [:= init];` prelude
7205    /// before `BEGIN`, and IF / RAISE / embedded SQL statements
7206    /// inside the body.
7207    /// Called by [`parse_plpgsql_body`] after the body's tokens
7208    /// have been lexed into this temporary parser.
7209    pub(crate) fn parse_plpgsql_block(&mut self) -> Result<PlPgSqlBlock, ParseError> {
7210        // v7.12.6 — optional DECLARE prelude.
7211        let declarations = if matches!(
7212            self.peek(),
7213            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("declare")
7214        ) {
7215            self.advance();
7216            self.parse_plpgsql_declare_block()?
7217        } else {
7218            Vec::new()
7219        };
7220        // BEGIN keyword (PL/pgSQL — distinct from the SQL
7221        // `BEGIN` transaction-start, but we can reuse the
7222        // reserved Token::Begin since the body is a separate
7223        // lex/parse context).
7224        if !matches!(self.peek(), Token::Begin) {
7225            return Err(self.err(alloc::format!(
7226                "expected BEGIN at start of plpgsql block, got {:?}",
7227                self.peek()
7228            )));
7229        }
7230        self.advance();
7231        let statements = self.parse_plpgsql_stmt_list_until_end()?;
7232        // v7.37.20 (20.10) — optional EXCEPTION clause between the
7233        // body's last statement and the trailing END. When present
7234        // it's a series of `WHEN <cond> [OR <cond>]* THEN <body>`
7235        // arms terminated by END.
7236        let exception_handlers = if matches!(
7237            self.peek(),
7238            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("exception")
7239        ) {
7240            self.advance();
7241            self.parse_plpgsql_exception_handlers()?
7242        } else {
7243            Vec::new()
7244        };
7245        Ok(PlPgSqlBlock {
7246            declarations,
7247            statements,
7248            exception_handlers,
7249        })
7250    }
7251
7252    /// v7.37.20 (20.10) — parse EXCEPTION handlers `WHEN <cond>
7253    /// [OR <cond>]* THEN <body>` sequence up to the trailing END.
7254    fn parse_plpgsql_exception_handlers(
7255        &mut self,
7256    ) -> Result<Vec<crate::ast::ExceptionHandler>, ParseError> {
7257        let mut out: Vec<crate::ast::ExceptionHandler> = Vec::new();
7258        loop {
7259            // Stop at END — the block-level trailing END LOOP / END;
7260            // is handled by the caller.
7261            if matches!(
7262                self.peek(),
7263                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("end")
7264            ) {
7265                return Ok(out);
7266            }
7267            // WHEN <cond> [OR <cond>]* THEN <body>
7268            if !matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("when"))
7269            {
7270                return Err(self.err(alloc::format!(
7271                    "expected WHEN or END inside EXCEPTION clause, got {:?}",
7272                    self.peek()
7273                )));
7274            }
7275            self.advance();
7276            let mut conditions: Vec<String> = Vec::new();
7277            conditions.push(self.expect_ident_like()?);
7278            while matches!(self.peek(), Token::Or) {
7279                self.advance();
7280                conditions.push(self.expect_ident_like()?);
7281            }
7282            let then_kw = self.expect_ident_like()?;
7283            if !then_kw.eq_ignore_ascii_case("then") {
7284                return Err(self.err(alloc::format!(
7285                    "expected THEN after WHEN condition list, got {then_kw:?}"
7286                )));
7287            }
7288            let body = self.parse_plpgsql_stmt_list_until_end()?;
7289            out.push(crate::ast::ExceptionHandler { conditions, body });
7290        }
7291    }
7292
7293    /// v7.12.6 — parse the `DECLARE ... [var TYPE [:= init];]+`
7294    /// prelude. Caller has already consumed `DECLARE`. We stop
7295    /// reading entries when we hit `BEGIN`.
7296    fn parse_plpgsql_declare_block(&mut self) -> Result<Vec<PlPgSqlDeclare>, ParseError> {
7297        let mut out: Vec<PlPgSqlDeclare> = Vec::new();
7298        loop {
7299            if matches!(self.peek(), Token::Begin) {
7300                return Ok(out);
7301            }
7302            let name = self.expect_ident_like()?;
7303            // v7.37.20 (20.7) — type inference: if the next token is
7304            // `:=` or `=` (no explicit type), infer from the default
7305            // expression. Otherwise the ident that follows is the
7306            // declared type.
7307            //
7308            // v7.37.20 (20.8) — `<table>.<col>%TYPE` / `<table>%ROWTYPE`
7309            // (PG-standard). SPG parse-accepts and treats identically
7310            // to inference — the eventual runtime value determines
7311            // the local's type, which is faithful to how SPG handles
7312            // untyped locals today (see 20.7). Full compile-time
7313            // catalog lookup queues with v7.40 PL/pgSQL epic.
7314            let ty = if matches!(self.peek(), Token::ColonEq | Token::Eq) {
7315                // Sentinel: `FunctionArgType::Raw("_infer_")` tells the
7316                // downstream declaration walker to type the local by
7317                // the runtime type of the default expression.
7318                FunctionArgType::Raw("_infer_".into())
7319            } else {
7320                let ty_token = self.expect_ident_like()?;
7321                // Detect `<ident>[.<ident>][%TYPE | %ROWTYPE]`:
7322                // consume optional `.<ident>` qualifier + `%<KW>`
7323                // suffix. Both qualifier and suffix map to _infer_.
7324                if matches!(self.peek(), Token::Dot) {
7325                    self.advance();
7326                    let _ = self.expect_ident_like()?;
7327                }
7328                if matches!(self.peek(), Token::Percent) {
7329                    self.advance();
7330                    // Consume the trailing TYPE / ROWTYPE ident.
7331                    let _ = self.expect_ident_like()?;
7332                    FunctionArgType::Raw("_infer_".into())
7333                } else {
7334                    match map_type_ident_to_column_type_name(&ty_token) {
7335                        Some(t) => FunctionArgType::Typed(t),
7336                        None => FunctionArgType::Raw(ty_token),
7337                    }
7338                }
7339            };
7340            let default = match self.peek() {
7341                Token::ColonEq => {
7342                    self.advance();
7343                    Some(self.parse_expr(0)?)
7344                }
7345                Token::Eq => {
7346                    // PL/pgSQL also accepts `=` for the
7347                    // DECLARE default (PG treats them the same
7348                    // in this position).
7349                    self.advance();
7350                    Some(self.parse_expr(0)?)
7351                }
7352                _ => None,
7353            };
7354            // Mandatory `;` between declarations.
7355            if !matches!(self.peek(), Token::Semicolon) {
7356                return Err(self.err(alloc::format!(
7357                    "expected ; after DECLARE entry for {name:?}, got {:?}",
7358                    self.peek()
7359                )));
7360            }
7361            self.advance();
7362            out.push(PlPgSqlDeclare { name, ty, default });
7363        }
7364    }
7365
7366    /// v7.12.6 — parse PL/pgSQL statements up to (and consuming)
7367    /// the terminating `END;` (or `END IF;` etc — handled by the
7368    /// per-construct sub-parsers). Used by both the outer block
7369    /// and the IF/ELSE branch bodies.
7370    fn parse_plpgsql_stmt_list_until_end(&mut self) -> Result<Vec<PlPgSqlStmt>, ParseError> {
7371        let mut statements: Vec<PlPgSqlStmt> = Vec::new();
7372        loop {
7373            // Allow trailing semicolons + END.
7374            while matches!(self.peek(), Token::Semicolon) {
7375                self.advance();
7376            }
7377            // END / ELSE / ELSIF / EXCEPTION — handled by the caller.
7378            if matches!(
7379                self.peek(),
7380                Token::Ident(s) | Token::QuotedIdent(s)
7381                    if s.eq_ignore_ascii_case("end")
7382                        || s.eq_ignore_ascii_case("else")
7383                        || s.eq_ignore_ascii_case("elsif")
7384                        || s.eq_ignore_ascii_case("elseif")
7385                        || s.eq_ignore_ascii_case("exception")
7386                        || s.eq_ignore_ascii_case("when")
7387            ) {
7388                return Ok(statements);
7389            }
7390            // Otherwise: one statement, then expect `;` or
7391            // a block-terminator keyword.
7392            let stmt = self.parse_plpgsql_stmt()?;
7393            statements.push(stmt);
7394            match self.peek() {
7395                Token::Semicolon => {
7396                    self.advance();
7397                }
7398                Token::Ident(s) | Token::QuotedIdent(s)
7399                    if s.eq_ignore_ascii_case("end")
7400                        || s.eq_ignore_ascii_case("else")
7401                        || s.eq_ignore_ascii_case("elsif")
7402                        || s.eq_ignore_ascii_case("elseif")
7403                        || s.eq_ignore_ascii_case("exception")
7404                        || s.eq_ignore_ascii_case("when") =>
7405                {
7406                    // Final statement of the block without `;`.
7407                }
7408                other => {
7409                    return Err(self.err(alloc::format!(
7410                        "expected ; or END/ELSE/ELSIF after plpgsql statement, got {other:?}"
7411                    )));
7412                }
7413            }
7414        }
7415    }
7416
7417    fn parse_plpgsql_stmt(&mut self) -> Result<PlPgSqlStmt, ParseError> {
7418        // RETURN keyword?
7419        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("return"))
7420        {
7421            self.advance();
7422            return self.parse_plpgsql_return();
7423        }
7424        // v7.12.6 — IF block.
7425        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("if"))
7426        {
7427            self.advance();
7428            return self.parse_plpgsql_if();
7429        }
7430        // v7.37.20 (20.6) — FOR <var> IN EXECUTE <string_expr> LOOP.
7431        // Detected by peeking that token pos+3 is Ident("execute").
7432        if matches!(self.peek(), Token::For)
7433            && matches!(
7434                self.tokens.get(self.pos + 1),
7435                Some(Token::Ident(_) | Token::QuotedIdent(_))
7436            )
7437            && matches!(self.tokens.get(self.pos + 2), Some(Token::In))
7438            && matches!(
7439                self.tokens.get(self.pos + 3),
7440                Some(Token::Ident(s) | Token::QuotedIdent(s)) if s.eq_ignore_ascii_case("execute")
7441            )
7442        {
7443            self.advance(); // FOR
7444            let var = self.expect_ident_like()?;
7445            self.advance(); // IN
7446            self.advance(); // EXECUTE
7447            // Prescan for LOOP at paren depth 0 so parse_expr stops
7448            // before the LOOP keyword (same trick as the bare-SELECT
7449            // ForQuery arm).
7450            let mut depth: i32 = 0;
7451            let mut loop_pos: Option<usize> = None;
7452            let mut scan = self.pos;
7453            while scan < self.tokens.len() {
7454                match self.tokens.get(scan) {
7455                    Some(Token::LParen) => depth += 1,
7456                    Some(Token::RParen) => depth -= 1,
7457                    Some(Token::Ident(s) | Token::QuotedIdent(s))
7458                        if depth == 0 && s.eq_ignore_ascii_case("loop") =>
7459                    {
7460                        loop_pos = Some(scan);
7461                        break;
7462                    }
7463                    _ => {}
7464                }
7465                scan += 1;
7466            }
7467            let loop_pos = loop_pos.ok_or_else(|| {
7468                self.err(alloc::format!(
7469                    "FOR <var> IN EXECUTE <expr> ... LOOP: no LOOP keyword found"
7470                ))
7471            })?;
7472            let saved_loop = self.tokens[loop_pos].clone();
7473            self.tokens[loop_pos] = Token::Semicolon;
7474            let expr_result = self.parse_expr(0);
7475            self.tokens[loop_pos] = saved_loop;
7476            let sql_expr = expr_result?;
7477            let loop_kw = self.expect_ident_like()?;
7478            if !loop_kw.eq_ignore_ascii_case("loop") {
7479                return Err(self.err(alloc::format!(
7480                    "expected LOOP after FOR <var> IN EXECUTE <expr>, got {loop_kw:?}"
7481                )));
7482            }
7483            let body = self.parse_plpgsql_stmt_list_until_end()?;
7484            let end_kw = self.expect_ident_like()?;
7485            if !end_kw.eq_ignore_ascii_case("end") {
7486                return Err(self.err(alloc::format!(
7487                    "expected END LOOP after FOR IN EXECUTE body, got {end_kw:?}"
7488                )));
7489            }
7490            let loop_kw2 = self.expect_ident_like()?;
7491            if !loop_kw2.eq_ignore_ascii_case("loop") {
7492                return Err(self.err(alloc::format!(
7493                    "expected END LOOP after FOR IN EXECUTE body, got END {loop_kw2:?}"
7494                )));
7495            }
7496            return Ok(PlPgSqlStmt::ForExecute {
7497                var,
7498                sql_expr,
7499                body,
7500            });
7501        }
7502        // v7.37.20 (20.5) — FOR <var> IN <SELECT> LOOP.
7503        //
7504        // Two syntactic forms:
7505        //   FOR var IN SELECT ... ORDER BY ... LOOP ...
7506        //   FOR var IN (SELECT ...) LOOP ...
7507        //
7508        // Bare-SELECT form: to keep parse_select_stmt from swallowing
7509        // the trailing `LOOP` keyword as a table alias, we prescan
7510        // forward to find LOOP at paren depth 0, splice a fake
7511        // Semicolon at that position (so SELECT parses cleanly),
7512        // then re-splice LOOP back in.
7513        //
7514        // Paren-wrapped form: parse `(` `SELECT ...` `)` then expect
7515        // LOOP directly — no scan required.
7516        if matches!(self.peek(), Token::For)
7517            && matches!(
7518                self.tokens.get(self.pos + 1),
7519                Some(Token::Ident(_) | Token::QuotedIdent(_))
7520            )
7521            && matches!(self.tokens.get(self.pos + 2), Some(Token::In))
7522            && (matches!(self.tokens.get(self.pos + 3), Some(Token::Select))
7523                || matches!(self.tokens.get(self.pos + 3), Some(Token::LParen)))
7524        {
7525            self.advance(); // FOR
7526            let var = self.expect_ident_like()?;
7527            // IN
7528            self.advance();
7529            let query = if matches!(self.peek(), Token::LParen) {
7530                // Paren-wrapped SELECT.
7531                self.advance();
7532                let inner = self.parse_select_stmt()?;
7533                let Statement::Select(q) = inner else {
7534                    return Err(self.err(alloc::format!(
7535                        "expected SELECT inside (…), got {:?}",
7536                        self.peek()
7537                    )));
7538                };
7539                if !matches!(self.peek(), Token::RParen) {
7540                    return Err(self.err(alloc::format!(
7541                        "expected ')' after FOR-IN-SELECT body, got {:?}",
7542                        self.peek()
7543                    )));
7544                }
7545                self.advance();
7546                q
7547            } else {
7548                // Bare SELECT: prescan to find the LOOP boundary.
7549                let mut depth: i32 = 0;
7550                let mut loop_pos: Option<usize> = None;
7551                let mut scan = self.pos;
7552                while scan < self.tokens.len() {
7553                    match self.tokens.get(scan) {
7554                        Some(Token::LParen) => depth += 1,
7555                        Some(Token::RParen) => depth -= 1,
7556                        Some(Token::Ident(s) | Token::QuotedIdent(s))
7557                            if depth == 0 && s.eq_ignore_ascii_case("loop") =>
7558                        {
7559                            loop_pos = Some(scan);
7560                            break;
7561                        }
7562                        _ => {}
7563                    }
7564                    scan += 1;
7565                }
7566                let loop_pos = loop_pos.ok_or_else(|| {
7567                    self.err(alloc::format!(
7568                        "FOR <var> IN <SELECT> ... LOOP: no LOOP keyword found"
7569                    ))
7570                })?;
7571                // Swap the LOOP token with a synthetic Semicolon so
7572                // parse_select_stmt stops there, then restore afterward.
7573                let saved_loop = self.tokens[loop_pos].clone();
7574                self.tokens[loop_pos] = Token::Semicolon;
7575                let parse_result = self.parse_select_stmt();
7576                self.tokens[loop_pos] = saved_loop;
7577                let inner = parse_result?;
7578                let Statement::Select(q) = inner else {
7579                    return Err(self.err(alloc::format!(
7580                        "expected SELECT after FOR <var> IN, got {:?}",
7581                        self.peek()
7582                    )));
7583                };
7584                q
7585            };
7586            let loop_kw = self.expect_ident_like()?;
7587            if !loop_kw.eq_ignore_ascii_case("loop") {
7588                return Err(self.err(alloc::format!(
7589                    "expected LOOP after FOR <var> IN <SELECT>, got {loop_kw:?}"
7590                )));
7591            }
7592            let body = self.parse_plpgsql_stmt_list_until_end()?;
7593            let end_kw = self.expect_ident_like()?;
7594            if !end_kw.eq_ignore_ascii_case("end") {
7595                return Err(self.err(alloc::format!(
7596                    "expected END LOOP after FOR IN SELECT body, got {end_kw:?}"
7597                )));
7598            }
7599            let loop_kw2 = self.expect_ident_like()?;
7600            if !loop_kw2.eq_ignore_ascii_case("loop") {
7601                return Err(self.err(alloc::format!(
7602                    "expected END LOOP after FOR IN SELECT body, got END {loop_kw2:?}"
7603                )));
7604            }
7605            return Ok(PlPgSqlStmt::ForQuery {
7606                var,
7607                query: Box::new(query),
7608                body,
7609            });
7610        }
7611        // v7.37.20 (20.4) — FOR <var> IN [REVERSE] <start>..<end> LOOP.
7612        // FOR is a reserved keyword token (Token::For).
7613        if matches!(self.peek(), Token::For)
7614            && matches!(
7615                self.tokens.get(self.pos + 1),
7616                Some(Token::Ident(_) | Token::QuotedIdent(_))
7617            )
7618            && matches!(self.tokens.get(self.pos + 2), Some(Token::In))
7619        {
7620            self.advance(); // FOR
7621            let var = self.expect_ident_like()?;
7622            if !matches!(self.peek(), Token::In) {
7623                return Err(self.err(alloc::format!(
7624                    "expected IN after FOR <var>, got {:?}",
7625                    self.peek()
7626                )));
7627            }
7628            self.advance();
7629            let reverse = matches!(
7630                self.peek(),
7631                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("reverse")
7632            );
7633            if reverse {
7634                self.advance();
7635            }
7636            let start = self.parse_expr(0)?;
7637            if !matches!(self.peek(), Token::DotDot) {
7638                return Err(self.err(alloc::format!(
7639                    "expected '..' between FOR loop bounds, got {:?}",
7640                    self.peek()
7641                )));
7642            }
7643            self.advance();
7644            let end = self.parse_expr(0)?;
7645            let loop_kw = self.expect_ident_like()?;
7646            if !loop_kw.eq_ignore_ascii_case("loop") {
7647                return Err(self.err(alloc::format!(
7648                    "expected LOOP after FOR <var> IN start..end, got {loop_kw:?}"
7649                )));
7650            }
7651            let body = self.parse_plpgsql_stmt_list_until_end()?;
7652            let end_kw = self.expect_ident_like()?;
7653            if !end_kw.eq_ignore_ascii_case("end") {
7654                return Err(self.err(alloc::format!(
7655                    "expected END LOOP after FOR body, got {end_kw:?}"
7656                )));
7657            }
7658            let loop_kw2 = self.expect_ident_like()?;
7659            if !loop_kw2.eq_ignore_ascii_case("loop") {
7660                return Err(self.err(alloc::format!(
7661                    "expected END LOOP after FOR body, got END {loop_kw2:?}"
7662                )));
7663            }
7664            return Ok(PlPgSqlStmt::ForRange {
7665                var,
7666                start,
7667                end,
7668                reverse,
7669                body,
7670            });
7671        }
7672        // v7.37.20 (20.2) — bare `LOOP <body> END LOOP;`.
7673        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("loop"))
7674        {
7675            self.advance();
7676            let body = self.parse_plpgsql_stmt_list_until_end()?;
7677            let end_kw = self.expect_ident_like()?;
7678            if !end_kw.eq_ignore_ascii_case("end") {
7679                return Err(self.err(alloc::format!(
7680                    "expected END LOOP after LOOP body, got {end_kw:?}"
7681                )));
7682            }
7683            let loop_kw = self.expect_ident_like()?;
7684            if !loop_kw.eq_ignore_ascii_case("loop") {
7685                return Err(self.err(alloc::format!(
7686                    "expected END LOOP after LOOP body, got END {loop_kw:?}"
7687                )));
7688            }
7689            return Ok(PlPgSqlStmt::Loop { body });
7690        }
7691        // v7.37.20 (20.2) — `EXIT [WHEN <cond>]` inside a loop.
7692        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("exit"))
7693        {
7694            self.advance();
7695            let when = if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("when"))
7696            {
7697                self.advance();
7698                Some(self.parse_expr(0)?)
7699            } else {
7700                None
7701            };
7702            return Ok(PlPgSqlStmt::Exit { when });
7703        }
7704        // v7.37.20 (20.13) — `EXECUTE <string_expr>`. Dispatches an
7705        // already-parsed Statement or a runtime-computed SQL string.
7706        // The disambiguator vs the extended-query-protocol `EXECUTE
7707        // <stmt_name>` (which is a top-level Statement, not a
7708        // plpgsql line) is that inside a DO block / trigger body the
7709        // EXECUTE keyword ALWAYS refers to dynamic SQL.
7710        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("execute"))
7711        {
7712            self.advance();
7713            let sql = self.parse_expr(0)?;
7714            return Ok(PlPgSqlStmt::ExecuteDynamic { sql });
7715        }
7716        // v7.37.20 (20.2) — `CONTINUE [WHEN <cond>]` inside a loop.
7717        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("continue"))
7718        {
7719            self.advance();
7720            let when = if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("when"))
7721            {
7722                self.advance();
7723                Some(self.parse_expr(0)?)
7724            } else {
7725                None
7726            };
7727            return Ok(PlPgSqlStmt::Continue { when });
7728        }
7729        // v7.37.20 (20.3) — WHILE <cond> LOOP <body> END LOOP.
7730        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("while"))
7731        {
7732            self.advance();
7733            let condition = self.parse_expr(0)?;
7734            let loop_kw = self.expect_ident_like()?;
7735            if !loop_kw.eq_ignore_ascii_case("loop") {
7736                return Err(self.err(alloc::format!(
7737                    "expected LOOP after WHILE <condition>, got {loop_kw:?}"
7738                )));
7739            }
7740            let body = self.parse_plpgsql_stmt_list_until_end()?;
7741            // Expect END LOOP.
7742            let end_kw = self.expect_ident_like()?;
7743            if !end_kw.eq_ignore_ascii_case("end") {
7744                return Err(self.err(alloc::format!(
7745                    "expected END LOOP after WHILE body, got {end_kw:?}"
7746                )));
7747            }
7748            let loop_kw2 = self.expect_ident_like()?;
7749            if !loop_kw2.eq_ignore_ascii_case("loop") {
7750                return Err(self.err(alloc::format!(
7751                    "expected END LOOP after WHILE body, got END {loop_kw2:?}"
7752                )));
7753            }
7754            return Ok(PlPgSqlStmt::While { condition, body });
7755        }
7756        // v7.12.6 — RAISE.
7757        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("raise"))
7758        {
7759            self.advance();
7760            return self.parse_plpgsql_raise();
7761        }
7762        // v7.37.20 (20.14) — ASSERT <cond> [, <msg>].
7763        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("assert"))
7764        {
7765            self.advance();
7766            let condition = self.parse_expr(0)?;
7767            let message = if matches!(self.peek(), Token::Comma) {
7768                self.advance();
7769                Some(self.parse_expr(0)?)
7770            } else {
7771                None
7772            };
7773            return Ok(PlPgSqlStmt::Assert { condition, message });
7774        }
7775        // v7.37.20 (20.12) — PERFORM <select>. Per PG docs:
7776        //   "PERFORM is equivalent to SELECT but discards the
7777        //    result." Side effects (function calls, RAISE inside
7778        //    SQL functions, etc.) still execute. We desugar to
7779        //    `SELECT <body>` and wrap in EmbeddedSql so the engine's
7780        //    existing embedded-statement path handles execution +
7781        //    result-discard cleanly. The result is naturally
7782        //    discarded because EmbeddedSql doesn't propagate row
7783        //    sets back to the plpgsql interpreter.
7784        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("perform"))
7785        {
7786            self.advance();
7787            // Splice a synthetic Token::Select into the stream at
7788            // the current position so parse_select_stmt parses the
7789            // remainder as a normal SELECT body. Token-stream
7790            // surgery mirrors the try_parse_plpgsql_select_into
7791            // pattern used for SELECT … INTO desugaring.
7792            self.tokens.insert(self.pos, Token::Select);
7793            let select = self.parse_select_stmt()?;
7794            let Statement::Select(s) = select else {
7795                return Err(self.err(alloc::format!(
7796                    "expected SELECT body after PERFORM, got {:?}",
7797                    self.peek()
7798                )));
7799            };
7800            return Ok(PlPgSqlStmt::EmbeddedSql(Box::new(Statement::Select(s))));
7801        }
7802        // v7.16.2 — `SELECT <projection> INTO <var> [FROM …]`
7803        // plpgsql-specific shape (mailrs round-10 migrate-042).
7804        // PG's SELECT INTO at top-level SQL would CREATE a new
7805        // table; inside plpgsql it ASSIGNS the query result to
7806        // a local variable. We detect the INTO at paren-depth
7807        // 0 between SELECT and the statement boundary; if
7808        // found, split the token stream into "pre-INTO
7809        // projection" + "var" + "post-INTO FROM/WHERE…" and
7810        // rebuild as a SelectInto with a regular SELECT body
7811        // (no INTO clause).
7812        if matches!(self.peek(), Token::Select)
7813            && let Some((select_body, var_name)) = self.try_parse_plpgsql_select_into()?
7814        {
7815            return Ok(PlPgSqlStmt::SelectInto {
7816                var: var_name,
7817                body: Box::new(select_body),
7818            });
7819        }
7820        // v7.12.6 — embedded SQL statements. INSERT/UPDATE/DELETE/
7821        // SELECT can appear directly inside a trigger body; we
7822        // recurse into the regular Statement parser, which will
7823        // stop at the trailing `;` (which our caller then
7824        // consumes).
7825        // v7.16.2 — top-level DO blocks (mailrs round-10 A.2)
7826        // also embed ALTER / CREATE / DROP statements; route
7827        // those through the same parser so the DO body parses
7828        // cleanly.
7829        if matches!(self.peek(), Token::Insert)
7830            || matches!(self.peek(), Token::Select)
7831            || matches!(self.peek(), Token::Create)
7832            || matches!(self.peek(), Token::Drop)
7833            || matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
7834                if s.eq_ignore_ascii_case("update")
7835                    || s.eq_ignore_ascii_case("delete")
7836                    || s.eq_ignore_ascii_case("alter"))
7837        {
7838            let stmt = self.parse_one_statement()?;
7839            return Ok(PlPgSqlStmt::EmbeddedSql(Box::new(stmt)));
7840        }
7841        // Otherwise: assignment. `NEW.col` / `OLD.col` / `var`
7842        // followed by `:=` and an expression.
7843        let target = self.parse_plpgsql_assign_target()?;
7844        // PL/pgSQL assignment uses `:=`. The lexer represents
7845        // this as a colon followed by `=`; check both shapes.
7846        match self.peek() {
7847            Token::ColonEq => {
7848                self.advance();
7849            }
7850            Token::Colon => {
7851                self.advance();
7852                if !matches!(self.peek(), Token::Eq) {
7853                    return Err(self.err(alloc::format!(
7854                        "expected := after plpgsql assign target, got `:` then {:?}",
7855                        self.peek()
7856                    )));
7857                }
7858                self.advance();
7859            }
7860            other => {
7861                return Err(self.err(alloc::format!(
7862                    "expected := after plpgsql assign target, got {other:?}"
7863                )));
7864            }
7865        }
7866        let value = self.parse_expr(0)?;
7867        Ok(PlPgSqlStmt::Assign { target, value })
7868    }
7869
7870    /// v7.12.6 — `IF cond THEN body [ELSIF cond THEN body]*
7871    /// [ELSE body] END IF`. `IF` keyword already consumed.
7872    fn parse_plpgsql_if(&mut self) -> Result<PlPgSqlStmt, ParseError> {
7873        let mut branches: Vec<(Expr, Vec<PlPgSqlStmt>)> = Vec::new();
7874        let mut else_branch: Vec<PlPgSqlStmt> = Vec::new();
7875        loop {
7876            // <expr> THEN
7877            let cond = self.parse_expr(0)?;
7878            let then_kw = self.expect_ident_like()?;
7879            if !then_kw.eq_ignore_ascii_case("then") {
7880                return Err(self.err(alloc::format!(
7881                    "expected THEN after IF/ELSIF condition, got {then_kw:?}"
7882                )));
7883            }
7884            let body = self.parse_plpgsql_stmt_list_until_end()?;
7885            branches.push((cond, body));
7886            // Look at terminator: ELSIF/ELSEIF, ELSE, or END IF.
7887            match self.peek() {
7888                Token::Ident(s) | Token::QuotedIdent(s)
7889                    if s.eq_ignore_ascii_case("elsif") || s.eq_ignore_ascii_case("elseif") =>
7890                {
7891                    self.advance();
7892                    continue;
7893                }
7894                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("else") => {
7895                    self.advance();
7896                    else_branch = self.parse_plpgsql_stmt_list_until_end()?;
7897                    break;
7898                }
7899                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("end") => {
7900                    break;
7901                }
7902                other => {
7903                    return Err(self.err(alloc::format!(
7904                        "expected ELSIF / ELSE / END after IF branch body, got {other:?}"
7905                    )));
7906                }
7907            }
7908        }
7909        // Expect `END IF` (the END keyword is the one we're
7910        // looking at right now).
7911        let end_kw = self.expect_ident_like()?;
7912        if !end_kw.eq_ignore_ascii_case("end") {
7913            return Err(self.err(alloc::format!("expected END IF, got {end_kw:?}")));
7914        }
7915        let if_kw = self.expect_ident_like()?;
7916        if !if_kw.eq_ignore_ascii_case("if") {
7917            return Err(self.err(alloc::format!("expected END IF, got END {if_kw:?}")));
7918        }
7919        Ok(PlPgSqlStmt::If {
7920            branches,
7921            else_branch,
7922        })
7923    }
7924
7925    /// v7.12.6 — `RAISE { NOTICE | WARNING | INFO | LOG | DEBUG
7926    /// | EXCEPTION } '<message>' [, args]*`. The `RAISE` keyword
7927    /// is already consumed.
7928    fn parse_plpgsql_raise(&mut self) -> Result<PlPgSqlStmt, ParseError> {
7929        let lvl_ident = self.expect_ident_like()?;
7930        let level = match lvl_ident.to_ascii_lowercase().as_str() {
7931            "notice" => RaiseLevel::Notice,
7932            "warning" => RaiseLevel::Warning,
7933            "info" => RaiseLevel::Info,
7934            "log" => RaiseLevel::Log,
7935            "debug" => RaiseLevel::Debug,
7936            "exception" => RaiseLevel::Exception,
7937            other => {
7938                return Err(self.err(alloc::format!(
7939                    "expected RAISE level (NOTICE/WARNING/INFO/LOG/DEBUG/EXCEPTION), got {other:?}"
7940                )));
7941            }
7942        };
7943        // Message: required for v7.12.6. PG accepts a bare
7944        // RAISE-rethrow form (no message), reserved for future
7945        // RAISE-no-args support.
7946        let Token::String(msg) = self.peek() else {
7947            return Err(self.err(alloc::format!(
7948                "expected RAISE message string, got {:?}",
7949                self.peek()
7950            )));
7951        };
7952        let message = msg.clone();
7953        self.advance();
7954        // Optional comma-separated args (PG `%` format substitution).
7955        let mut args: Vec<Expr> = Vec::new();
7956        while matches!(self.peek(), Token::Comma) {
7957            self.advance();
7958            args.push(self.parse_expr(0)?);
7959        }
7960        Ok(PlPgSqlStmt::Raise {
7961            level,
7962            message,
7963            args,
7964        })
7965    }
7966
7967    /// v7.16.2 — scan ahead for a plpgsql-flavoured `SELECT
7968    /// <projection> INTO <var> [FROM …]` (mailrs round-10
7969    /// migrate-042). Returns `(rebuilt_select_without_into,
7970    /// var_name)` when the pattern matches; `None` for
7971    /// regular SELECTs (those go through the embedded-SQL
7972    /// path). Token-stream surgery so the rebuilt SELECT
7973    /// parses through the regular `parse_select_stmt`.
7974    #[allow(clippy::too_many_lines)]
7975    fn try_parse_plpgsql_select_into(
7976        &mut self,
7977    ) -> Result<Option<(SelectStatement, String)>, ParseError> {
7978        // Scan forward from `self.pos + 1` (past Token::Select)
7979        // for Token::Into at paren-depth 0, stopping at the
7980        // first `;`, `END`, `ELSE`, `ELSIF` keyword that would
7981        // end the plpgsql statement.
7982        let start = self.pos;
7983        let mut into_pos: Option<usize> = None;
7984        let mut depth: i32 = 0;
7985        let mut i = start + 1;
7986        while i < self.tokens.len() {
7987            match &self.tokens[i] {
7988                Token::LParen => depth += 1,
7989                Token::RParen => depth -= 1,
7990                Token::Semicolon if depth == 0 => break,
7991                Token::Ident(s)
7992                    if depth == 0
7993                        && (s.eq_ignore_ascii_case("end")
7994                            || s.eq_ignore_ascii_case("else")
7995                            || s.eq_ignore_ascii_case("elsif")) =>
7996                {
7997                    break;
7998                }
7999                Token::Into if depth == 0 => {
8000                    into_pos = Some(i);
8001                    break;
8002                }
8003                _ => {}
8004            }
8005            i += 1;
8006        }
8007        let Some(into_at) = into_pos else {
8008            return Ok(None);
8009        };
8010        // The token immediately after INTO must be the target
8011        // var ident; anything else (e.g. INSERT INTO table)
8012        // ruled out by the depth-0 check above. Capture it.
8013        let var = match self.tokens.get(into_at + 1) {
8014            Some(Token::Ident(s) | Token::QuotedIdent(s)) => s.clone(),
8015            other => {
8016                return Err(self.err(alloc::format!(
8017                    "expected variable name after SELECT … INTO, got {other:?}"
8018                )));
8019            }
8020        };
8021        // Find the end of the plpgsql SELECT INTO statement —
8022        // same boundary rules as the depth-0 scan above.
8023        let mut end = into_at + 2;
8024        let mut depth2: i32 = 0;
8025        while end < self.tokens.len() {
8026            match &self.tokens[end] {
8027                Token::LParen => depth2 += 1,
8028                Token::RParen => depth2 -= 1,
8029                Token::Semicolon if depth2 == 0 => break,
8030                Token::Ident(s)
8031                    if depth2 == 0
8032                        && (s.eq_ignore_ascii_case("end")
8033                            || s.eq_ignore_ascii_case("else")
8034                            || s.eq_ignore_ascii_case("elsif")) =>
8035                {
8036                    break;
8037                }
8038                _ => {}
8039            }
8040            end += 1;
8041        }
8042        // Rebuild a token stream that represents the SELECT
8043        // WITHOUT the INTO clause: [SELECT .. up-to-INTO] + [
8044        // post-var tokens up to statement end]. Run the
8045        // regular `parse_select_stmt` against it.
8046        let mut rebuilt: Vec<Token> = Vec::with_capacity(end - start);
8047        for j in start..into_at {
8048            rebuilt.push(self.tokens[j].clone());
8049        }
8050        for j in (into_at + 2)..end {
8051            rebuilt.push(self.tokens[j].clone());
8052        }
8053        rebuilt.push(Token::Eof);
8054        let saved_pos = self.pos;
8055        let saved_tokens = core::mem::replace(&mut self.tokens, rebuilt);
8056        self.pos = 0;
8057        // parse_select_stmt → parse_bare_select consumes Token::Select itself.
8058        if !matches!(self.peek(), Token::Select) {
8059            self.tokens = saved_tokens;
8060            self.pos = saved_pos;
8061            return Err(self.err("plpgsql SELECT … INTO: rebuilt stream missing SELECT".into()));
8062        }
8063        let sel = self.parse_select_stmt();
8064        self.tokens = saved_tokens;
8065        self.pos = end;
8066        let sel = sel?;
8067        let Statement::Select(body) = sel else {
8068            return Err(self.err(alloc::format!(
8069                "plpgsql SELECT … INTO: rebuilt SELECT did not produce a Select node, got {sel:?}"
8070            )));
8071        };
8072        Ok(Some((body, var)))
8073    }
8074
8075    fn parse_plpgsql_assign_target(&mut self) -> Result<AssignTarget, ParseError> {
8076        // v7.16.1 — read the head token DIRECTLY rather than
8077        // via `expect_ident_like`. The v7.14.0 schema-qualifier
8078        // strip (`public.t` → `t`) inside `expect_ident_like`
8079        // greedily consumes any `ident . ident` pair, which
8080        // silently turned every `NEW.col := …` /
8081        // `OLD.col := …` plpgsql assignment into a Local("col")
8082        // assignment — the head "new"/"old" was eaten as if it
8083        // were a schema name and the Dot was consumed too, so
8084        // this function's own `peek() == Token::Dot` check
8085        // below never fired. Every BEFORE trigger that rewrote
8086        // a NEW cell was a silent no-op for two major releases
8087        // (v7.14.0 + v7.15.0) until the e2e_trigger workspace-
8088        // gate failures were investigated as v7.16.1 backlog.
8089        let head = match self.advance() {
8090            Token::Ident(s) | Token::QuotedIdent(s) => s,
8091            other => {
8092                return Err(self.err(alloc::format!(
8093                    "expected NEW / OLD / <local_var> as plpgsql assign target, got {other:?}"
8094                )));
8095            }
8096        };
8097        if matches!(self.peek(), Token::Dot) {
8098            self.advance();
8099            let col = self.expect_ident_like()?;
8100            if head.eq_ignore_ascii_case("new") {
8101                return Ok(AssignTarget::NewColumn(col));
8102            }
8103            if head.eq_ignore_ascii_case("old") {
8104                return Ok(AssignTarget::OldColumn(col));
8105            }
8106            return Err(self.err(alloc::format!(
8107                "plpgsql assign target must be NEW.<col> / OLD.<col> / <local_var>; \
8108                 got {head:?}.<col>"
8109            )));
8110        }
8111        Ok(AssignTarget::Local(head))
8112    }
8113
8114    fn parse_plpgsql_return(&mut self) -> Result<PlPgSqlStmt, ParseError> {
8115        // RETURN NEW / OLD / NULL — bare-ident forms.
8116        match self.peek() {
8117            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("new") => {
8118                self.advance();
8119                return Ok(PlPgSqlStmt::Return(ReturnTarget::New));
8120            }
8121            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("old") => {
8122                self.advance();
8123                return Ok(PlPgSqlStmt::Return(ReturnTarget::Old));
8124            }
8125            Token::Null => {
8126                self.advance();
8127                return Ok(PlPgSqlStmt::Return(ReturnTarget::Null));
8128            }
8129            // Bare `RETURN;` (no value) — treated as `RETURN NULL`
8130            // per PL/pgSQL convention.
8131            Token::Semicolon => {
8132                return Ok(PlPgSqlStmt::Return(ReturnTarget::Null));
8133            }
8134            _ => {}
8135        }
8136        // v7.37.20 (20.11) — RETURN QUERY <select> / RETURN QUERY
8137        // EXECUTE <expr>. In a DO block context RETURN QUERY has no
8138        // caller-visible effect (blocks don't return sets), so we
8139        // desugar it identically to PERFORM: parse the SELECT (or
8140        // EXECUTE dynamic) as embedded SQL that runs for side
8141        // effects and discards the result. RETURN NEXT <expr>
8142        // (single-row accumulator) queues with v7.40 SETOF function
8143        // infrastructure.
8144        // v7.39 (read01 round 66) — `RETURN NEXT <expr>`: append a row to the set
8145        // and keep going.
8146        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("next"))
8147        {
8148            self.advance();
8149            let e = self.parse_expr(0)?;
8150            return Ok(PlPgSqlStmt::ReturnNext(e));
8151        }
8152        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("query"))
8153        {
8154            self.advance();
8155            // v7.39 (read01 round 68) — `RETURN QUERY EXECUTE <sql expr>`: the
8156            // rows go to the set, like the static form. It used to desugar to a
8157            // bare ExecuteDynamic, whose result was DISCARDED.
8158            if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("execute"))
8159            {
8160                self.advance();
8161                let sql = self.parse_expr(0)?;
8162                return Ok(PlPgSqlStmt::ReturnQueryExecute { sql });
8163            }
8164            // Bare RETURN QUERY <select>. If the current token is
8165            // not already SELECT (e.g., the user wrote `RETURN QUERY
8166            // <projection> FROM ...` in a shorthand — rare but PG
8167            // accepts a bare projection here), splice one in. Same
8168            // trick as PERFORM.
8169            if !matches!(self.peek(), Token::Select) {
8170                self.tokens.insert(self.pos, Token::Select);
8171            }
8172            let select = self.parse_select_stmt()?;
8173            let Statement::Select(s) = select else {
8174                return Err(self.err(alloc::format!(
8175                    "expected SELECT body after RETURN QUERY, got {:?}",
8176                    self.peek()
8177                )));
8178            };
8179            // v7.39 (read01 round 66) — a REAL statement now. It used to desugar
8180            // to an embedded side-effect SELECT whose rows were DISCARDED, which
8181            // in a SETOF function is the entire answer thrown away.
8182            return Ok(PlPgSqlStmt::ReturnQuery(Box::new(s)));
8183        }
8184        // Fall through: parse a full expression.
8185        let e = self.parse_expr(0)?;
8186        Ok(PlPgSqlStmt::Return(ReturnTarget::Expr(e)))
8187    }
8188
8189    fn parse_trigger_event(&mut self) -> Result<TriggerEvent, ParseError> {
8190        // INSERT is a reserved Token; UPDATE / DELETE / TRUNCATE
8191        // are ident-shaped (the parser keys off case-insensitive
8192        // match — same shape used by the top-level Update / Delete
8193        // dispatchers at parse_one_statement).
8194        if matches!(self.peek(), Token::Insert) {
8195            self.advance();
8196            return Ok(TriggerEvent::Insert);
8197        }
8198        match self.peek() {
8199            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("update") => {
8200                self.advance();
8201                Ok(TriggerEvent::Update)
8202            }
8203            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("delete") => {
8204                self.advance();
8205                Ok(TriggerEvent::Delete)
8206            }
8207            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("truncate") => {
8208                self.advance();
8209                Ok(TriggerEvent::Truncate)
8210            }
8211            other => Err(self.err(alloc::format!(
8212                "expected INSERT / UPDATE / DELETE / TRUNCATE in trigger event list, got {other:?}"
8213            ))),
8214        }
8215    }
8216
8217    /// v6.1.2 → v6.1.3 — `CREATE PUBLICATION <name>` body. Accepts:
8218    ///   - (no clause) → implicit `FOR ALL TABLES`
8219    ///   - `FOR ALL TABLES`
8220    ///   - `FOR ALL TABLES EXCEPT t1, t2, …` (v6.1.3)
8221    ///   - `FOR TABLE t1, t2, …` (v6.1.3) — `FOR TABLES …` also
8222    ///     accepted as an SPG lenience. PG18-measured (round 753): PG
8223    ///     REJECTS the bare plural (`invalid publication object list`,
8224    ///     TABLES only pairs with IN SCHEMA); the old note claimed an
8225    ///     unverifiable "PG 19 accepts both". Ledgered, not load-bearing.
8226    fn parse_create_publication_after_keyword(&mut self) -> Result<Statement, ParseError> {
8227        let name = self.expect_ident_or_string()?;
8228        // Bare DDL maps to FOR ALL TABLES — matches the v6.1.2
8229        // shape so existing publications keep parsing identically.
8230        let scope = if matches!(self.peek(), Token::For) {
8231            self.advance();
8232            if matches!(self.peek(), Token::All) {
8233                self.advance();
8234                if !matches!(self.peek(), Token::Tables) {
8235                    return Err(self.err(format!(
8236                        "expected TABLES after FOR ALL, got {:?}",
8237                        self.peek()
8238                    )));
8239                }
8240                self.advance();
8241                if matches!(self.peek(), Token::Except) {
8242                    self.advance();
8243                    let tables = self.parse_publication_table_list()?;
8244                    PublicationScope::AllTablesExcept(tables)
8245                } else {
8246                    PublicationScope::AllTables
8247                }
8248            } else if matches!(self.peek(), Token::Table) {
8249                self.advance();
8250                let tables = self.parse_publication_table_list()?;
8251                PublicationScope::ForTables(tables)
8252            } else if matches!(self.peek(), Token::Tables) {
8253                // v7.39 (round 754, F31-B5) — PG18-measured: the bare
8254                // plural (`FOR TABLES t`) is REJECTED (`invalid
8255                // publication object list`); TABLES only pairs with
8256                // `IN SCHEMA`. The old arm accepted it on an
8257                // unverifiable "PG 19 accepts both" claim.
8258                self.advance();
8259                if !matches!(self.peek(), Token::In) {
8260                    return Err(self.err(alloc::string::String::from(
8261                        "invalid publication object list",
8262                    )));
8263                }
8264                self.advance();
8265                if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("schema")) {
8266                    return Err(self.err(format!(
8267                        "expected SCHEMA after FOR TABLES IN, got {:?}",
8268                        self.peek()
8269                    )));
8270                }
8271                self.advance();
8272                let schema = self.expect_ident_or_string()?;
8273                PublicationScope::TablesInSchema(schema)
8274            } else {
8275                return Err(self.err(format!(
8276                    "expected ALL TABLES or TABLE <list> after FOR, got {:?}",
8277                    self.peek()
8278                )));
8279            }
8280        } else {
8281            PublicationScope::AllTables
8282        };
8283        Ok(Statement::CreatePublication(CreatePublicationStatement {
8284            name,
8285            scope,
8286        }))
8287    }
8288
8289    /// v6.1.3 — Comma-separated identifier list for the publication
8290    /// FOR-clause. Requires at least one entry; empty list is a
8291    /// parse error (PG behaviour). Quoted idents are accepted; the
8292    /// names round-trip through `Display` as `quote_ident(name)`.
8293    ///
8294    /// v7.37.21 (21.2 + 21.3) — accept-and-discard the per-table
8295    /// `(col_list) WHERE (predicate)` modifiers PG 15+ emits in
8296    /// pg_dump output. SPG's publication state today is per-table
8297    /// only (matching the pre-PG-15 surface); the col list + WHERE
8298    /// are parsed so dumps load through and the table name reaches
8299    /// `PublicationScope::ForTables`, but the filter is not enforced
8300    /// at publish time. Re-open when a customer dogfood gate
8301    /// requires per-row-filter or column-subset publish semantics
8302    /// (which gates on persistent slot state landing first, 21.12).
8303    fn parse_publication_table_list(&mut self) -> Result<Vec<String>, ParseError> {
8304        let first = self.parse_publication_table_entry()?;
8305        let mut out = alloc::vec![first];
8306        while matches!(self.peek(), Token::Comma) {
8307            self.advance();
8308            out.push(self.parse_publication_table_entry()?);
8309        }
8310        Ok(out)
8311    }
8312
8313    /// One table entry inside a FOR TABLE clause:
8314    ///     tab_name [ (col, col, …) ] [ WHERE (predicate) ]
8315    /// Returns just the table name; the column list + WHERE predicate
8316    /// are consumed and discarded per the parse-accept-discard
8317    /// commitment above.
8318    fn parse_publication_table_entry(&mut self) -> Result<String, ParseError> {
8319        let name = self.expect_ident_like()?;
8320        // Optional column list — `(col, col, …)`.
8321        if matches!(self.peek(), Token::LParen) {
8322            self.advance();
8323            // Empty parens are a PG error too; require ≥ 1 column.
8324            let _ = self.expect_ident_like()?;
8325            while matches!(self.peek(), Token::Comma) {
8326                self.advance();
8327                let _ = self.expect_ident_like()?;
8328            }
8329            if !matches!(self.peek(), Token::RParen) {
8330                return Err(self.err(alloc::format!(
8331                    "expected ')' to close publication column list, got {:?}",
8332                    self.peek()
8333                )));
8334            }
8335            self.advance();
8336        }
8337        // Optional row filter — `WHERE (predicate)`.
8338        if matches!(self.peek(), Token::Where) {
8339            self.advance();
8340            if !matches!(self.peek(), Token::LParen) {
8341                return Err(self.err(alloc::format!(
8342                    "expected '(' after WHERE in publication row filter, got {:?}",
8343                    self.peek()
8344                )));
8345            }
8346            self.advance();
8347            let _ = self.parse_expr(0)?;
8348            if !matches!(self.peek(), Token::RParen) {
8349                return Err(self.err(alloc::format!(
8350                    "expected ')' to close publication WHERE filter, got {:?}",
8351                    self.peek()
8352                )));
8353            }
8354            self.advance();
8355        }
8356        Ok(name)
8357    }
8358
8359    /// v6.1.4 — `CREATE SUBSCRIPTION <name>
8360    ///                 CONNECTION '<conn>'
8361    ///                 PUBLICATION <pub> [, <pub> ...]`.
8362    ///
8363    /// The clause order is fixed (CONNECTION first, then
8364    /// PUBLICATION) to match PG. No WITH-options accepted in
8365    /// v6.1.4 — `enabled` defaults to true, no other knobs ship.
8366    fn parse_create_subscription_after_keyword(&mut self) -> Result<Statement, ParseError> {
8367        let name = self.expect_ident_or_string()?;
8368        if !matches!(self.peek(), Token::Connection) {
8369            return Err(self.err(format!(
8370                "expected CONNECTION after CREATE SUBSCRIPTION <name>, got {:?}",
8371                self.peek()
8372            )));
8373        }
8374        self.advance();
8375        let conn_str = self.expect_string_literal()?;
8376        if !matches!(self.peek(), Token::Publication) {
8377            return Err(self.err(format!(
8378                "expected PUBLICATION after CONNECTION '<conn>', got {:?}",
8379                self.peek()
8380            )));
8381        }
8382        self.advance();
8383        // Reuse the publication FOR-list parser shape: at least one
8384        // identifier, comma-separated.
8385        let first = self.expect_ident_like()?;
8386        let mut publications = alloc::vec![first];
8387        while matches!(self.peek(), Token::Comma) {
8388            self.advance();
8389            publications.push(self.expect_ident_like()?);
8390        }
8391        Ok(Statement::CreateSubscription(CreateSubscriptionStatement {
8392            name,
8393            conn_str,
8394            publications,
8395        }))
8396    }
8397
8398    /// v6.1.7 — `WAIT FOR WAL POSITION <pos> [WITH TIMEOUT <ms>]`.
8399    /// All keywords after `WAIT` are bare idents in v6.1.x; no
8400    /// lexer churn. Both `<pos>` and `<ms>` are positive integers
8401    /// that fit `u64`.
8402    /// Parameter name in `SET <name>`. A GUC name may be dotted, but the
8403    /// qualifier is a *namespace* the app owns (`app.user_id`,
8404    /// `myapp.tenant` — the request-context / RLS pattern), NOT a schema
8405    /// to discard. So parse the raw segments here instead of
8406    /// `expect_ident_like`, which strips a leading `schema.` qualifier
8407    /// and would collapse `SET app.foo` to just `foo`. Standard GUCs are
8408    /// a single segment and round-trip unchanged.
8409    fn parse_set_param_name(&mut self) -> Result<String, ParseError> {
8410        let mut parts: alloc::vec::Vec<String> = alloc::vec::Vec::new();
8411        loop {
8412            let seg = match self.advance() {
8413                Token::Ident(s) | Token::QuotedIdent(s) => s,
8414                other if unreserved_keyword_text(&other).is_some() => {
8415                    unreserved_keyword_text(&other).unwrap()
8416                }
8417                other => {
8418                    return Err(ParseError {
8419                        message: format!("expected parameter name, got {other:?}"),
8420                        token_pos: self.consumed_pos(),
8421                    });
8422                }
8423            };
8424            parts.push(seg);
8425            if matches!(self.peek(), Token::Dot) {
8426                self.advance();
8427                continue;
8428            }
8429            break;
8430        }
8431        Ok(parts.join(".").to_ascii_lowercase())
8432    }
8433
8434    fn parse_set_value(&mut self) -> Result<crate::ast::SetValue, ParseError> {
8435        Self::parse_set_value_inner(self)
8436    }
8437
8438    fn parse_set_value_inner(&mut self) -> Result<crate::ast::SetValue, ParseError> {
8439        match self.advance() {
8440            Token::String(s) => Ok(crate::ast::SetValue::String(s)),
8441            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("default") => {
8442                Ok(crate::ast::SetValue::Default)
8443            }
8444            Token::Ident(s) | Token::QuotedIdent(s) => {
8445                let mut accum = s;
8446                while matches!(self.peek(), Token::Dot) {
8447                    self.advance();
8448                    let next = self.expect_ident_like()?;
8449                    accum.push('.');
8450                    accum.push_str(&next);
8451                }
8452                Ok(crate::ast::SetValue::Ident(accum))
8453            }
8454            Token::Integer(n) => Ok(crate::ast::SetValue::Number(n.to_string())),
8455            Token::Float(f) => Ok(crate::ast::SetValue::Number(f.to_string())),
8456            // v7.22 (mailrs round-13 gap 2) — PG boolean parameter
8457            // spellings that lex as keyword tokens, not idents:
8458            // `SET standard_conforming_strings = on` is in every
8459            // pg_dump preamble (`off` already lexes as an ident).
8460            // v7.39 (round 769, F31 tranche 5 #150) — `SET x TO DEFAULT`:
8461            // DEFAULT lexes as its keyword token, so the ident arm above
8462            // never saw it and the everyday reset form was a syntax error.
8463            Token::Default => Ok(crate::ast::SetValue::Default),
8464            Token::On => Ok(crate::ast::SetValue::Ident("on".to_string())),
8465            Token::True => Ok(crate::ast::SetValue::Ident("true".to_string())),
8466            Token::False => Ok(crate::ast::SetValue::Ident("false".to_string())),
8467            // v7.14.0 — MySQL session/user variable RHS
8468            // (e.g. `SET OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS`).
8469            // Wrap as Ident so the SET handler can record it; the
8470            // engine treats `@VAR` / `@@VAR` values as opaque
8471            // strings.
8472            Token::SessionVar(s) => Ok(crate::ast::SetValue::Ident(s)),
8473            // v7.14.0 — `SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'`
8474            // is the common MySQL preamble shape. Allow a `+` or
8475            // `-` prefix on negative numerics for parity with PG
8476            // (some param defaults are negative).
8477            Token::Minus => match self.advance() {
8478                Token::Integer(n) => Ok(crate::ast::SetValue::Number(alloc::format!("-{n}"))),
8479                Token::Float(f) => Ok(crate::ast::SetValue::Number(alloc::format!("-{f}"))),
8480                other => Err(self.err(format!(
8481                    "expected numeric after `-` in SET value, got {other:?}"
8482                ))),
8483            },
8484            other => Err(self.err(format!(
8485                "expected literal, identifier, or DEFAULT after `=` in SET, got {other:?}"
8486            ))),
8487        }
8488    }
8489
8490    /// v7.38 轴 4 — `[ISOLATION LEVEL …] [READ ONLY|WRITE]
8491    /// [[NOT] DEFERRABLE]` modes after `SET TRANSACTION` or
8492    /// `START TRANSACTION` / `BEGIN`. Returns the isolation level
8493    /// (default `ReadCommitted` if no `ISOLATION LEVEL` clause was
8494    /// present). Modes are comma-separated per PG; SPG also
8495    /// accepts space-separated for tolerance. READ ONLY / WRITE
8496    /// / DEFERRABLE are parsed-and-ignored (recorded for future
8497    /// surface but not behaviorally honoured today).
8498    /// Parse the trailing `[ISOLATION LEVEL …] [READ ONLY|WRITE]
8499    /// [[NOT] DEFERRABLE]` modes of BEGIN / START TRANSACTION / SET
8500    /// TRANSACTION. Returns `Some(level)` only when an explicit `ISOLATION
8501    /// LEVEL` clause was given, so a bare `BEGIN` / `BEGIN READ ONLY` keeps the
8502    /// session default rather than forcing READ COMMITTED.
8503    fn parse_isolation_level_clauses(
8504        &mut self,
8505    ) -> Result<crate::ast::TransactionModes, ParseError> {
8506        let mut level = IsolationLevel::default();
8507        let mut have_level = false;
8508        // v7.39 — READ ONLY / READ WRITE used to be consumed and dropped,
8509        // so `BEGIN READ ONLY` opened an ordinary read-write transaction.
8510        let mut read_only: Option<bool> = None;
8511        loop {
8512            // ISOLATION LEVEL …
8513            let saw_isolation =
8514                matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("isolation"));
8515            if saw_isolation {
8516                self.advance(); // ISOLATION
8517                if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("level")) {
8518                    return Err(self.err(alloc::format!(
8519                        "expected LEVEL after ISOLATION, got {:?}",
8520                        self.peek()
8521                    )));
8522                }
8523                self.advance(); // LEVEL
8524                // SERIALIZABLE | REPEATABLE READ | READ COMMITTED | READ UNCOMMITTED
8525                let w1 = self
8526                    .expect_ident_like()
8527                    .map_err(|e| self.err(alloc::format!("isolation level: {e:?}")))?;
8528                let lc = w1.to_ascii_lowercase();
8529                level = match lc.as_str() {
8530                    "serializable" => IsolationLevel::Serializable,
8531                    "repeatable" => {
8532                        // Expect READ
8533                        let w2 = self
8534                            .expect_ident_like()
8535                            .map_err(|e| self.err(alloc::format!("REPEATABLE …: {e:?}")))?;
8536                        if !w2.eq_ignore_ascii_case("read") {
8537                            return Err(self.err(alloc::format!(
8538                                "expected READ after REPEATABLE, got {w2:?}"
8539                            )));
8540                        }
8541                        IsolationLevel::RepeatableRead
8542                    }
8543                    "read" => {
8544                        let w2 = self
8545                            .expect_ident_like()
8546                            .map_err(|e| self.err(alloc::format!("READ …: {e:?}")))?;
8547                        match w2.to_ascii_lowercase().as_str() {
8548                            "committed" => IsolationLevel::ReadCommitted,
8549                            "uncommitted" => IsolationLevel::ReadUncommitted,
8550                            other => {
8551                                return Err(self.err(alloc::format!(
8552                                    "expected COMMITTED or UNCOMMITTED after READ, got {other:?}"
8553                                )));
8554                            }
8555                        }
8556                    }
8557                    other => {
8558                        return Err(self.err(alloc::format!("unknown isolation level {other:?}")));
8559                    }
8560                };
8561                have_level = true;
8562            } else if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("read")) {
8563                // v7.39 — READ ONLY | READ WRITE. The comment here used to
8564                // read "parsed, not behaviorally honoured", and it was
8565                // accurate: the clause was thrown away, so `BEGIN READ ONLY`
8566                // opened an ordinary read-write transaction and accepted
8567                // every write in it.
8568                self.advance();
8569                match self.peek().clone() {
8570                    Token::Ident(s) if s.eq_ignore_ascii_case("only") => {
8571                        self.advance();
8572                        read_only = Some(true);
8573                    }
8574                    Token::Ident(s) if s.eq_ignore_ascii_case("write") => {
8575                        self.advance();
8576                        read_only = Some(false);
8577                    }
8578                    other => {
8579                        return Err(self.err(alloc::format!(
8580                            "expected ONLY or WRITE after READ, got {other:?}"
8581                        )));
8582                    }
8583                }
8584            } else if matches!(self.peek(), Token::Not) {
8585                // NOT DEFERRABLE — `NOT` lexes as a reserved keyword.
8586                self.advance();
8587                if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("deferrable")) {
8588                    return Err(self.err(alloc::format!(
8589                        "expected DEFERRABLE after NOT, got {:?}",
8590                        self.peek()
8591                    )));
8592                }
8593                self.advance();
8594            } else if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("deferrable"))
8595            {
8596                self.advance();
8597            } else {
8598                break;
8599            }
8600            // Optional comma between modes.
8601            if matches!(self.peek(), Token::Comma) {
8602                self.advance();
8603            }
8604        }
8605        Ok(crate::ast::TransactionModes {
8606            isolation: have_level.then_some(level),
8607            read_only,
8608        })
8609    }
8610
8611    fn parse_wait_after_keyword(&mut self) -> Result<Statement, ParseError> {
8612        // FOR is a v6.1.2-reserved keyword (Token::For). The
8613        // other two are bare idents — they've never needed lexer
8614        // support and we keep it that way.
8615        if !matches!(self.peek(), Token::For) {
8616            return Err(self.err(format!("expected FOR after WAIT, got {:?}", self.peek())));
8617        }
8618        self.advance();
8619        self.expect_keyword_ident("wal")?;
8620        self.expect_keyword_ident("position")?;
8621        let pos = self.expect_u64_literal()?;
8622        let timeout_ms = if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("with"))
8623        {
8624            self.advance();
8625            self.expect_keyword_ident("timeout")?;
8626            Some(self.expect_u64_literal()?)
8627        } else {
8628            None
8629        };
8630        Ok(Statement::WaitForWalPosition { pos, timeout_ms })
8631    }
8632
8633    /// v6.1.7 helper — consume a `Token::Integer` and check it
8634    /// fits `u64`. WAL positions and millisecond timeouts are
8635    /// non-negative.
8636    fn expect_u64_literal(&mut self) -> Result<u64, ParseError> {
8637        match self.advance() {
8638            Token::Integer(n) if n >= 0 => Ok(n as u64),
8639            Token::Integer(n) => Err(ParseError {
8640                message: format!("expected non-negative integer, got {n}"),
8641                token_pos: self.consumed_pos(),
8642            }),
8643            other => Err(ParseError {
8644                message: format!("expected integer literal, got {other:?}"),
8645                token_pos: self.consumed_pos(),
8646            }),
8647        }
8648    }
8649
8650    /// `CREATE USER` body — name + WITH PASSWORD '<pw>' + optional
8651    /// ROLE '<role>' (defaults to readonly). All string slots accept
8652    /// either a quoted ident or a quoted string literal.
8653    /// `CREATE {USER|ROLE} name [WITH] [PASSWORD 'x'] [LOGIN|NOLOGIN]
8654    /// [INHERIT|NOINHERIT] [SUPERUSER|NOSUPERUSER] [ROLE 'admin']`.
8655    ///
8656    /// `is_user` = the statement said USER, which in PG means LOGIN by default.
8657    /// The legacy SPG `ROLE 'readwrite'` clause (the coarse read/write/admin
8658    /// wire role) still parses — it is a different axis from the PG attributes.
8659    /// v7.39 (round 547) — is this ALTER ROLE / DATABASE one of the
8660    /// SET forms? Peeks past the name (and an `IN DATABASE d`) for SET
8661    /// or RESET, so the plain attribute forms keep their old path.
8662    fn peeks_db_role_setting(&self) -> bool {
8663        let mut i = self.pos + 1; // past the object's name
8664        let word = |p: usize| -> Option<String> {
8665            match self.tokens.get(p) {
8666                Some(Token::Ident(s) | Token::QuotedIdent(s)) => Some(s.to_ascii_lowercase()),
8667                Some(Token::In) => Some(String::from("in")),
8668                _ => None,
8669            }
8670        };
8671        if word(i).as_deref() == Some("in") && word(i + 1).as_deref() == Some("database") {
8672            i += 3; // IN DATABASE <name>
8673        }
8674        matches!(word(i).as_deref(), Some("set" | "reset"))
8675    }
8676
8677    fn parse_db_role_setting(&mut self, is_database: bool) -> Result<Statement, ParseError> {
8678        use crate::ast::SetDbRoleSettingStatement;
8679        // `ALTER ROLE ALL SET …` — ALL lexes as a KEYWORD, not an
8680        // identifier, so the ordinary name reader refuses it. Same trap
8681        // as TABLE / INDEX / FULL / DEFAULT before it.
8682        let name = if matches!(self.peek(), Token::All) {
8683            self.advance();
8684            String::from("all")
8685        } else {
8686            self.expect_ident_or_string()?
8687        };
8688        // `ALTER ROLE ALL SET …` is PG's every-role scope (oid 0).
8689        let all = name.eq_ignore_ascii_case("all");
8690        let (mut database, mut role) = if is_database {
8691            (Some(name), None)
8692        } else if all {
8693            (None, None)
8694        } else {
8695            (None, Some(name))
8696        };
8697        if matches!(self.peek(), Token::In) {
8698            self.advance();
8699            self.advance(); // DATABASE
8700            database = Some(self.expect_ident_or_string()?);
8701        }
8702        let resetting = matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("reset"));
8703        self.advance(); // SET | RESET
8704        if resetting && matches!(self.peek(), Token::All) {
8705            self.advance();
8706            self.consume_until_statement_boundary();
8707            return Ok(Statement::SetDbRoleSetting(Box::new(
8708                SetDbRoleSettingStatement {
8709                    database,
8710                    role,
8711                    param: None,
8712                    value: None,
8713                },
8714            )));
8715        }
8716        let param = self.expect_ident_like()?;
8717        let value = if resetting {
8718            None
8719        } else {
8720            // `SET p = v` and PG's `SET p TO v` both. TO lexes as a
8721            // KEYWORD, so the ident-only check missed it and consumed
8722            // the word itself as the value — the same trap as ALL, one
8723            // clause over.
8724            if matches!(self.peek(), Token::Eq | Token::To) || self.peek_keyword_ident("to") {
8725                self.advance();
8726            }
8727            Some(self.take_guc_value())
8728        };
8729        self.consume_until_statement_boundary();
8730        Ok(Statement::SetDbRoleSetting(Box::new(
8731            SetDbRoleSettingStatement {
8732                database,
8733                role,
8734                param: Some(param),
8735                value,
8736            },
8737        )))
8738    }
8739
8740    /// The remainder of a `SET <p> = …` clause as PG renders it back:
8741    /// a quoted literal loses its quotes, a bare word or number does not.
8742    fn take_guc_value(&mut self) -> String {
8743        match self.advance() {
8744            Token::String(s) => s,
8745            Token::Integer(n) => format!("{n}"),
8746            Token::Float(f) => format!("{f}"),
8747            Token::Ident(s) | Token::QuotedIdent(s) => s,
8748            other => format!("{other:?}"),
8749        }
8750    }
8751
8752    fn parse_create_user_after_keyword(&mut self, is_user: bool) -> Result<Statement, ParseError> {
8753        let name = self.expect_ident_or_string()?;
8754        if self.peek_keyword_ident("with") {
8755            self.advance();
8756        }
8757        let mut password = String::new();
8758        let mut role = String::new();
8759        let mut login: Option<bool> = None;
8760        let mut inherit: Option<bool> = None;
8761        let mut superuser: Option<bool> = None;
8762        // Not a `while let`: the pattern would borrow `self` across the
8763        // body, which calls `self.advance()` / `self.expect_*` (&mut).
8764        #[allow(clippy::while_let_loop)]
8765        loop {
8766            let (Token::Ident(w) | Token::QuotedIdent(w)) = self.peek() else {
8767                break;
8768            };
8769            match w.to_ascii_lowercase().as_str() {
8770                "password" => {
8771                    self.advance();
8772                    password = self.expect_string_literal()?;
8773                }
8774                // PG accepts (and pg_dump emits) ENCRYPTED PASSWORD; the value
8775                // is the same slot.
8776                "encrypted" => {
8777                    self.advance();
8778                    self.expect_keyword_ident("password")?;
8779                    password = self.expect_string_literal()?;
8780                }
8781                "login" => {
8782                    self.advance();
8783                    login = Some(true);
8784                }
8785                "nologin" => {
8786                    self.advance();
8787                    login = Some(false);
8788                }
8789                "inherit" => {
8790                    self.advance();
8791                    inherit = Some(true);
8792                }
8793                "noinherit" => {
8794                    self.advance();
8795                    inherit = Some(false);
8796                }
8797                "superuser" => {
8798                    self.advance();
8799                    superuser = Some(true);
8800                }
8801                "nosuperuser" => {
8802                    self.advance();
8803                    superuser = Some(false);
8804                }
8805                // SPG's own coarse wire role: `ROLE 'readwrite'`.
8806                "role" => {
8807                    self.advance();
8808                    role = self.expect_string_literal()?;
8809                }
8810                // Every other PG role option (CREATEDB, CONNECTION LIMIT n,
8811                // VALID UNTIL '…', CREATEROLE, REPLICATION, BYPASSRLS …) is
8812                // accepted and ignored so a pg_dump role block restores. They
8813                // gate capabilities SPG does not have.
8814                "createdb" | "nocreatedb" | "createrole" | "nocreaterole" | "replication"
8815                | "noreplication" | "bypassrls" | "nobypassrls" => {
8816                    self.advance();
8817                }
8818                "connection" => {
8819                    self.advance();
8820                    self.expect_keyword_ident("limit")?;
8821                    self.advance(); // the number
8822                }
8823                "valid" => {
8824                    self.advance();
8825                    self.expect_keyword_ident("until")?;
8826                    self.expect_string_literal()?;
8827                }
8828                _ => break,
8829            }
8830        }
8831        if role.is_empty() {
8832            role = "readonly".to_string();
8833        }
8834        Ok(Statement::CreateUser(crate::ast::CreateUserStatement {
8835            name,
8836            password,
8837            role,
8838            login,
8839            inherit,
8840            superuser,
8841            is_user,
8842        }))
8843    }
8844
8845    /// v7.39 (RLS) — parenthesised policy qualifier `( <expr> )`; caller has
8846    /// consumed the USING / WITH CHECK keyword.
8847    fn parse_paren_expr(&mut self, clause: &str) -> Result<Expr, ParseError> {
8848        if !matches!(self.peek(), Token::LParen) {
8849            return Err(self.err(alloc::format!(
8850                "expected '(' after {clause}, got {:?}",
8851                self.peek()
8852            )));
8853        }
8854        self.advance();
8855        let e = self.parse_expr(0)?;
8856        if !matches!(self.peek(), Token::RParen) {
8857            return Err(self.err(alloc::format!(
8858                "expected ')' to close {clause}, got {:?}",
8859                self.peek()
8860            )));
8861        }
8862        self.advance();
8863        Ok(e)
8864    }
8865
8866    /// v7.39 (RLS) — `TO role [, role]*`; caller has consumed `TO`.
8867    fn parse_policy_roles(&mut self) -> Result<Vec<String>, ParseError> {
8868        let mut roles = Vec::new();
8869        loop {
8870            roles.push(self.expect_ident_like()?);
8871            if matches!(self.peek(), Token::Comma) {
8872                self.advance();
8873            } else {
8874                break;
8875            }
8876        }
8877        Ok(roles)
8878    }
8879
8880    /// v7.39 (RLS) — `CREATE POLICY name ON table [AS {PERMISSIVE|RESTRICTIVE}]
8881    /// [FOR cmd] [TO roles] [USING (expr)] [WITH CHECK (expr)]`. Caller consumed
8882    /// `CREATE POLICY`.
8883    fn parse_create_policy_after_keyword(&mut self) -> Result<Statement, ParseError> {
8884        use crate::ast::PolicyCmd;
8885        let name = self.expect_ident_like()?;
8886        if !matches!(self.peek(), Token::On) {
8887            return Err(self.err(alloc::format!(
8888                "expected ON after CREATE POLICY name, got {:?}",
8889                self.peek()
8890            )));
8891        }
8892        self.advance();
8893        let table = self.expect_ident_like()?;
8894
8895        let mut permissive = true;
8896        if matches!(self.peek(), Token::As) {
8897            self.advance();
8898            let w = self.expect_ident_like()?;
8899            permissive = if w.eq_ignore_ascii_case("permissive") {
8900                true
8901            } else if w.eq_ignore_ascii_case("restrictive") {
8902                false
8903            } else {
8904                return Err(self.err(alloc::format!(
8905                    "expected PERMISSIVE or RESTRICTIVE after AS, got {w:?}"
8906                )));
8907            };
8908        }
8909
8910        let mut cmd = PolicyCmd::All;
8911        if matches!(self.peek(), Token::For) {
8912            self.advance();
8913            cmd = self.parse_policy_cmd()?;
8914        }
8915
8916        let mut roles = Vec::new();
8917        if matches!(self.peek(), Token::To) {
8918            self.advance();
8919            roles = self.parse_policy_roles()?;
8920        }
8921
8922        let mut using = None;
8923        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("using"))
8924        {
8925            self.advance();
8926            using = Some(self.parse_paren_expr("USING")?);
8927        }
8928
8929        let mut with_check = None;
8930        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("with"))
8931        {
8932            self.advance();
8933            if !matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("check"))
8934            {
8935                return Err(self.err(alloc::format!(
8936                    "expected CHECK after WITH, got {:?}",
8937                    self.peek()
8938                )));
8939            }
8940            self.advance();
8941            with_check = Some(self.parse_paren_expr("WITH CHECK")?);
8942        }
8943
8944        // Clause-per-command matrix (PG wording).
8945        match cmd {
8946            PolicyCmd::Insert => {
8947                if using.is_some() {
8948                    return Err(self.err("only WITH CHECK expression allowed for INSERT".into()));
8949                }
8950            }
8951            PolicyCmd::Select | PolicyCmd::Delete => {
8952                if with_check.is_some() {
8953                    return Err(self.err("WITH CHECK cannot be applied to SELECT or DELETE".into()));
8954                }
8955            }
8956            PolicyCmd::Update | PolicyCmd::All => {}
8957        }
8958
8959        Ok(Statement::CreatePolicy(crate::ast::CreatePolicyStatement {
8960            name,
8961            table,
8962            permissive,
8963            cmd,
8964            roles,
8965            using,
8966            with_check,
8967        }))
8968    }
8969
8970    /// v7.39 (RLS) — the command word after `FOR`.
8971    fn parse_policy_cmd(&mut self) -> Result<crate::ast::PolicyCmd, ParseError> {
8972        use crate::ast::PolicyCmd;
8973        match self.peek().clone() {
8974            Token::All => {
8975                self.advance();
8976                Ok(PolicyCmd::All)
8977            }
8978            Token::Select => {
8979                self.advance();
8980                Ok(PolicyCmd::Select)
8981            }
8982            Token::Insert => {
8983                self.advance();
8984                Ok(PolicyCmd::Insert)
8985            }
8986            Token::Ident(s) if s.eq_ignore_ascii_case("update") => {
8987                self.advance();
8988                Ok(PolicyCmd::Update)
8989            }
8990            Token::Ident(s) if s.eq_ignore_ascii_case("delete") => {
8991                self.advance();
8992                Ok(PolicyCmd::Delete)
8993            }
8994            other => Err(self.err(alloc::format!(
8995                "expected ALL/SELECT/INSERT/UPDATE/DELETE after FOR, got {other:?}"
8996            ))),
8997        }
8998    }
8999
9000    /// v7.39 (RLS) — `ALTER POLICY name ON table { RENAME TO new | [TO roles]
9001    /// [USING (expr)] [WITH CHECK (expr)] }`. Caller consumed `ALTER POLICY`.
9002    fn parse_alter_policy_after_keyword(&mut self) -> Result<Statement, ParseError> {
9003        let name = self.expect_ident_like()?;
9004        if !matches!(self.peek(), Token::On) {
9005            return Err(self.err(alloc::format!(
9006                "expected ON after ALTER POLICY name, got {:?}",
9007                self.peek()
9008            )));
9009        }
9010        self.advance();
9011        let table = self.expect_ident_like()?;
9012
9013        // RENAME TO new
9014        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("rename"))
9015        {
9016            self.advance();
9017            if !matches!(self.peek(), Token::To) {
9018                return Err(self.err(alloc::format!(
9019                    "expected TO after RENAME, got {:?}",
9020                    self.peek()
9021                )));
9022            }
9023            self.advance();
9024            let new = self.expect_ident_like()?;
9025            return Ok(Statement::AlterPolicy(crate::ast::AlterPolicyStatement {
9026                name,
9027                table,
9028                rename_to: Some(new),
9029                roles: None,
9030                using: None,
9031                with_check: None,
9032            }));
9033        }
9034
9035        let mut roles = None;
9036        if matches!(self.peek(), Token::To) {
9037            self.advance();
9038            roles = Some(self.parse_policy_roles()?);
9039        }
9040        let mut using = None;
9041        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("using"))
9042        {
9043            self.advance();
9044            using = Some(self.parse_paren_expr("USING")?);
9045        }
9046        let mut with_check = None;
9047        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("with"))
9048        {
9049            self.advance();
9050            if !matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("check"))
9051            {
9052                return Err(self.err(alloc::format!(
9053                    "expected CHECK after WITH, got {:?}",
9054                    self.peek()
9055                )));
9056            }
9057            self.advance();
9058            with_check = Some(self.parse_paren_expr("WITH CHECK")?);
9059        }
9060        Ok(Statement::AlterPolicy(crate::ast::AlterPolicyStatement {
9061            name,
9062            table,
9063            rename_to: None,
9064            roles,
9065            using,
9066            with_check,
9067        }))
9068    }
9069
9070    /// v7.39 (RLS) — `DROP POLICY [IF EXISTS] name ON table`. Caller consumed
9071    /// `DROP POLICY`.
9072    fn parse_drop_policy_after_keyword(&mut self) -> Result<Statement, ParseError> {
9073        let if_exists = self.consume_if_exists();
9074        let name = self.expect_ident_like()?;
9075        if !matches!(self.peek(), Token::On) {
9076            return Err(self.err(alloc::format!(
9077                "expected ON after DROP POLICY name, got {:?}",
9078                self.peek()
9079            )));
9080        }
9081        self.advance();
9082        let table = self.expect_ident_like()?;
9083        Ok(Statement::DropPolicy(crate::ast::DropPolicyStatement {
9084            name,
9085            table,
9086            if_exists,
9087        }))
9088    }
9089}
9090fn wrap_from_leaves(
9091    e: &mut Expr,
9092    names: &[String],
9093    make: &dyn Fn(Expr) -> Expr,
9094    refs: &dyn Fn(&Expr) -> bool,
9095) {
9096    if let Expr::Column(c) = e {
9097        if c.qualifier
9098            .as_deref()
9099            .is_some_and(|q| names.iter().any(|n| n.eq_ignore_ascii_case(q)))
9100        {
9101            let taken = core::mem::replace(e, Expr::Literal(Literal::Null));
9102            *e = make(taken);
9103        }
9104        return;
9105    }
9106    match e {
9107        Expr::Binary { lhs, rhs, .. } => {
9108            wrap_from_leaves(lhs, names, make, refs);
9109            wrap_from_leaves(rhs, names, make, refs);
9110        }
9111        Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
9112            wrap_from_leaves(expr, names, make, refs)
9113        }
9114        Expr::FunctionCall { args, .. } => {
9115            for a in args.iter_mut() {
9116                wrap_from_leaves(a, names, make, refs);
9117            }
9118        }
9119        Expr::Case {
9120            operand,
9121            branches,
9122            else_branch,
9123        } => {
9124            if let Some(o) = operand.as_deref_mut() {
9125                wrap_from_leaves(o, names, make, refs);
9126            }
9127            for (w, t) in branches.iter_mut() {
9128                wrap_from_leaves(w, names, make, refs);
9129                wrap_from_leaves(t, names, make, refs);
9130            }
9131            if let Some(el) = else_branch.as_deref_mut() {
9132                wrap_from_leaves(el, names, make, refs);
9133            }
9134        }
9135        // Compound variants the walk doesn't decompose: keep the
9136        // pre-D.30 behavior — wrap the whole sub-expr if it touches
9137        // a source table, so nothing regresses.
9138        other => {
9139            if refs(other) {
9140                let taken = core::mem::replace(other, Expr::Literal(Literal::Null));
9141                *other = make(taken);
9142            }
9143        }
9144    }
9145}
9146
9147/// v7.39 (round 241) — does this expression reference any of the FROM /
9148/// USING table names (shared by the UPDATE…FROM and DELETE…USING
9149/// lowerings)?
9150fn expr_refs_tables(e: &Expr, names: &[String]) -> bool {
9151    match e {
9152        Expr::Column(c) => c
9153            .qualifier
9154            .as_deref()
9155            .is_some_and(|q| names.iter().any(|n| n.eq_ignore_ascii_case(q))),
9156        Expr::Binary { lhs, rhs, .. } => {
9157            expr_refs_tables(lhs, names) || expr_refs_tables(rhs, names)
9158        }
9159        Expr::Unary { expr, .. } | Expr::Cast { expr, .. } => expr_refs_tables(expr, names),
9160        Expr::FunctionCall { args, .. } => args.iter().any(|a| expr_refs_tables(a, names)),
9161        Expr::Case {
9162            operand,
9163            branches,
9164            else_branch,
9165        } => {
9166            operand
9167                .as_deref()
9168                .is_some_and(|o| expr_refs_tables(o, names))
9169                || branches
9170                    .iter()
9171                    .any(|(w, t)| expr_refs_tables(w, names) || expr_refs_tables(t, names))
9172                || else_branch
9173                    .as_deref()
9174                    .is_some_and(|el| expr_refs_tables(el, names))
9175        }
9176        _ => false,
9177    }
9178}
9179
9180impl Parser {
9181    /// v4.4 `UPDATE <table> SET col = expr [, col = expr]* [WHERE cond]`.
9182    /// Caller already consumed the leading `UPDATE` ident.
9183    /// v7.39 (round 420) — does a JOIN clause start here? Used to spot
9184    /// MySQL's multi-table `UPDATE a JOIN b ON …` / `UPDATE a LEFT JOIN b …`
9185    /// after the target name has been read. `JOIN` is a reserved token;
9186    /// the qualifiers are bare idents.
9187    fn peek_is_update_join_start(&self) -> bool {
9188        match self.peek() {
9189            // JOIN and its qualifiers are reserved lexer tokens (the grammar
9190            // dedicates arms to `LEFT [OUTER] JOIN` and friends).
9191            Token::Join
9192            | Token::Inner
9193            | Token::Left
9194            | Token::Right
9195            | Token::Cross
9196            | Token::Full => true,
9197            // NATURAL / STRAIGHT_JOIN arrive as bare idents.
9198            Token::Ident(s) | Token::QuotedIdent(s) => {
9199                matches!(s.to_ascii_lowercase().as_str(), "natural" | "straight_join")
9200            }
9201            _ => false,
9202        }
9203    }
9204
9205    /// v7.39 (round 430) — `SET @x = <expr> [, @y := <expr>]`, MySQL's
9206    /// USER-variable assignment. Its own per-session namespace, an arbitrary
9207    /// expression on the right, and `:=` as a second spelling of `=`.
9208    ///
9209    /// Out-of-line (`inline(never)`): the statement-parse frame it is called
9210    /// from sits on the nesting recursion chain (a CTE body, a subquery),
9211    /// and holding this loop's `Vec` + `String` locals there overflowed the
9212    /// 512 KiB guard (`e2e_in_list_depth::round25_union_cte_search_shape`).
9213    #[inline(never)]
9214    fn parse_set_user_vars(&mut self) -> Result<Statement, ParseError> {
9215        let mut assigns: Vec<(String, Expr)> = Vec::new();
9216        let mut settings: Vec<(String, Expr)> = Vec::new();
9217        loop {
9218            // v7.39 (round 554) — a plain NAME here is a session
9219            // setting, not a user variable. mysqldump writes the two in
9220            // one statement — `SET @OLD_SQL_MODE=@@SQL_MODE,
9221            // SQL_MODE='NO_AUTO_VALUE_ON_ZERO'` saves a value and
9222            // changes it — and this refused the mixture outright, so no
9223            // dump could be restored past its preamble.
9224            if let Token::Ident(name) | Token::QuotedIdent(name) = self.peek().clone() {
9225                self.advance();
9226                if !matches!(self.peek(), Token::Eq | Token::ColonEq) {
9227                    return Err(self.err(alloc::format!(
9228                        "expected `=` after {name}, got {:?}",
9229                        self.peek()
9230                    )));
9231                }
9232                self.advance();
9233                let value = self.parse_expr(0)?;
9234                settings.push((name.to_ascii_lowercase(), value));
9235                if matches!(self.peek(), Token::Comma) {
9236                    self.advance();
9237                    continue;
9238                }
9239                break;
9240            }
9241            let Token::SessionVar(raw) = self.peek().clone() else {
9242                return Err(self.err(alloc::format!(
9243                    "expected a user variable after SET, got {:?}",
9244                    self.peek()
9245                )));
9246            };
9247            if raw.starts_with("@@") {
9248                return Err(self.err(alloc::string::String::from(
9249                    "cannot mix `@@` settings with `@` user variables in one SET",
9250                )));
9251            }
9252            self.advance();
9253            if !matches!(self.peek(), Token::Eq | Token::ColonEq) {
9254                return Err(self.err(alloc::format!(
9255                    "expected `=` or `:=` after {raw}, got {:?}",
9256                    self.peek()
9257                )));
9258            }
9259            self.advance();
9260            let value = self.parse_expr(0)?;
9261            assigns.push((raw.trim_start_matches('@').to_ascii_lowercase(), value));
9262            if matches!(self.peek(), Token::Comma) {
9263                self.advance();
9264                continue;
9265            }
9266            break;
9267        }
9268        Ok(Statement::SetUserVars(assigns, settings))
9269    }
9270
9271    fn parse_update_after_keyword(&mut self) -> Result<Statement, ParseError> {
9272        // v7.39 (round 646) — `UPDATE ONLY t SET …`. Read as a table
9273        // NAMED `only` until now, which failed on `relation "only" does
9274        // not exist`. The lookahead is what keeps a table actually
9275        // called `only` working: the keyword is only a keyword when a
9276        // TABLE NAME follows it — and `SET` arrives as an identifier
9277        // here, so `UPDATE only SET a = 2` would otherwise take `SET`
9278        // for the table and die on the `=`. Measured by the pin.
9279        let only = matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
9280            if s.eq_ignore_ascii_case("only"))
9281            && matches!(
9282                self.tokens.get(self.pos + 1),
9283                Some(Token::Ident(n) | Token::QuotedIdent(n)) if !n.eq_ignore_ascii_case("set")
9284            );
9285        if only {
9286            self.advance();
9287        }
9288        let table = self.expect_ident_like()?;
9289        // v7.39 (round 241) — `UPDATE t [AS] alias SET …`. PG allows the
9290        // bare spelling; a bare identifier that is the SET keyword itself
9291        // is the clause, not an alias.
9292        // v7.39 (round 420) — nor is a bare join qualifier (`LEFT` / `INNER`
9293        // / …) an alias: `UPDATE a LEFT JOIN b …` starts the MySQL
9294        // multi-table form, and swallowing `LEFT` as `a`'s alias made the
9295        // following JOIN a syntax error.
9296        let starts_join = self.mysql_dialect && self.peek_is_update_join_start();
9297        let alias = if matches!(self.peek(), Token::As) {
9298            self.advance();
9299            Some(self.expect_ident_like()?)
9300        } else {
9301            match self.peek() {
9302                Token::Ident(s) | Token::QuotedIdent(s)
9303                    if !s.eq_ignore_ascii_case("set") && !starts_join =>
9304                {
9305                    let a = s.clone();
9306                    self.advance();
9307                    Some(a)
9308                }
9309                _ => None,
9310            }
9311        };
9312        // v7.39 (round 420) — MySQL's multi-table UPDATE:
9313        //     UPDATE a, b        SET a.v = b.v WHERE a.id = b.id
9314        //     UPDATE a JOIN b ON a.id = b.id      SET a.v = b.v + 1
9315        //     UPDATE a LEFT JOIN b ON a.id = b.id SET a.v = COALESCE(b.v, -1)
9316        // The FIRST table is the mutation target and the rest are sources —
9317        // exactly the shape PG spells `UPDATE a SET … FROM b WHERE …`, which
9318        // SPG already lowers onto correlated subqueries. So rewind, let
9319        // `parse_from_clause` read the whole list (it handles aliases, comma
9320        // lists, and every JOIN form), then peel the target off the front.
9321        let (mysql_from, mysql_on, mysql_outer) = if self.mysql_dialect
9322            && (matches!(self.peek(), Token::Comma) || self.peek_is_update_join_start())
9323        {
9324            // NOTE: `advance()` destroys the tokens it returns
9325            // (`mem::replace(.., Eof)`), so re-parsing by rewinding `self.pos`
9326            // is NOT possible — the tail is read forward, once, through the
9327            // same grammar `parse_from_clause` uses after its primary.
9328            let target_qual = alias.clone().unwrap_or_else(|| table.clone());
9329            let mut joins = self.parse_from_joins(&target_qual)?;
9330            if joins.is_empty() {
9331                return Err(self.err(alloc::string::String::from(
9332                    "multi-table UPDATE needs at least one source table",
9333                )));
9334            }
9335            let head = joins.remove(0);
9336            // A LEFT join keeps every target row (the unmatched ones see NULL
9337            // on the source side), so it must NOT get the EXISTS row filter
9338            // the inner / comma forms use.
9339            let outer = matches!(head.kind, crate::ast::JoinKind::Left);
9340            let src = FromClause {
9341                primary: head.table,
9342                joins,
9343            };
9344            (Some(src), head.on, outer)
9345        } else {
9346            (None, None, false)
9347        };
9348        self.expect_keyword_ident("set")?;
9349        let mut assignments = Vec::new();
9350        loop {
9351            // `SET (a, b) = (e1, e2)` / `SET (a, b) = (SELECT x, y
9352            // …)` — the parenthesized multi-assignment. Expressions
9353            // assign positionally; a subquery RHS clones per column
9354            // keeping only the Nth projection item.
9355            if matches!(self.peek(), Token::LParen) {
9356                self.advance();
9357                let mut cols = alloc::vec![self.expect_ident_like()?];
9358                while matches!(self.peek(), Token::Comma) {
9359                    self.advance();
9360                    cols.push(self.expect_ident_like()?);
9361                }
9362                if !matches!(self.peek(), Token::RParen) {
9363                    return Err(self.err(format!(
9364                        "expected ')' after SET column list, got {:?}",
9365                        self.peek()
9366                    )));
9367                }
9368                self.advance();
9369                if !matches!(self.peek(), Token::Eq) {
9370                    return Err(self.err(format!(
9371                        "expected `=` after SET column list, got {:?}",
9372                        self.peek()
9373                    )));
9374                }
9375                self.advance();
9376                if !matches!(self.peek(), Token::LParen) {
9377                    return Err(self.err(format!(
9378                        "expected '(' after SET (…) =, got {:?}",
9379                        self.peek()
9380                    )));
9381                }
9382                self.advance();
9383                if matches!(self.peek(), Token::Select) {
9384                    let inner = match self.parse_select_stmt()? {
9385                        Statement::Select(s) => s,
9386                        other => {
9387                            return Err(self.err(alloc::format!(
9388                                "expected SELECT in SET (…) = (SELECT …), got {other:?}"
9389                            )));
9390                        }
9391                    };
9392                    if !matches!(self.peek(), Token::RParen) {
9393                        return Err(self.err(format!(
9394                            "expected ')' after SET subquery, got {:?}",
9395                            self.peek()
9396                        )));
9397                    }
9398                    self.advance();
9399                    if inner.items.len() != cols.len() {
9400                        return Err(self.err(alloc::format!(
9401                            "SET (…) = (SELECT …) arity mismatch: {} columns, {} items",
9402                            cols.len(),
9403                            inner.items.len()
9404                        )));
9405                    }
9406                    for (i, col) in cols.into_iter().enumerate() {
9407                        let mut sub = inner.clone();
9408                        sub.items = alloc::vec![sub.items[i].clone()];
9409                        assignments.push((col, Expr::ScalarSubquery(Box::new(sub))));
9410                    }
9411                } else {
9412                    let mut exprs = alloc::vec![self.parse_expr(0)?];
9413                    while matches!(self.peek(), Token::Comma) {
9414                        self.advance();
9415                        exprs.push(self.parse_expr(0)?);
9416                    }
9417                    if !matches!(self.peek(), Token::RParen) {
9418                        return Err(self.err(format!(
9419                            "expected ')' after SET row values, got {:?}",
9420                            self.peek()
9421                        )));
9422                    }
9423                    self.advance();
9424                    if exprs.len() != cols.len() {
9425                        return Err(self.err(alloc::format!(
9426                            "SET (…) = (…) arity mismatch: {} columns, {} values",
9427                            cols.len(),
9428                            exprs.len()
9429                        )));
9430                    }
9431                    for (col, e) in cols.into_iter().zip(exprs) {
9432                        assignments.push((col, e));
9433                    }
9434                }
9435                if matches!(self.peek(), Token::Comma) {
9436                    self.advance();
9437                    continue;
9438                }
9439                break;
9440            }
9441            // v7.39 (round 420) — MySQL's multi-table UPDATE qualifies its
9442            // assignment targets (`SET a.v = b.v`). `expect_ident_like`
9443            // SILENTLY strips a `<qual>.` prefix (it exists for PG's
9444            // `public.` dump qualifiers), so the qualifier has to be read off
9445            // the token stream first — otherwise `SET b.v = 888` would write
9446            // to the TARGET table's `v` while naming a source table, a
9447            // silent-wrong. A qualifier naming a SOURCE table means a
9448            // multi-TARGET update — mutating two tables in one statement —
9449            // which SPG does not model, so it is refused loudly.
9450            let set_qual: Option<String> = if mysql_from.is_some()
9451                && matches!(self.tokens.get(self.pos + 1), Some(Token::Dot))
9452            {
9453                match self.peek() {
9454                    Token::Ident(s) | Token::QuotedIdent(s) => Some(s.clone()),
9455                    _ => None,
9456                }
9457            } else {
9458                None
9459            };
9460            let col = self.expect_ident_like()?;
9461            if let Some(q) = set_qual {
9462                let names_target = q.eq_ignore_ascii_case(&table)
9463                    || alias.as_deref().is_some_and(|a| a.eq_ignore_ascii_case(&q));
9464                if !names_target {
9465                    return Err(self.err(alloc::format!(
9466                        "multi-table UPDATE can only assign to its first table \
9467                         ({table}); `{q}.{col}` targets another table"
9468                    )));
9469                }
9470            }
9471            // v7.37 D.53 — array element assignment target `SET arr[i] = v`,
9472            // desugared to `arr = __array_assign(arr, i, v)` (mirrors the
9473            // `__column_default` marker lowering just below). PG assigns to the
9474            // i-th (1-based) element, NULL-padding when i exceeds the length.
9475            if matches!(self.peek(), Token::LBracket) {
9476                self.advance();
9477                let index = self.parse_expr(0)?;
9478                // v7.39 (round 257) — the SLICE target `SET arr[lo:hi] = src`
9479                // (and the open `arr[lo:]`), lowered to
9480                // `__array_assign_slice`. Only the single-subscript form
9481                // parsed before, so a slice assignment was a syntax error.
9482                let mut slice_hi: Option<Option<Expr>> = None;
9483                if matches!(self.peek(), Token::Colon) {
9484                    self.advance();
9485                    slice_hi = Some(if matches!(self.peek(), Token::RBracket) {
9486                        None
9487                    } else {
9488                        Some(self.parse_expr(0)?)
9489                    });
9490                }
9491                if !matches!(self.peek(), Token::RBracket) {
9492                    return Err(self.err(format!(
9493                        "expected `]` after array subscript in UPDATE SET, got {:?}",
9494                        self.peek()
9495                    )));
9496                }
9497                self.advance();
9498                if !matches!(self.peek(), Token::Eq) {
9499                    return Err(self.err(format!(
9500                        "expected `=` after array subscript in UPDATE SET, got {:?}",
9501                        self.peek()
9502                    )));
9503                }
9504                self.advance();
9505                let value = self.parse_expr(0)?;
9506                // PG merges several subscript writes to the same column into one
9507                // array (`SET arr[1]=x, arr[3]=y`), so chain onto any prior
9508                // assignment to `col` rather than each overwriting the original.
9509                let existing = assignments.iter().position(|(c, _)| c == &col);
9510                let base = match existing {
9511                    Some(i) => assignments[i].1.clone(),
9512                    None => Expr::Column(ColumnName {
9513                        qualifier: None,
9514                        name: col.clone(),
9515                    }),
9516                };
9517                let assigned = match slice_hi {
9518                    None => Expr::FunctionCall {
9519                        name: "__array_assign".to_string(),
9520                        args: alloc::vec![base, index, value],
9521                    },
9522                    Some(hi) => Expr::FunctionCall {
9523                        name: "__array_assign_slice".to_string(),
9524                        args: alloc::vec![
9525                            base,
9526                            index,
9527                            hi.unwrap_or(Expr::Literal(crate::ast::Literal::Null)),
9528                            value,
9529                        ],
9530                    },
9531                };
9532                match existing {
9533                    Some(i) => assignments[i].1 = assigned,
9534                    None => assignments.push((col, assigned)),
9535                }
9536                if matches!(self.peek(), Token::Comma) {
9537                    self.advance();
9538                    continue;
9539                }
9540                break;
9541            }
9542            if !matches!(self.peek(), Token::Eq) {
9543                return Err(self.err(format!(
9544                    "expected `=` after column name in UPDATE SET, got {:?}",
9545                    self.peek()
9546                )));
9547            }
9548            self.advance();
9549            // `SET col = DEFAULT` — the column's declared default;
9550            // rides out as a marker call the update executor
9551            // resolves against the schema.
9552            let value = if matches!(self.peek(), Token::Default) {
9553                self.advance();
9554                Expr::FunctionCall {
9555                    name: "__column_default".to_string(),
9556                    args: Vec::new(),
9557                }
9558            } else {
9559                self.parse_expr(0)?
9560            };
9561            assignments.push((col, value));
9562            if matches!(self.peek(), Token::Comma) {
9563                self.advance();
9564                continue;
9565            }
9566            break;
9567        }
9568        // `UPDATE t SET … FROM src [, …] WHERE cond` — PG's joined
9569        // update. Lowers onto the correlated-subquery machinery:
9570        // the WHERE becomes EXISTS(SELECT 1 FROM src WHERE cond)
9571        // and each assignment that references a FROM-list table
9572        // wraps into a correlated scalar subquery
9573        // (SELECT expr FROM src WHERE cond). Equivalent for the
9574        // unique-join shape (the overwhelmingly common one); a
9575        // multi-match, which PG resolves by arbitrary pick,
9576        // surfaces as a scalar-subquery cardinality error instead
9577        // of a silent arbitrary result.
9578        // v7.39 (round 420) — the MySQL multi-table form supplies the source
9579        // list up front (`UPDATE a, b SET …`) instead of via FROM, so it feeds
9580        // the SAME lowering below. Both spellings together is not legal in
9581        // either dialect.
9582        let from_clause = if let Some(fc) = mysql_from {
9583            if matches!(self.peek(), Token::From) {
9584                return Err(self.err(alloc::string::String::from(
9585                    "multi-table UPDATE already names its sources; drop the FROM clause",
9586                )));
9587            }
9588            Some(fc)
9589        } else if matches!(self.peek(), Token::From) {
9590            self.advance();
9591            Some(self.parse_from_clause()?)
9592        } else {
9593            None
9594        };
9595        let where_ = if matches!(self.peek(), Token::Where) {
9596            self.advance();
9597            Some(self.parse_expr(0)?)
9598        } else {
9599            None
9600        };
9601        // v7.39 (round 421, fixing round 420) — the SOURCE subquery's filter
9602        // and the TARGET-row filter are NOT the same predicate once a LEFT
9603        // join is involved:
9604        //   * inner / comma / PG's `FROM`: the ON predicate and the WHERE are
9605        //     one conjunction, and the whole thing filters target rows via
9606        //     EXISTS.
9607        //   * LEFT join: only the ON predicate belongs inside the source
9608        //     subquery. The WHERE still filters TARGET rows (with source
9609        //     columns read through the correlated subquery, which yields NULL
9610        //     for an unmatched row — exactly LEFT-join semantics).
9611        // Round 420 folded ON into WHERE unconditionally and then dropped the
9612        // outer filter for the LEFT case, so `UPDATE a LEFT JOIN b ON … SET …
9613        // WHERE a.id > 1` updated EVERY row.
9614        let sub_where = match (mysql_on.clone(), where_.clone()) {
9615            _ if mysql_outer => mysql_on.clone(),
9616            (Some(on), Some(w)) => Some(Expr::Binary {
9617                lhs: Box::new(on),
9618                op: crate::ast::BinOp::And,
9619                rhs: Box::new(w),
9620            }),
9621            (Some(on), None) => Some(on),
9622            (None, w) => w,
9623        };
9624        // v7.39 (round 413) — MySQL `UPDATE … [ORDER BY …] [LIMIT n]`. PG
9625        // has no such clause on UPDATE, so this is accepted only under the
9626        // MySQL dialect; a PG session's `UPDATE … ORDER BY …` still errors.
9627        let update_order_limit = self.parse_mysql_dml_order_limit("UPDATE")?;
9628        let mut returning = self.parse_optional_returning()?;
9629        // v7.39 (round 533) — kept for the engine, which can resolve the
9630        // UNQUALIFIED leaves this lowering has to leave alone.
9631        let from_sources = from_clause.as_ref().map(|fc| {
9632            alloc::boxed::Box::new(crate::ast::UpdateFromSources {
9633                from: fc.clone(),
9634                sub_where: sub_where.clone(),
9635            })
9636        });
9637        let (assignments, where_) = if let Some(fc) = from_clause {
9638            let names: Vec<String> = core::iter::once(&fc.primary)
9639                .chain(fc.joins.iter().map(|j| &j.table))
9640                .flat_map(|t| {
9641                    t.alias
9642                        .clone()
9643                        .into_iter()
9644                        .chain(core::iter::once(t.name.clone()))
9645                })
9646                .collect();
9647            let refs_list = |e: &Expr| -> bool {
9648                fn walk(e: &Expr, names: &[String]) -> bool {
9649                    match e {
9650                        Expr::Column(c) => c
9651                            .qualifier
9652                            .as_deref()
9653                            .is_some_and(|q| names.iter().any(|n| n.eq_ignore_ascii_case(q))),
9654                        Expr::Binary { lhs, rhs, .. } => walk(lhs, names) || walk(rhs, names),
9655                        Expr::Unary { expr, .. } | Expr::Cast { expr, .. } => walk(expr, names),
9656                        Expr::FunctionCall { args, .. } => args.iter().any(|a| walk(a, names)),
9657                        Expr::Case {
9658                            operand,
9659                            branches,
9660                            else_branch,
9661                        } => {
9662                            operand.as_deref().is_some_and(|o| walk(o, names))
9663                                || branches
9664                                    .iter()
9665                                    .any(|(w, t)| walk(w, names) || walk(t, names))
9666                                || else_branch.as_deref().is_some_and(|el| walk(el, names))
9667                        }
9668                        _ => false,
9669                    }
9670                }
9671                walk(e, &names)
9672            };
9673            let sub_select = |items: Vec<SelectItem>| SelectStatement {
9674                locking: None,
9675                ctes: Vec::new(),
9676                distinct: false,
9677                distinct_on: Vec::new(),
9678                items,
9679                from: Some(fc.clone()),
9680                where_: sub_where.clone(),
9681                group_by: None,
9682                group_by_all: false,
9683                having: None,
9684                unions: Vec::new(),
9685                order_by: Vec::new(),
9686                limit: None,
9687                offset: None,
9688                limit_with_ties: false,
9689                window_check_exprs: Vec::new(),
9690            };
9691            // v7.37 D.30 — replace each FROM-qualified column *leaf* in the
9692            // assignment RHS with a correlated scalar subquery, instead of
9693            // wrapping the whole RHS. Wrapping the whole expr moved a target-
9694            // column reference (`SET v = v + u.bonus`, where `v` is the target
9695            // table's column) inside a subquery whose FROM only has the source
9696            // table, so the unqualified `v` resolved against the source and
9697            // errored ColumnNotFound. Leaving target columns in the outer UPDATE
9698            // context — where they belong — fixes it; only the source columns
9699            // (`u.bonus`) become subqueries. A whole-expr fallback covers
9700            // compound variants the leaf-walk doesn't decompose.
9701            let make_subq = |inner: Expr| {
9702                Expr::ScalarSubquery(Box::new(sub_select(alloc::vec![SelectItem::Expr {
9703                    expr: inner,
9704                    alias: None,
9705                }])))
9706            };
9707            let assignments = assignments
9708                .into_iter()
9709                .map(|(col, mut expr)| {
9710                    wrap_from_leaves(&mut expr, &names, &make_subq, &refs_list);
9711                    (col, expr)
9712                })
9713                .collect();
9714            let exists = Expr::Exists {
9715                subquery: Box::new(sub_select(alloc::vec![SelectItem::Expr {
9716                    expr: Expr::Literal(Literal::Integer(1)),
9717                    alias: None,
9718                }])),
9719                negated: false,
9720            };
9721            // v7.39 (round 241) — RETURNING may reference the FROM-list
9722            // tables too (`RETURNING emp.id, dept.name`); the same
9723            // leaf-to-correlated-subquery lowering the assignments get.
9724            // Without it the qualifier died at eval with "unknown table
9725            // qualifier". (RETURNING was parsed before this block — the
9726            // lowering is a pure AST transformation.)
9727            if let Some(items) = returning.as_mut() {
9728                for item in items.iter_mut() {
9729                    if let SelectItem::Expr { expr, .. } = item {
9730                        wrap_from_leaves(expr, &names, &make_subq, &refs_list);
9731                    }
9732                }
9733            }
9734            // v7.39 (round 420, corrected in 421) — a MySQL LEFT JOIN keeps
9735            // EVERY matching target row: it gets no EXISTS filter, but the
9736            // caller's WHERE still applies, with source columns read through
9737            // the correlated subquery (NULL when unmatched — LEFT-join
9738            // semantics). `sub_where` above already excluded the WHERE from
9739            // the source subquery for this case.
9740            if mysql_outer {
9741                let mut outer = where_;
9742                if let Some(w) = outer.as_mut() {
9743                    wrap_from_leaves(w, &names, &make_subq, &refs_list);
9744                }
9745                (assignments, outer)
9746            } else {
9747                (assignments, Some(exists))
9748            }
9749        } else {
9750            (assignments, where_)
9751        };
9752        Ok(Statement::Update(crate::ast::UpdateStatement {
9753            ctes: Vec::new(),
9754            table,
9755            only,
9756            alias,
9757            assignments,
9758            from_sources,
9759            where_,
9760            order_limit: update_order_limit,
9761            returning,
9762        }))
9763    }
9764
9765    /// v7.39 (round 432) — MySQL's `[ORDER BY …] [LIMIT n]` tail on a DML
9766    /// statement. UPDATE grew it in round 413 and DELETE in round 432; the
9767    /// clause and its meaning are identical, so both call this rather than
9768    /// keeping two copies that could disagree on, say, whether `LIMIT 0` is
9769    /// legal. PG has no such clause on either statement, so it is read only
9770    /// under the MySQL dialect — a PG session's `DELETE … ORDER BY …` still
9771    /// errors.
9772    ///
9773    /// `#[inline(never)]`: its locals would otherwise land on the statement-
9774    /// parsing recursion frame, which is what tipped the 512 KiB nesting
9775    /// stack in round 430.
9776    #[inline(never)]
9777    fn parse_mysql_dml_order_limit(
9778        &mut self,
9779        what: &str,
9780    ) -> Result<Option<alloc::boxed::Box<crate::ast::DmlOrderLimit>>, ParseError> {
9781        if !self.mysql_dialect {
9782            return Ok(None);
9783        }
9784        let order_by = self.parse_order_by_keys()?;
9785        let limit = if matches!(self.peek(), Token::Limit) {
9786            self.advance();
9787            let tok = self.advance();
9788            let Token::Integer(n) = tok else {
9789                return Err(self.err(alloc::format!(
9790                    "expected integer after {what} LIMIT, got {tok:?}"
9791                )));
9792            };
9793            // MySQL rejects the `LIMIT offset, count` form here — only a
9794            // single row count is legal on a DML statement.
9795            if matches!(self.peek(), Token::Comma) {
9796                return Err(self.err(alloc::format!(
9797                    "{what} LIMIT takes a row count, not an offset"
9798                )));
9799            }
9800            let n = u32::try_from(n)
9801                .map_err(|_| self.err(alloc::format!("{what} LIMIT out of range: {n}")))?;
9802            Some(n)
9803        } else {
9804            None
9805        };
9806        if order_by.is_empty() && limit.is_none() {
9807            return Ok(None);
9808        }
9809        Ok(Some(alloc::boxed::Box::new(crate::ast::DmlOrderLimit {
9810            order_by,
9811            limit,
9812        })))
9813    }
9814
9815    /// v4.4 `DELETE FROM <table> [WHERE cond]`. Caller already consumed
9816    /// the leading `DELETE` ident.
9817    fn parse_delete_after_keyword(&mut self) -> Result<Statement, ParseError> {
9818        // v7.39 (round 421) — MySQL's multi-table DELETE names its target(s)
9819        // BEFORE the FROM: `DELETE a FROM a JOIN b ON …`. (`DELETE FROM a
9820        // USING a, b WHERE …` — the third MySQL spelling — needs no special
9821        // parse here; it reaches the existing USING path with the target
9822        // repeated in the list, which the source-list peel below handles.)
9823        // More than one name is a multi-TARGET delete, which SPG does not
9824        // model; it is refused rather than half-applied.
9825        let mysql_pre_target: Option<String> =
9826            if self.mysql_dialect && !matches!(self.peek(), Token::From) {
9827                let first = self.expect_ident_like()?;
9828                if matches!(self.peek(), Token::Comma) {
9829                    return Err(self.err(alloc::format!(
9830                        "multi-table DELETE can only delete from one table; \
9831                     `DELETE {first}, …` names several"
9832                    )));
9833                }
9834                Some(first)
9835            } else {
9836                None
9837            };
9838        if !matches!(self.peek(), Token::From) {
9839            return Err(self.err(format!("expected FROM after DELETE, got {:?}", self.peek())));
9840        }
9841        self.advance();
9842        // v7.39 (round 646) — `DELETE FROM ONLY t`, same shape and same
9843        // lookahead as the UPDATE spelling.
9844        let only = matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
9845            if s.eq_ignore_ascii_case("only"))
9846            && matches!(
9847                self.tokens.get(self.pos + 1),
9848                Some(Token::Ident(_) | Token::QuotedIdent(_))
9849            );
9850        if only {
9851            self.advance();
9852        }
9853        let table = self.expect_ident_like()?;
9854        // v7.39 (round 241) — `DELETE FROM t [AS] alias …`. The bare
9855        // spelling must not swallow the clause keywords that can follow
9856        // the target.
9857        let alias = if matches!(self.peek(), Token::As) {
9858            self.advance();
9859            Some(self.expect_ident_like()?)
9860        } else {
9861            match self.peek() {
9862                Token::Ident(s) | Token::QuotedIdent(s)
9863                    if !s.eq_ignore_ascii_case("using") && !s.eq_ignore_ascii_case("returning") =>
9864                {
9865                    let a = s.clone();
9866                    self.advance();
9867                    Some(a)
9868                }
9869                _ => None,
9870            }
9871        };
9872        // v7.39 (round 421) — MySQL's multi-table DELETE source list, read
9873        // through the SAME join grammar the FROM clause uses (see the
9874        // `advance()`-destroys-tokens note on `parse_from_joins`).
9875        let mut mysql_on: Option<Expr> = None;
9876        let mut mysql_outer = false;
9877        let mysql_using = if mysql_pre_target.is_some()
9878            && (matches!(self.peek(), Token::Comma) || self.peek_is_update_join_start())
9879        {
9880            let target_qual = alias.clone().unwrap_or_else(|| table.clone());
9881            let mut joins = self.parse_from_joins(&target_qual)?;
9882            if joins.is_empty() {
9883                return Err(self.err(alloc::string::String::from(
9884                    "multi-table DELETE needs at least one source table",
9885                )));
9886            }
9887            let head = joins.remove(0);
9888            mysql_outer = matches!(head.kind, crate::ast::JoinKind::Left);
9889            mysql_on = head.on;
9890            Some(FromClause {
9891                primary: head.table,
9892                joins,
9893            })
9894        } else {
9895            None
9896        };
9897        // The pre-FROM target must be the table the FROM names (or its
9898        // alias) — `DELETE b FROM a JOIN b …` would delete from a table that
9899        // is not the scan target.
9900        if let Some(t) = &mysql_pre_target {
9901            let names_target = t.eq_ignore_ascii_case(&table)
9902                || alias.as_deref().is_some_and(|a| a.eq_ignore_ascii_case(t));
9903            if !names_target {
9904                return Err(self.err(alloc::format!(
9905                    "DELETE target `{t}` is not the first table in the FROM clause ({table})"
9906                )));
9907            }
9908        }
9909        // `DELETE FROM t USING src [, …] WHERE cond` — PG's joined
9910        // delete. Same lowering as UPDATE … FROM: the WHERE
9911        // becomes EXISTS(SELECT 1 FROM src WHERE cond), driven per
9912        // target row by the correlated machinery.
9913        let using_clause = if let Some(fc) = mysql_using {
9914            Some(fc)
9915        } else if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("using")) {
9916            self.advance();
9917            let mut fc = self.parse_from_clause()?;
9918            // v7.39 (round 421) — MySQL's `DELETE FROM a USING a, b WHERE …`
9919            // repeats the TARGET as the first USING entry (PG's spelling
9920            // lists only the extra sources). Peel it so the source subquery
9921            // does not re-scan — and shadow — the target table.
9922            let primary_is_target =
9923                fc.primary.name.eq_ignore_ascii_case(&table) && fc.primary.alias.is_none();
9924            if self.mysql_dialect && primary_is_target && !fc.joins.is_empty() {
9925                let head = fc.joins.remove(0);
9926                mysql_outer = matches!(head.kind, crate::ast::JoinKind::Left);
9927                mysql_on = head.on;
9928                fc = FromClause {
9929                    primary: head.table,
9930                    joins: fc.joins,
9931                };
9932            }
9933            Some(fc)
9934        } else {
9935            None
9936        };
9937        let where_ = if matches!(self.peek(), Token::Where) {
9938            self.advance();
9939            Some(self.parse_expr(0)?)
9940        } else {
9941            None
9942        };
9943        // v7.39 (round 432) — MySQL's `DELETE … [ORDER BY …] [LIMIT n]`,
9944        // read before RETURNING (MariaDB's own extension trails the LIMIT).
9945        let delete_order_limit = self.parse_mysql_dml_order_limit("DELETE")?;
9946        let mut returning = self.parse_optional_returning()?;
9947        let where_ = if let Some(fc) = using_clause {
9948            // v7.39 (round 241) — same RETURNING lowering as UPDATE…FROM:
9949            // a USING-table reference in RETURNING becomes a correlated
9950            // scalar subquery over the USING list.
9951            let names: Vec<String> = core::iter::once(&fc.primary)
9952                .chain(fc.joins.iter().map(|j| &j.table))
9953                .flat_map(|t| {
9954                    t.alias
9955                        .clone()
9956                        .into_iter()
9957                        .chain(core::iter::once(t.name.clone()))
9958                })
9959                .collect();
9960            // v7.39 (round 421) — same ON / WHERE split as UPDATE: a LEFT
9961            // join filters the SOURCE subquery on the ON predicate alone and
9962            // leaves the WHERE filtering TARGET rows (so the anti-join idiom
9963            // `LEFT JOIN b ON … WHERE b.id IS NULL` deletes the unmatched
9964            // rows); every other form folds ON and WHERE into one EXISTS.
9965            let sub_where = match (mysql_on.clone(), where_.clone()) {
9966                _ if mysql_outer => mysql_on.clone(),
9967                (Some(on), Some(w)) => Some(Expr::Binary {
9968                    lhs: Box::new(on),
9969                    op: crate::ast::BinOp::And,
9970                    rhs: Box::new(w),
9971                }),
9972                (Some(on), None) => Some(on),
9973                (None, w) => w,
9974            };
9975            let exists_where = sub_where.clone();
9976            let sub_fc = fc.clone();
9977            let make_subq = move |leaf: Expr| -> Expr {
9978                Expr::ScalarSubquery(Box::new(SelectStatement {
9979                    locking: None,
9980                    ctes: Vec::new(),
9981                    distinct: false,
9982                    distinct_on: Vec::new(),
9983                    items: alloc::vec![SelectItem::Expr {
9984                        expr: leaf,
9985                        alias: None,
9986                    }],
9987                    from: Some(sub_fc.clone()),
9988                    where_: sub_where.clone(),
9989                    group_by: None,
9990                    group_by_all: false,
9991                    having: None,
9992                    unions: Vec::new(),
9993                    order_by: Vec::new(),
9994                    limit: None,
9995                    offset: None,
9996                    limit_with_ties: false,
9997                    window_check_exprs: Vec::new(),
9998                }))
9999            };
10000            let refs = |e: &Expr| expr_refs_tables(e, &names);
10001            if let Some(items) = returning.as_mut() {
10002                for item in items.iter_mut() {
10003                    if let SelectItem::Expr { expr, .. } = item {
10004                        wrap_from_leaves(expr, &names, &make_subq, &refs);
10005                    }
10006                }
10007            }
10008            // A LEFT join deletes the target rows the WHERE selects, reading
10009            // source columns through the correlated subquery (NULL when
10010            // unmatched); no EXISTS row filter.
10011            if mysql_outer {
10012                let mut outer = where_;
10013                if let Some(w) = outer.as_mut() {
10014                    wrap_from_leaves(w, &names, &make_subq, &refs);
10015                }
10016                outer
10017            } else {
10018                Some(Expr::Exists {
10019                    subquery: Box::new(SelectStatement {
10020                        locking: None,
10021                        ctes: Vec::new(),
10022                        distinct: false,
10023                        distinct_on: Vec::new(),
10024                        items: alloc::vec![SelectItem::Expr {
10025                            expr: Expr::Literal(Literal::Integer(1)),
10026                            alias: None,
10027                        }],
10028                        from: Some(fc),
10029                        where_: exists_where,
10030                        group_by: None,
10031                        group_by_all: false,
10032                        having: None,
10033                        unions: Vec::new(),
10034                        order_by: Vec::new(),
10035                        limit: None,
10036                        offset: None,
10037                        limit_with_ties: false,
10038                        window_check_exprs: Vec::new(),
10039                    }),
10040                    negated: false,
10041                })
10042            }
10043        } else {
10044            where_
10045        };
10046        Ok(Statement::Delete(crate::ast::DeleteStatement {
10047            ctes: Vec::new(),
10048            table,
10049            only,
10050            alias,
10051            where_,
10052            order_limit: delete_order_limit,
10053            returning,
10054        }))
10055    }
10056
10057    /// v7.17.0 Phase 3.P0-42 — parse `MERGE INTO <target> [alias]
10058    /// USING <source> [alias] ON <expr> WHEN [NOT] MATCHED [AND
10059    /// <expr>] THEN <action> [WHEN …]` after the leading `MERGE`
10060    /// keyword. v7.17 surface:
10061    ///   * source: table reference (subquery source is a follow-up)
10062    ///   * actions: UPDATE SET / DELETE / DO NOTHING (matched);
10063    ///     INSERT (cols) VALUES (vals) / DO NOTHING (not matched)
10064    ///   * AND-conditioned WHEN clauses; clauses tried in declaration
10065    ///     order
10066    fn parse_merge_after_keyword(&mut self) -> Result<Statement, ParseError> {
10067        // INTO
10068        let is_into_kw = matches!(self.peek(), Token::Into)
10069            || matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("into"));
10070        if !is_into_kw {
10071            return Err(self.err(format!("expected INTO after MERGE, got {:?}", self.peek())));
10072        }
10073        self.advance();
10074        let target = self.expect_ident_like()?;
10075        // Optional alias — bare ident before USING.
10076        let target_alias = match self.peek() {
10077            Token::Ident(s) | Token::QuotedIdent(s) if !s.eq_ignore_ascii_case("using") => {
10078                Some(self.expect_ident_like()?)
10079            }
10080            _ => None,
10081        };
10082        // USING
10083        let is_using_kw = matches!(
10084            self.peek(),
10085            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("using")
10086        );
10087        if !is_using_kw {
10088            return Err(self.err(format!(
10089                "expected USING after MERGE INTO target, got {:?}",
10090                self.peek()
10091            )));
10092        }
10093        self.advance();
10094        // v7.37 D.44 — `USING (SELECT …) alias` subquery source, or `USING
10095        // <table> [alias]`. PG requires an alias after a subquery source.
10096        let (source, source_select) = if matches!(self.peek(), Token::LParen) {
10097            self.advance(); // (
10098            // v7.39 (round 768, F31-D5) — `USING (VALUES …)`: the same
10099            // constant-SELECT lowering the derived-table parser uses
10100            // (PG deletes through this form; it was a parse error).
10101            let inner = if matches!(self.peek(), Token::Values) {
10102                self.advance(); // VALUES
10103                Statement::Select(self.parse_values_rows_body()?)
10104            } else {
10105                self.parse_select_stmt()?
10106            };
10107            match self.advance() {
10108                Token::RParen => {}
10109                other => {
10110                    return Err(self.err(format!(
10111                        "expected ')' after MERGE USING subquery, got {other:?}"
10112                    )));
10113                }
10114            }
10115            let Statement::Select(sub) = inner else {
10116                return Err(self.err("MERGE USING subquery must be a SELECT".into()));
10117            };
10118            (String::new(), Some(Box::new(sub)))
10119        } else {
10120            (self.expect_ident_like()?, None)
10121        };
10122        let source_alias = match self.peek() {
10123            Token::Ident(s) | Token::QuotedIdent(s)
10124                if !s.eq_ignore_ascii_case("on") && !s.eq_ignore_ascii_case("as") =>
10125            {
10126                Some(self.expect_ident_like()?)
10127            }
10128            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("as") => {
10129                self.advance(); // AS
10130                Some(self.expect_ident_like()?)
10131            }
10132            _ => None,
10133        };
10134        // v7.39 (round 768, F31-D5) — optional positional column-alias
10135        // list after the source alias (`s(id, v)`).
10136        let mut source_column_aliases: Vec<String> = Vec::new();
10137        if source_alias.is_some() && matches!(self.peek(), Token::LParen) {
10138            self.advance();
10139            loop {
10140                source_column_aliases.push(self.expect_ident_like()?);
10141                match self.peek() {
10142                    Token::Comma => {
10143                        self.advance();
10144                    }
10145                    Token::RParen => {
10146                        self.advance();
10147                        break;
10148                    }
10149                    other => {
10150                        return Err(self.err(format!(
10151                            "expected ',' or ')' in MERGE source column list, got {other:?}"
10152                        )));
10153                    }
10154                }
10155            }
10156        }
10157        if source_select.is_some() && source_alias.is_none() {
10158            return Err(self.err("MERGE USING (subquery) requires an alias".into()));
10159        }
10160        // ON
10161        if !matches!(self.peek(), Token::On) {
10162            return Err(self.err(format!(
10163                "expected ON after MERGE … USING source, got {:?}",
10164                self.peek()
10165            )));
10166        }
10167        self.advance();
10168        let on = self.parse_expr(0)?;
10169        // One or more WHEN clauses.
10170        let mut clauses: Vec<crate::ast::MergeWhenClause> = Vec::new();
10171        loop {
10172            let is_when_kw = matches!(
10173                self.peek(),
10174                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("when")
10175            );
10176            if !is_when_kw {
10177                break;
10178            }
10179            self.advance(); // WHEN
10180            // [NOT] MATCHED
10181            let matched = if matches!(self.peek(), Token::Not) {
10182                self.advance();
10183                crate::ast::MergeMatched::NotMatched
10184            } else {
10185                crate::ast::MergeMatched::Matched
10186            };
10187            let is_matched_kw = matches!(
10188                self.peek(),
10189                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("matched")
10190            );
10191            if !is_matched_kw {
10192                return Err(self.err(format!(
10193                    "expected MATCHED in WHEN clause, got {:?}",
10194                    self.peek()
10195                )));
10196            }
10197            self.advance();
10198            // v7.39 (round 146, PG17) — `NOT MATCHED [BY TARGET | BY SOURCE]`.
10199            // BY TARGET is the default (a synonym); BY SOURCE flips the clause
10200            // to fire for target rows no source row matches.
10201            let mut matched = matched;
10202            if matches!(matched, crate::ast::MergeMatched::NotMatched) && self.peek_is_by() {
10203                self.advance();
10204                match self.peek() {
10205                    Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("source") => {
10206                        self.advance();
10207                        matched = crate::ast::MergeMatched::NotMatchedBySource;
10208                    }
10209                    Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("target") => {
10210                        self.advance();
10211                    }
10212                    other => {
10213                        return Err(self.err(format!(
10214                            "expected SOURCE or TARGET after NOT MATCHED BY, got {other:?}"
10215                        )));
10216                    }
10217                }
10218            }
10219            // Optional AND <expr>
10220            let condition = if matches!(self.peek(), Token::And) {
10221                self.advance();
10222                Some(self.parse_expr(0)?)
10223            } else {
10224                None
10225            };
10226            // THEN
10227            let is_then_kw = matches!(
10228                self.peek(),
10229                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("then")
10230            );
10231            if !is_then_kw {
10232                return Err(self.err(format!(
10233                    "expected THEN in WHEN clause, got {:?}",
10234                    self.peek()
10235                )));
10236            }
10237            self.advance();
10238            // Action: INSERT / UPDATE / DELETE / DO NOTHING
10239            let action = match self.peek().clone() {
10240                Token::Insert => {
10241                    self.advance();
10242                    // v7.39 (read01 round 123) — the `(cols)` list is OPTIONAL,
10243                    // exactly like a plain INSERT: `WHEN NOT MATCHED THEN INSERT
10244                    // VALUES (…)` omits it and fills every column in declaration
10245                    // order. PG accepts this; SPG used to require the list.
10246                    let mut columns: Vec<String> = Vec::new();
10247                    if matches!(self.peek(), Token::LParen) {
10248                        self.advance();
10249                        loop {
10250                            columns.push(self.expect_ident_like()?);
10251                            if matches!(self.peek(), Token::Comma) {
10252                                self.advance();
10253                                continue;
10254                            }
10255                            break;
10256                        }
10257                        if !matches!(self.peek(), Token::RParen) {
10258                            return Err(self.err(format!(
10259                                "expected ')' after INSERT column list, got {:?}",
10260                                self.peek()
10261                            )));
10262                        }
10263                        self.advance();
10264                    }
10265                    // VALUES (...)
10266                    if !matches!(self.peek(), Token::Values) {
10267                        return Err(self.err(format!(
10268                            "expected VALUES in MERGE INSERT, got {:?}",
10269                            self.peek()
10270                        )));
10271                    }
10272                    self.advance();
10273                    if !matches!(self.peek(), Token::LParen) {
10274                        return Err(self.err(format!(
10275                            "expected '(' after VALUES in MERGE INSERT, got {:?}",
10276                            self.peek()
10277                        )));
10278                    }
10279                    self.advance();
10280                    let mut values: Vec<crate::ast::Expr> = Vec::new();
10281                    loop {
10282                        values.push(self.parse_expr(0)?);
10283                        if matches!(self.peek(), Token::Comma) {
10284                            self.advance();
10285                            continue;
10286                        }
10287                        break;
10288                    }
10289                    if !matches!(self.peek(), Token::RParen) {
10290                        return Err(self.err(format!(
10291                            "expected ')' after MERGE INSERT values, got {:?}",
10292                            self.peek()
10293                        )));
10294                    }
10295                    self.advance();
10296                    // Empty column list = positional into every column, so the
10297                    // count is checked against the table arity at execution.
10298                    if !columns.is_empty() && columns.len() != values.len() {
10299                        return Err(self.err(format!(
10300                            "MERGE INSERT column count ({}) ≠ value count ({})",
10301                            columns.len(),
10302                            values.len()
10303                        )));
10304                    }
10305                    crate::ast::MergeAction::Insert { columns, values }
10306                }
10307                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("update") => {
10308                    self.advance();
10309                    // SET
10310                    let is_set_kw = matches!(
10311                        self.peek(),
10312                        Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("set")
10313                    );
10314                    if !is_set_kw {
10315                        return Err(self.err(format!(
10316                            "expected SET after UPDATE in MERGE, got {:?}",
10317                            self.peek()
10318                        )));
10319                    }
10320                    self.advance();
10321                    let mut assignments: Vec<(String, crate::ast::Expr)> = Vec::new();
10322                    loop {
10323                        let col = self.expect_ident_like()?;
10324                        if !matches!(self.peek(), Token::Eq) {
10325                            return Err(self.err(format!(
10326                                "expected '=' in MERGE UPDATE assignment, got {:?}",
10327                                self.peek()
10328                            )));
10329                        }
10330                        self.advance();
10331                        let expr = self.parse_expr(0)?;
10332                        assignments.push((col, expr));
10333                        if matches!(self.peek(), Token::Comma) {
10334                            self.advance();
10335                            continue;
10336                        }
10337                        break;
10338                    }
10339                    crate::ast::MergeAction::Update { assignments }
10340                }
10341                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("delete") => {
10342                    self.advance();
10343                    crate::ast::MergeAction::Delete
10344                }
10345                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("do") => {
10346                    self.advance();
10347                    let is_nothing_kw = matches!(
10348                        self.peek(),
10349                        Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("nothing")
10350                    );
10351                    if !is_nothing_kw {
10352                        return Err(self.err(format!(
10353                            "expected NOTHING after DO in MERGE clause, got {:?}",
10354                            self.peek()
10355                        )));
10356                    }
10357                    self.advance();
10358                    crate::ast::MergeAction::DoNothing
10359                }
10360                other => {
10361                    return Err(self.err(format!(
10362                        "expected INSERT / UPDATE / DELETE / DO NOTHING in MERGE clause, got {other:?}"
10363                    )));
10364                }
10365            };
10366            // PG's grammar simply has no INSERT production under BY SOURCE
10367            // (a target row already exists there) — same syntax error.
10368            if matches!(matched, crate::ast::MergeMatched::NotMatchedBySource)
10369                && matches!(action, crate::ast::MergeAction::Insert { .. })
10370            {
10371                return Err(self.err(String::from("syntax error at or near \"INSERT\"")));
10372            }
10373            clauses.push(crate::ast::MergeWhenClause {
10374                matched,
10375                condition,
10376                action,
10377            });
10378        }
10379        if clauses.is_empty() {
10380            return Err(self.err(String::from("MERGE requires at least one WHEN clause")));
10381        }
10382        // v7.38 (read01 U-merge) — PG rejects a WHEN clause that follows an
10383        // unconditional (no `AND`) WHEN of the same match kind: it could
10384        // never fire. Check per match kind in clause order.
10385        let mut seen_unconditional_matched = false;
10386        let mut seen_unconditional_not_matched = false;
10387        let mut seen_unconditional_by_source = false;
10388        for c in &clauses {
10389            let seen = match c.matched {
10390                crate::ast::MergeMatched::Matched => &mut seen_unconditional_matched,
10391                crate::ast::MergeMatched::NotMatched => &mut seen_unconditional_not_matched,
10392                crate::ast::MergeMatched::NotMatchedBySource => &mut seen_unconditional_by_source,
10393            };
10394            if *seen {
10395                return Err(self.err(String::from(
10396                    "unreachable WHEN clause specified after unconditional WHEN clause",
10397                )));
10398            }
10399            if c.condition.is_none() {
10400                *seen = true;
10401            }
10402        }
10403        // v7.39 (round 130) — optional trailing `RETURNING <projection>` (PG17+).
10404        let returning = self.parse_optional_returning()?;
10405        Ok(Statement::Merge(crate::ast::MergeStatement {
10406            // Attached by `parse_with_cte_then_select` when the MERGE
10407            // heads a WITH clause (round 149).
10408            ctes: Vec::new(),
10409            target,
10410            target_alias,
10411            source,
10412            source_alias,
10413            source_select,
10414            source_column_aliases,
10415            on,
10416            clauses,
10417            returning,
10418        }))
10419    }
10420
10421    /// v7.9.4 — parse the optional trailing `RETURNING <projection>`
10422    /// clause on INSERT / UPDATE / DELETE. Same projection grammar
10423    /// as SELECT, so `RETURNING *`, `RETURNING col`,
10424    /// `RETURNING expr AS alias`, and `RETURNING a, b, c` all work.
10425    fn parse_optional_returning(
10426        &mut self,
10427    ) -> Result<Option<Vec<crate::ast::SelectItem>>, ParseError> {
10428        let is_returning_kw = matches!(
10429            self.peek(),
10430            Token::Ident(s) if s.eq_ignore_ascii_case("returning")
10431        );
10432        if !is_returning_kw {
10433            return Ok(None);
10434        }
10435        self.advance();
10436        let mut items = Vec::new();
10437        loop {
10438            items.push(self.parse_select_item()?);
10439            if matches!(self.peek(), Token::Comma) {
10440                self.advance();
10441                continue;
10442            }
10443            break;
10444        }
10445        Ok(Some(items))
10446    }
10447
10448    /// v6.0.4 — parse the tail of an ALTER statement after the
10449    /// leading `ALTER` keyword has been consumed. Only one form is
10450    /// supported in v6.0.4:
10451    ///
10452    /// ```text
10453    /// ALTER INDEX <name> REBUILD [WITH (encoding = <enc>)]
10454    /// ```
10455    fn parse_alter_after_keyword(&mut self) -> Result<Statement, ParseError> {
10456        // ALTER INDEX <name> ... | ALTER TABLE <name> SET hot_tier_bytes = <n>
10457        // v7.14.0 — `ALTER TABLE ONLY` modifier (PG partition-
10458        // exclusion) is accepted by stripping the `ONLY` keyword
10459        // before the table parse.
10460        // v7.14.0 — `ALTER SEQUENCE / ALTER VIEW / ALTER OWNER`
10461        // and the long PG-dump tail are accepted as no-ops.
10462        match self.advance() {
10463            Token::Index => {}
10464            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("index") => {}
10465            // v6.7.2 — ALTER TABLE t SET hot_tier_bytes = X
10466            // v7.14.0 — ALTER TABLE ONLY t … strip the `ONLY`.
10467            Token::Table => {
10468                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("only")) {
10469                    self.advance();
10470                }
10471                return self.parse_alter_table_after_keyword();
10472            }
10473            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("policy") => {
10474                return self.parse_alter_policy_after_keyword();
10475            }
10476            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("table") => {
10477                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("only")) {
10478                    self.advance();
10479                }
10480                return self.parse_alter_table_after_keyword();
10481            }
10482            // v7.17.0 — ALTER SEQUENCE name <options>. Moved out
10483            // of the silent-noop tail.
10484            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("sequence") => {
10485                return self.parse_alter_sequence_after_keyword();
10486            }
10487            // v7.37 D.55 — ALTER TYPE name ADD VALUE [IF NOT EXISTS] 'label'
10488            // [{BEFORE | AFTER} 'existing']. Real enum evolution; other ALTER
10489            // TYPE forms (RENAME / OWNER / SET SCHEMA) still no-op below.
10490            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("type") => {
10491                // NB: the match arm consumed `TYPE` via self.advance(); the
10492                // cursor is now at the type name — do NOT advance again.
10493                let type_name = self.expect_ident_like()?;
10494                let is_add_value = matches!(self.peek(), Token::Ident(a) if a.eq_ignore_ascii_case("add"))
10495                    && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(v)) if v.eq_ignore_ascii_case("value"));
10496                if is_add_value {
10497                    self.advance(); // ADD
10498                    self.advance(); // VALUE
10499                    // `IF NOT EXISTS` — NOT lexes as the keyword `Token::Not`,
10500                    // IF/EXISTS as identifiers.
10501                    let if_not_exists = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("if"))
10502                    {
10503                        let n1 = self.tokens.get(self.pos + 1);
10504                        let n2 = self.tokens.get(self.pos + 2);
10505                        if matches!(n1, Some(Token::Not))
10506                            && matches!(n2, Some(Token::Ident(s)) if s.eq_ignore_ascii_case("exists"))
10507                        {
10508                            self.advance();
10509                            self.advance();
10510                            self.advance();
10511                            true
10512                        } else {
10513                            false
10514                        }
10515                    } else {
10516                        false
10517                    };
10518                    let label = self.expect_string_literal()?;
10519                    let position = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("before") || s.eq_ignore_ascii_case("after"))
10520                    {
10521                        let is_before = matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("before"));
10522                        self.advance();
10523                        let anchor = self.expect_string_literal()?;
10524                        Some((is_before, anchor))
10525                    } else {
10526                        None
10527                    };
10528                    return Ok(Statement::AlterTypeAddValue {
10529                        type_name,
10530                        label,
10531                        if_not_exists,
10532                        position,
10533                    });
10534                }
10535                // v7.39 (read01 round 49) — `RENAME VALUE 'old' TO 'new'`.
10536                // Used to fall into the no-op tail below: accepted, silently
10537                // ignored. `RENAME TO <newtype>` keeps falling through.
10538                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("rename"))
10539                    && matches!(
10540                        self.tokens.get(self.pos + 1),
10541                        Some(Token::Ident(s)) if s.eq_ignore_ascii_case("value")
10542                    )
10543                {
10544                    self.advance(); // RENAME
10545                    self.advance(); // VALUE
10546                    let old = self.expect_string_literal()?;
10547                    if matches!(self.peek(), Token::To) {
10548                        self.advance();
10549                    } else {
10550                        self.expect_keyword_ident("to")?;
10551                    }
10552                    let new = self.expect_string_literal()?;
10553                    return Ok(Statement::AlterTypeRenameValue {
10554                        type_name,
10555                        old,
10556                        new,
10557                    });
10558                }
10559                // Other ALTER TYPE forms — the ACTION stays a no-op
10560                // (pg_dump tail), but v7.39 (round 708) the NAME is
10561                // validated: `ALTER TYPE nosuch RENAME TO x` reported
10562                // success for a type that does not exist.
10563                self.consume_until_statement_boundary();
10564                return Ok(Statement::ValidateOnly {
10565                    kind: crate::ast::ValidateOnlyKind::TypeName,
10566                    names: alloc::vec![type_name],
10567                });
10568            }
10569            // v7.14.0 — ALTER VIEW / ALTER FUNCTION /
10570            // ALTER DOMAIN / ALTER DATABASE / ALTER USER / ALTER
10571            // ROLE / ALTER SCHEMA / ALTER OWNER / ALTER DEFAULT
10572            // PRIVILEGES — accept as no-op so pg_dump's tail loads.
10573            // v7.17.0 NOTE: ALTER SEQUENCE moved out (above).
10574            // v7.39 (round 260) — ALTER DOMAIN is REAL now, so it leaves the
10575            // pg_dump no-op list below: every form used to report success
10576            // and change nothing, which is worse than refusing outright
10577            // (a migration dropping a constraint kept rejecting data).
10578            // NOTE: the enclosing `match self.advance()` already consumed
10579            // the DOMAIN keyword, so the name is next.
10580            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("domain") => {
10581                return self.parse_alter_domain_after_keyword();
10582            }
10583            // v7.39 (round 547) — `ALTER ROLE|USER <r> [IN DATABASE <d>]
10584            // SET|RESET …` and `ALTER DATABASE <d> SET|RESET …`. These
10585            // used to fall into the pg_dump no-op tail below, so a DBA
10586            // setting a per-role default was told it worked and nothing
10587            // happened. Intercepted here, BEFORE that tail.
10588            // v7.39 (round 695) — `ALTER SYSTEM SET <name> = …` / `RESET
10589            // <name>` / `RESET ALL`. Same reason the ROLE / DATABASE
10590            // interception below exists: swallowed with the no-op tail, an
10591            // unknown parameter name was ACCEPTED where PG18 answers
10592            // `unrecognized configuration parameter`. SPG applies nothing
10593            // either way — there is no postgresql.auto.conf — but it now
10594            // says so about a name it does not know.
10595            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("system") => {
10596                // NOTE: the scrutinee is `self.advance()`, so SYSTEM is
10597                // already consumed here. An extra advance eats the SET and
10598                // the parameter name is never seen — which is exactly the
10599                // bug a panic in this branch disproved: the branch WAS on
10600                // the path, the reading of it was wrong.
10601                let mut parameter = None;
10602                // SET <name> … | RESET <name> | RESET ALL
10603                if matches!(self.peek(), Token::Ident(k)
10604                    if k.eq_ignore_ascii_case("set") || k.eq_ignore_ascii_case("reset"))
10605                {
10606                    self.advance();
10607                    if let Token::Ident(n) | Token::QuotedIdent(n) = self.peek().clone()
10608                        && !n.eq_ignore_ascii_case("all")
10609                    {
10610                        self.advance();
10611                        // A dotted GUC (`plpgsql.check_asserts`) is two
10612                        // tokens; keep the whole name.
10613                        let mut full = n;
10614                        while matches!(self.peek(), Token::Dot) {
10615                            self.advance();
10616                            if let Token::Ident(t) | Token::QuotedIdent(t) = self.advance() {
10617                                full.push('.');
10618                                full.push_str(&t);
10619                            }
10620                        }
10621                        parameter = Some(full);
10622                    }
10623                }
10624                self.consume_until_statement_boundary();
10625                return Ok(Statement::AlterSystem { parameter });
10626            }
10627            Token::Ident(s) | Token::QuotedIdent(s)
10628                if matches!(
10629                    s.to_ascii_lowercase().as_str(),
10630                    "role" | "user" | "database"
10631                ) && self.peeks_db_role_setting() =>
10632            {
10633                let is_database = s.eq_ignore_ascii_case("database");
10634                return self.parse_db_role_setting(is_database);
10635            }
10636            // v7.39 (round 708) — `ALTER ROLE|USER <name> [WITH attrs…]`
10637            // (the non-SET forms; SET/RESET took the branch above). The
10638            // attributes still no-op — recorded, and the ignored PASSWORD
10639            // is ledgered as its own follow-up — but the ROLE is validated:
10640            // any name was accepted for a role that does not exist.
10641            Token::Ident(s) | Token::QuotedIdent(s)
10642                if s.eq_ignore_ascii_case("role") || s.eq_ignore_ascii_case("user") =>
10643            {
10644                // NB: the enclosing `match self.advance()` already consumed
10645                // ROLE/USER — the round-695 trap, hit again in this round's
10646                // first draft (the name was eaten and WITH parsed as the
10647                // role). The cursor is at the name.
10648                let name = self.expect_ident_or_string()?;
10649                // v7.39 (round 750) — scan the attribute tail for
10650                // PASSWORD. Everything else stays a recorded no-op, but
10651                // a dropped credential rotation is a SECURITY bug:
10652                // `ALTER USER x PASSWORD 'new'` answered ALTER ROLE and
10653                // changed nothing, so the old password kept working.
10654                // ENCRYPTED/UNENCRYPTED are PG-noise prefixes; `PASSWORD
10655                // NULL` clears the credential.
10656                let mut password: Option<Option<String>> = None;
10657                loop {
10658                    match self.peek() {
10659                        Token::Semicolon | Token::Eof => break,
10660                        Token::Ident(w) if w.eq_ignore_ascii_case("password") => {
10661                            self.advance();
10662                            match self.advance() {
10663                                Token::String(p) => password = Some(Some(p)),
10664                                Token::Null => password = Some(None),
10665                                Token::Ident(n) if n.eq_ignore_ascii_case("null") => {
10666                                    password = Some(None);
10667                                }
10668                                other => {
10669                                    return Err(self.err(alloc::format!(
10670                                        "expected password string or NULL after PASSWORD, got {other:?}"
10671                                    )));
10672                                }
10673                            }
10674                        }
10675                        _ => {
10676                            self.advance();
10677                        }
10678                    }
10679                }
10680                if name.eq_ignore_ascii_case("all") {
10681                    // `ALTER ROLE ALL …` names every role; nothing to check.
10682                    return Ok(Statement::Empty);
10683                }
10684                if let Some(pw) = password {
10685                    return Ok(Statement::AlterRolePassword { name, password: pw });
10686                }
10687                return Ok(Statement::ValidateOnly {
10688                    kind: crate::ast::ValidateOnlyKind::RoleName,
10689                    names: alloc::vec![name],
10690                });
10691            }
10692            // v7.39 (round 709) — ALTER COLLATION / TEXT SEARCH
10693            // CONFIGURATION / EVENT TRIGGER / LARGE OBJECT leave the no-op
10694            // list far enough to validate the NAME; the actions still no-op.
10695            // (TEXT SEARCH DICTIONARY / PARSER / TEMPLATE stay noise: SPG
10696            // models none of them and their dumps are rare.)
10697            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("collation") => {
10698                let name = self.expect_ident_or_string()?;
10699                self.consume_until_statement_boundary();
10700                return Ok(Statement::ValidateOnly {
10701                    kind: crate::ast::ValidateOnlyKind::CollationName,
10702                    names: alloc::vec![name],
10703                });
10704            }
10705            Token::Ident(s) | Token::QuotedIdent(s)
10706                if s.eq_ignore_ascii_case("text")
10707                    && matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("search"))
10708                    && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(k)) if k.eq_ignore_ascii_case("configuration")) =>
10709            {
10710                self.advance(); // SEARCH
10711                self.advance(); // CONFIGURATION
10712                let name = self.expect_ident_like()?;
10713                self.consume_until_statement_boundary();
10714                return Ok(Statement::ValidateOnly {
10715                    kind: crate::ast::ValidateOnlyKind::TsConfigName,
10716                    names: alloc::vec![name],
10717                });
10718            }
10719            Token::Ident(s) | Token::QuotedIdent(s)
10720                if s.eq_ignore_ascii_case("event")
10721                    && matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("trigger")) =>
10722            {
10723                self.advance(); // TRIGGER
10724                let name = self.expect_ident_like()?;
10725                self.consume_until_statement_boundary();
10726                return Ok(Statement::ValidateOnly {
10727                    kind: crate::ast::ValidateOnlyKind::EventTriggerName,
10728                    names: alloc::vec![name],
10729                });
10730            }
10731            Token::Ident(s) | Token::QuotedIdent(s)
10732                if s.eq_ignore_ascii_case("large")
10733                    && matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("object")) =>
10734            {
10735                self.advance(); // OBJECT
10736                let oid = match self.advance() {
10737                    Token::Integer(n) => alloc::format!("{n}"),
10738                    other => {
10739                        return Err(
10740                            self.err(alloc::format!("expected large object oid, got {other:?}"))
10741                        );
10742                    }
10743                };
10744                self.consume_until_statement_boundary();
10745                return Ok(Statement::ValidateOnly {
10746                    kind: crate::ast::ValidateOnlyKind::LargeObjectOid,
10747                    names: alloc::vec![oid],
10748                });
10749            }
10750            // v7.39 (round 708) — `ALTER AGGREGATE name(args) …`. Same
10751            // argument-list parse as DROP AGGREGATE (round 707); the
10752            // action no-ops, the existence check is real.
10753            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("aggregate") => {
10754                // Same round-695 trap as above: AGGREGATE is already
10755                // consumed; the cursor is at the name.
10756                let name = self.expect_ident_like()?;
10757                let mut names = alloc::vec![name];
10758                if matches!(self.peek(), Token::LParen) {
10759                    self.advance();
10760                    loop {
10761                        match self.peek().clone() {
10762                            Token::RParen => {
10763                                self.advance();
10764                                break;
10765                            }
10766                            Token::Star => {
10767                                self.advance();
10768                                names.push(String::from("*"));
10769                            }
10770                            Token::Comma => {
10771                                self.advance();
10772                            }
10773                            _ => {
10774                                let mut t = self.expect_ident_like()?;
10775                                while let Token::Ident(nx) = self.peek() {
10776                                    let nx = nx.clone();
10777                                    self.advance();
10778                                    t.push(' ');
10779                                    t.push_str(&nx);
10780                                }
10781                                names.push(t);
10782                            }
10783                        }
10784                    }
10785                }
10786                self.consume_until_statement_boundary();
10787                return Ok(Statement::ValidateOnly {
10788                    kind: crate::ast::ValidateOnlyKind::AggregateName,
10789                    names,
10790                });
10791            }
10792            Token::Ident(s) | Token::QuotedIdent(s)
10793                if matches!(
10794                    s.to_ascii_lowercase().as_str(),
10795                    "view"
10796                        | "function"
10797                        | "database"
10798                        | "schema"
10799                        | "owner"
10800                        | "default"
10801                        | "extension"
10802                        | "materialized"
10803                        | "publication"
10804                        | "subscription"
10805                        // v7.37.17 (17.6 siblings) — additional ALTER
10806                        // targets pg_dump / pg_dumpall / operator DB
10807                        // migration scripts commonly emit. SPG has
10808                        // no matching machinery for any of these; the
10809                        // parser accepts + Empty-returns so pg_dump
10810                        // tail statements don't stall.
10811                        | "tablespace"
10812                        | "language"
10813                        | "operator"
10814                        | "conversion"
10815                        | "statistics"
10816                        | "server"
10817                        | "foreign"
10818                        // `text` stays for TEXT SEARCH DICTIONARY / PARSER
10819                        // / TEMPLATE (CONFIGURATION intercepted above).
10820                        | "text"
10821                ) =>
10822            {
10823                self.consume_until_statement_boundary();
10824                return Ok(Statement::Empty);
10825            }
10826            other => {
10827                return Err(self.err(format!(
10828                    "expected INDEX / TABLE / SEQUENCE / VIEW / FUNCTION / TYPE / OWNER / etc \
10829                     after ALTER, got {other:?}"
10830                )));
10831            }
10832        }
10833        // v7.16.2 — optional `IF EXISTS` after ALTER INDEX
10834        // (mailrs migrate-042 ships these). The presence of an
10835        // IF EXISTS makes the subsequent name lookup tolerate
10836        // a missing index — engine returns CommandOk no-op.
10837        let if_exists = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("if")) {
10838            let next = self.tokens.get(self.pos + 1);
10839            if matches!(next, Some(Token::Ident(s)) if s.eq_ignore_ascii_case("exists")) {
10840                self.advance();
10841                self.advance();
10842                true
10843            } else {
10844                false
10845            }
10846        } else {
10847            false
10848        };
10849        let name = self.expect_ident_like()?;
10850        // v7.16.2 — RENAME TO new_name shape (mailrs migrate-042).
10851        // Detect BEFORE the REBUILD path so the existing REBUILD
10852        // arm stays untouched.
10853        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("rename")) {
10854            self.advance();
10855            if matches!(self.peek(), Token::To) {
10856                self.advance();
10857            } else {
10858                self.expect_keyword_ident("to")?;
10859            }
10860            let new = self.expect_ident_like()?;
10861            return Ok(Statement::AlterIndex(crate::ast::AlterIndexStatement {
10862                name,
10863                target: crate::ast::AlterIndexTarget::Rename { new, if_exists },
10864            }));
10865        }
10866        // v7.39 (round 710) — SET ( … ) / RESET ( … ) storage parameters.
10867        // A syntax error before; the index is validated, the params no-op.
10868        if matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("reset"))
10869            || (matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("set"))
10870                && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen)))
10871        {
10872            self.consume_until_statement_boundary();
10873            return Ok(Statement::AlterIndex(crate::ast::AlterIndexStatement {
10874                name,
10875                target: crate::ast::AlterIndexTarget::StorageParams,
10876            }));
10877        }
10878        // REBUILD
10879        self.expect_keyword_ident("rebuild")?;
10880        // Optional: WITH (encoding = <enc>)
10881        let encoding = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("with")) {
10882            self.advance();
10883            if !matches!(self.peek(), Token::LParen) {
10884                return Err(self.err(format!(
10885                    "expected '(' after WITH in ALTER INDEX REBUILD, got {:?}",
10886                    self.peek()
10887                )));
10888            }
10889            self.advance();
10890            self.expect_keyword_ident("encoding")?;
10891            if !matches!(self.peek(), Token::Eq) {
10892                return Err(self.err(format!(
10893                    "expected '=' after encoding in ALTER INDEX REBUILD, got {:?}",
10894                    self.peek()
10895                )));
10896            }
10897            self.advance();
10898            let enc_ident = match self.advance() {
10899                Token::Ident(s) | Token::QuotedIdent(s) => s,
10900                other => {
10901                    return Err(self.err(format!("expected encoding name after =, got {other:?}")));
10902                }
10903            };
10904            let enc = match enc_ident.to_ascii_lowercase().as_str() {
10905                "f32" => VecEncoding::F32,
10906                "sq8" => VecEncoding::Sq8,
10907                "half" => VecEncoding::F16,
10908                other => {
10909                    return Err(self.err(format!(
10910                        "unknown vector encoding {other:?} in ALTER INDEX REBUILD; supported: F32, SQ8, HALF"
10911                    )));
10912                }
10913            };
10914            if !matches!(self.peek(), Token::RParen) {
10915                return Err(self.err(format!(
10916                    "expected ')' after encoding value, got {:?}",
10917                    self.peek()
10918                )));
10919            }
10920            self.advance();
10921            Some(enc)
10922        } else {
10923            None
10924        };
10925        Ok(Statement::AlterIndex(crate::ast::AlterIndexStatement {
10926            name,
10927            target: crate::ast::AlterIndexTarget::Rebuild { encoding },
10928        }))
10929    }
10930
10931    /// v6.7.2 — `ALTER TABLE <name> SET hot_tier_bytes = <n>`. The
10932    /// only `SET` form currently supported; future v6.7.x can add
10933    /// more SET subjects without changing the dispatch shape.
10934    /// v7.13.2 — mailrs round-6 S1: accepts comma-separated
10935    /// subactions. Single-subaction shape stays a 1-element vec.
10936    fn parse_alter_table_after_keyword(&mut self) -> Result<Statement, ParseError> {
10937        let table_name = self.expect_ident_like()?;
10938        let mut targets: Vec<crate::ast::AlterTableTarget> = Vec::new();
10939        loop {
10940            let subaction = self.parse_alter_table_subaction()?;
10941            // ADD COLUMN with inline REFERENCES emits both an
10942            // AddColumn and an AddForeignKey subaction; the
10943            // helper returns 1 or 2 items.
10944            targets.extend(subaction);
10945            if matches!(self.peek(), Token::Comma) {
10946                self.advance();
10947                continue;
10948            }
10949            break;
10950        }
10951        Ok(Statement::AlterTable(crate::ast::AlterTableStatement {
10952            name: table_name,
10953            targets,
10954        }))
10955    }
10956
10957    /// Parse one ALTER TABLE subaction. Returns a Vec because
10958    /// inline `REFERENCES` on `ADD COLUMN` produces both an
10959    /// AddColumn and an AddForeignKey entry (mailrs round-6 S3).
10960    /// v7.39.9 — MySQL's `FIRST` / `AFTER <col>` trailer on ADD /
10961    /// MODIFY / CHANGE COLUMN. Absent is the PostgreSQL form, which
10962    /// appends.
10963    fn parse_column_position(&mut self) -> Option<crate::ast::ColumnPosition> {
10964        match self.peek() {
10965            Token::Ident(s) if s.eq_ignore_ascii_case("first") => {
10966                self.advance();
10967                Some(crate::ast::ColumnPosition::First)
10968            }
10969            Token::Ident(s) if s.eq_ignore_ascii_case("after") => {
10970                self.advance();
10971                let name = self.expect_ident_like().ok()?;
10972                Some(crate::ast::ColumnPosition::After(name))
10973            }
10974            _ => None,
10975        }
10976    }
10977
10978    fn parse_alter_table_subaction(
10979        &mut self,
10980    ) -> Result<Vec<crate::ast::AlterTableTarget>, ParseError> {
10981        match self.peek() {
10982            // v7.39.9 — MySQL's own ALTER TABLE vocabulary. Each one is
10983            // a statement a real migration emits and SPG answered 1064
10984            // for; measured against MySQL 9.7.2, one at a time, beside
10985            // the published image.
10986            Token::Ident(s)
10987                if s.eq_ignore_ascii_case("modify") || s.eq_ignore_ascii_case("change") =>
10988            {
10989                let changing = s.eq_ignore_ascii_case("change");
10990                self.advance();
10991                if matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("column")) {
10992                    self.advance();
10993                }
10994                // `parse_column_def_with_fk` reads the NAME itself, so
10995                // `MODIFY` hands it the column and `CHANGE` eats the old
10996                // name first and lets it read the new one.
10997                let old_name = if changing {
10998                    Some(self.expect_ident_like()?)
10999                } else {
11000                    None
11001                };
11002                let (definition, _fk) = self.parse_column_def_with_fk()?;
11003                let column = old_name.clone().unwrap_or_else(|| definition.name.clone());
11004                let rename_to = if changing {
11005                    Some(definition.name.clone())
11006                } else {
11007                    None
11008                };
11009                let position = self.parse_column_position();
11010                Ok(alloc::vec![crate::ast::AlterTableTarget::ModifyColumn {
11011                    column,
11012                    rename_to,
11013                    definition,
11014                    position,
11015                }])
11016            }
11017            Token::Ident(s) if s.eq_ignore_ascii_case("auto_increment") => {
11018                self.advance();
11019                if matches!(self.peek(), Token::Eq) {
11020                    self.advance();
11021                }
11022                let n = self.expect_u64_literal()?;
11023                Ok(alloc::vec![
11024                    crate::ast::AlterTableTarget::SetTableAutoIncrement(
11025                        i64::try_from(n).unwrap_or(i64::MAX)
11026                    )
11027                ])
11028            }
11029            Token::Ident(s) if s.eq_ignore_ascii_case("engine") => {
11030                self.advance();
11031                if matches!(self.peek(), Token::Eq) {
11032                    self.advance();
11033                }
11034                let name = self.expect_ident_like()?;
11035                Ok(alloc::vec![crate::ast::AlterTableTarget::SetEngine(name)])
11036            }
11037            Token::Ident(s) if s.eq_ignore_ascii_case("convert") => {
11038                self.advance();
11039                // CONVERT TO CHARACTER SET <cs> [COLLATE <c>]
11040                if matches!(self.peek(), Token::To) {
11041                    self.advance();
11042                }
11043                let kw = self.expect_ident_like()?;
11044                if !kw.eq_ignore_ascii_case("character") {
11045                    return Err(self.err("expected CHARACTER after CONVERT TO".into()));
11046                }
11047                let set_kw = self.expect_ident_like()?;
11048                if !set_kw.eq_ignore_ascii_case("set") {
11049                    return Err(self.err("expected SET after CHARACTER".into()));
11050                }
11051                let charset = self.expect_ident_like()?;
11052                let collate =
11053                    if matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("collate")) {
11054                        self.advance();
11055                        Some(self.expect_ident_like()?)
11056                    } else {
11057                        None
11058                    };
11059                Ok(alloc::vec![
11060                    crate::ast::AlterTableTarget::ConvertToCharacterSet { charset, collate }
11061                ])
11062            }
11063            Token::Ident(s) if s.eq_ignore_ascii_case("set") => {
11064                self.advance();
11065                // v7.37.18 (18.7-18.15) — SET ( option = value, … )
11066                // storage parameters: paren-prefixed; consume.
11067                if matches!(self.peek(), Token::LParen) {
11068                    self.consume_until_statement_boundary();
11069                    return Ok(Vec::new());
11070                }
11071                let setting = self.expect_ident_like()?;
11072                if setting.eq_ignore_ascii_case("hot_tier_bytes") {
11073                    if !matches!(self.peek(), Token::Eq) {
11074                        return Err(self.err(alloc::format!(
11075                            "expected '=' after hot_tier_bytes, got {:?}",
11076                            self.peek()
11077                        )));
11078                    }
11079                    self.advance();
11080                    let n = self.expect_u64_literal()?;
11081                    return Ok(alloc::vec![crate::ast::AlterTableTarget::SetHotTierBytes(n)]);
11082                }
11083                // v7.37.18 (18.7 / 18.8 / 18.11 / 18.13 / 18.14) —
11084                // accept-and-no-op for ALTER TABLE SET <subject>
11085                // forms that pg_dump emits but SPG either treats
11086                // as N/A (single-tenant, single-owner, no shared
11087                // tablespaces) or accepts the dump-side declaration
11088                // without runtime effect:
11089                //   SET SCHEMA <name>            (18.11)
11090                //   SET TABLESPACE <name>        (18.8)
11091                //   SET LOGGED / UNLOGGED        (18.7 alt-form)
11092                //   SET WITHOUT CLUSTER          (18.13)
11093                //   SET WITHOUT OIDS             (PG legacy)
11094                //   SET (option = value, …)      (storage parameters)
11095                //   SET REPLICA IDENTITY {…}     (18.14)
11096                if setting.eq_ignore_ascii_case("schema")
11097                    || setting.eq_ignore_ascii_case("tablespace")
11098                    || setting.eq_ignore_ascii_case("logged")
11099                    || setting.eq_ignore_ascii_case("unlogged")
11100                    || setting.eq_ignore_ascii_case("without")
11101                {
11102                    self.consume_until_statement_boundary();
11103                    return Ok(Vec::new());
11104                }
11105                if setting.eq_ignore_ascii_case("replica") {
11106                    // SET REPLICA IDENTITY {DEFAULT|FULL|NOTHING|USING INDEX <name>}
11107                    self.consume_until_statement_boundary();
11108                    return Ok(Vec::new());
11109                }
11110                // SET (option=value, …) — storage parameters.
11111                if matches!(self.peek(), Token::LParen) {
11112                    self.consume_until_statement_boundary();
11113                    return Ok(Vec::new());
11114                }
11115                Err(self.err(alloc::format!(
11116                    "ALTER TABLE SET: unknown setting {setting:?}; supported: \
11117                     hot_tier_bytes / SCHEMA / TABLESPACE / LOGGED / UNLOGGED / \
11118                     WITHOUT CLUSTER / WITHOUT OIDS / REPLICA IDENTITY / (storage_params)"
11119                )))
11120            }
11121            // v7.39 (round 647) — `ALTER TABLE c INHERIT p`. Carried now,
11122            // not ignored: round 645 gave SPG the inheritance the
11123            // v7.37.18 no-op said it did not have.
11124            Token::Ident(s) if s.eq_ignore_ascii_case("inherit") => {
11125                self.advance();
11126                let parent = self.expect_ident_like()?;
11127                self.consume_until_statement_boundary();
11128                Ok(alloc::vec![crate::ast::AlterTableTarget::Inherit {
11129                    parent,
11130                    detach: false
11131                }])
11132            }
11133            // `NO INHERIT <parent>`. Guarded to NOT match `NO FORCE ROW
11134            // LEVEL SECURITY`, which has its own RLS arm below — without
11135            // the guard this swallowed NO FORCE as a no-op.
11136            Token::Ident(s)
11137                if s.eq_ignore_ascii_case("no")
11138                    && !matches!(
11139                        self.tokens.get(self.pos + 1),
11140                        Some(Token::Ident(t)) if t.eq_ignore_ascii_case("force")
11141                    ) =>
11142            {
11143                self.advance();
11144                if matches!(self.peek(), Token::Ident(k) | Token::QuotedIdent(k)
11145                    if k.eq_ignore_ascii_case("inherit"))
11146                {
11147                    self.advance();
11148                    let parent = self.expect_ident_like()?;
11149                    self.consume_until_statement_boundary();
11150                    return Ok(alloc::vec![crate::ast::AlterTableTarget::Inherit {
11151                        parent,
11152                        detach: true
11153                    }]);
11154                }
11155                self.consume_until_statement_boundary();
11156                Ok(Vec::new())
11157            }
11158            // v7.37.18 (18.10) — ALTER TABLE OWNER TO <user>. SPG is
11159            // single-owner, so there is still nothing to record.
11160            //
11161            // v7.39 (round 652) — but the name now reaches the engine,
11162            // which refuses a role that does not exist as PG does. The
11163            // no-op was swallowing the whole statement, so a dump naming
11164            // a role this server never heard of restored clean and left
11165            // the table owned by whoever ran the restore.
11166            Token::Ident(s) if s.eq_ignore_ascii_case("owner") => {
11167                self.advance();
11168                if matches!(self.peek(), Token::To) {
11169                    self.advance();
11170                }
11171                let role = self.expect_ident_like()?;
11172                Ok(alloc::vec![crate::ast::AlterTableTarget::OwnerTo {
11173                    role
11174                }])
11175            }
11176            // v7.37.18 (18.13) — ALTER TABLE CLUSTER ON <index>.
11177            // PG sets a hint; SPG doesn't have clustered storage, so the
11178            // hint itself stays a no-op.
11179            //
11180            // v7.39 (round 652) — the index name is checked now. PG
11181            // errors on one that does not exist, and swallowing that let
11182            // a typo'd CLUSTER ON pass silently.
11183            Token::Ident(s) if s.eq_ignore_ascii_case("cluster") => {
11184                self.advance();
11185                // `ON` is a reserved token, not an ident.
11186                if !matches!(self.peek(), Token::On) {
11187                    return Err(self.err(alloc::format!(
11188                        "expected ON after CLUSTER, got {:?}",
11189                        self.peek()
11190                    )));
11191                }
11192                self.advance();
11193                let index = self.expect_ident_like()?;
11194                Ok(alloc::vec![crate::ast::AlterTableTarget::ClusterOn {
11195                    index: Some(index)
11196                }])
11197            }
11198            // v7.39 (read01 round 49) — ALTER TABLE REPLICA IDENTITY
11199            // { DEFAULT | FULL | NOTHING | USING INDEX <name> }. PG records
11200            // what a logical decoder puts in the old-tuple image; SPG's
11201            // replication is SQL-text, so there is nothing to record.
11202            // Accept-and-no-op (it used to be a parse error).
11203            Token::Ident(s) if s.eq_ignore_ascii_case("replica") => {
11204                self.advance();
11205                // v7.39 (round 710) — `REPLICA IDENTITY USING INDEX <i>`
11206                // validates the index; DEFAULT / FULL / NOTHING stay no-op.
11207                if matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("identity"))
11208                    && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(k)) if k.eq_ignore_ascii_case("using"))
11209                {
11210                    self.advance(); // IDENTITY
11211                    self.advance(); // USING
11212                    if matches!(self.peek(), Token::Index)
11213                        || matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("index"))
11214                    {
11215                        self.advance();
11216                    }
11217                    let index = self.expect_ident_like()?;
11218                    self.consume_until_statement_boundary();
11219                    return Ok(alloc::vec![
11220                        crate::ast::AlterTableTarget::ReplicaIdentityUsingIndex { index }
11221                    ]);
11222                }
11223                self.consume_until_statement_boundary();
11224                Ok(Vec::new())
11225            }
11226            // v7.37.18 (18.15) — ALTER TABLE VALIDATE CONSTRAINT <name>.
11227            //
11228            // v7.39 (round 652) — it used to consume the statement and
11229            // return nothing, on the stated theory that SPG validated at
11230            // ADD CONSTRAINT time so there was never anything left to
11231            // validate. Measured against PG18, ADD CONSTRAINT did not
11232            // scan the existing rows at all — the comment described a
11233            // property SPG did not have, which is why nobody looked. Both
11234            // halves are real now: ADD scans unless told NOT VALID, and
11235            // this scans what NOT VALID skipped.
11236            Token::Ident(s) if s.eq_ignore_ascii_case("validate") => {
11237                self.advance();
11238                self.expect_keyword_ident("constraint")?;
11239                let name = self.expect_ident_like()?;
11240                Ok(alloc::vec![
11241                    crate::ast::AlterTableTarget::ValidateConstraint { name }
11242                ])
11243            }
11244            // v7.37.18 (18.18) — RESET ( option [, …] ). Inverse of
11245            // SET (option = value, …). PG uses it to clear per-table
11246            // storage params like fillfactor or autovacuum_*. SPG
11247            // engine-manages those parameters; accept-and-no-op.
11248            Token::Ident(s) if s.eq_ignore_ascii_case("reset") => {
11249                self.advance();
11250                self.consume_until_statement_boundary();
11251                Ok(Vec::new())
11252            }
11253            // v7.37.18 (18.18) — OF <type_name> / NOT OF. Composite-
11254            // type-of binding (PG 9.0+). SPG composite types
11255            // (v7.37.5 ζ-B sub-commit) follow CREATE TYPE; ALTER
11256            // TABLE OF is rare and inverse of CREATE TABLE OF.
11257            // Accept-and-no-op until a customer dump round-trips it.
11258            Token::Ident(s) if s.eq_ignore_ascii_case("of") => {
11259                self.advance();
11260                // v7.39 (round 710) — the type name is validated now.
11261                let type_name = self.expect_ident_like()?;
11262                self.consume_until_statement_boundary();
11263                Ok(alloc::vec![crate::ast::AlterTableTarget::OfType {
11264                    type_name
11265                }])
11266            }
11267            // v7.37.18 (18.18) — `NOT OF` lexes NOT as Token::Not
11268            // (reserved keyword) rather than Token::Ident("not"),
11269            // so it needs its own arm. Accept-and-no-op same as OF.
11270            Token::Not => {
11271                self.advance();
11272                self.consume_until_statement_boundary();
11273                Ok(Vec::new())
11274            }
11275            // v7.39 (RLS) — FORCE ROW LEVEL SECURITY (sets relforcerowsecurity).
11276            Token::Ident(s) if s.eq_ignore_ascii_case("force") => {
11277                self.advance();
11278                self.expect_row_level_security()?;
11279                Ok(alloc::vec![crate::ast::AlterTableTarget::SetRowSecurity {
11280                    enabled: None,
11281                    force: Some(true),
11282                }])
11283            }
11284            // v7.39 (RLS) — NO FORCE ROW LEVEL SECURITY.
11285            Token::Ident(s)
11286                if s.eq_ignore_ascii_case("no")
11287                    && matches!(
11288                        self.tokens.get(self.pos + 1),
11289                        Some(Token::Ident(t)) if t.eq_ignore_ascii_case("force")
11290                    ) =>
11291            {
11292                self.advance(); // NO
11293                self.advance(); // FORCE
11294                self.expect_row_level_security()?;
11295                Ok(alloc::vec![crate::ast::AlterTableTarget::SetRowSecurity {
11296                    enabled: None,
11297                    force: Some(false),
11298                }])
11299            }
11300            // v7.39 (RLS) — ENABLE/DISABLE ROW LEVEL SECURITY
11301            // (sets relrowsecurity). The guard requires the next token to be
11302            // `ROW` so the ENABLE/DISABLE TRIGGER arm still matches its case.
11303            Token::Ident(s)
11304                if (s.eq_ignore_ascii_case("enable") || s.eq_ignore_ascii_case("disable"))
11305                    && matches!(
11306                        self.tokens.get(self.pos + 1),
11307                        Some(Token::Ident(t)) if t.eq_ignore_ascii_case("row")
11308                    ) =>
11309            {
11310                let enabled = s.eq_ignore_ascii_case("enable");
11311                self.advance(); // ENABLE/DISABLE
11312                self.expect_row_level_security()?;
11313                Ok(alloc::vec![crate::ast::AlterTableTarget::SetRowSecurity {
11314                    enabled: Some(enabled),
11315                    force: None,
11316                }])
11317            }
11318            Token::Ident(s) if s.eq_ignore_ascii_case("add") => {
11319                self.advance();
11320                // v7.39 (round 431) — MySQL's `ALTER TABLE t ADD [UNIQUE]
11321                // {INDEX|KEY} [name] (cols)`, which every ORM migration
11322                // emits. The same grammar CREATE TABLE already accepts
11323                // inline (`KEY idx (a)`, prefix lengths and all), so it goes
11324                // through the SAME parser — an ALTER-only copy would be a
11325                // second place for the two to drift.
11326                if self.peek_mysql_inline_key_start() {
11327                    return Ok(match self.parse_mysql_inline_key()? {
11328                        Some(c) => {
11329                            alloc::vec![crate::ast::AlterTableTarget::AddTableConstraint(c)]
11330                        }
11331                        // FULLTEXT / SPATIAL parse and are accepted as a
11332                        // no-op here exactly as they are inline.
11333                        None => Vec::new(),
11334                    });
11335                }
11336                // v7.14.0 — ADD CONSTRAINT <name> { FOREIGN KEY |
11337                // PRIMARY KEY | UNIQUE | CHECK }. pg_dump emits
11338                // PRIMARY KEY this way; mysqldump emits both.
11339                // Peek-only dispatch (no advance) — `advance()`
11340                // destructively replaces consumed tokens with Eof,
11341                // so saved-pos restore would land on Eofs.
11342                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("constraint"))
11343                {
11344                    // The next-but-one ident is the constraint
11345                    // name; the one after THAT is the kind.
11346                    let kind_pos = self.pos + 2;
11347                    let kind = self.tokens.get(kind_pos).cloned();
11348                    if matches!(&kind, Some(Token::Ident(s)) if s.eq_ignore_ascii_case("foreign"))
11349                    {
11350                        let fk = self.parse_table_level_fk()?;
11351                        return Ok(alloc::vec![
11352                            crate::ast::AlterTableTarget::AddForeignKey(fk)
11353                        ]);
11354                    }
11355                    if matches!(&kind, Some(Token::Ident(s)) if s.eq_ignore_ascii_case("primary"))
11356                    {
11357                        self.advance(); // CONSTRAINT
11358                        // v7.39 (read01 round 48) — keep the name; the engine
11359                        // stores it now instead of dropping it on the floor.
11360                        let con_name = self.expect_ident_like()?;
11361                        self.advance(); // PRIMARY
11362                        self.expect_keyword_ident("key")?;
11363                        let cols = self.parse_paren_ident_list("PRIMARY KEY")?;
11364                        // v7.39 (round 711) — the ALTER form carries the
11365                        // timing too (pg_dump writes it here).
11366                        let (deferrable, initially_deferred) =
11367                            self.consume_deferrable_clauses_timed()?;
11368                        return Ok(alloc::vec![
11369                            crate::ast::AlterTableTarget::AddTableConstraint(
11370                                crate::ast::TableConstraint::PrimaryKey {
11371                                    name: Some(con_name),
11372                                    columns: cols,
11373                                    deferrable,
11374                                    initially_deferred,
11375                                }
11376                            )
11377                        ]);
11378                    }
11379                    if matches!(&kind, Some(Token::Ident(s)) if s.eq_ignore_ascii_case("unique"))
11380                    {
11381                        self.advance(); // CONSTRAINT
11382                        // v7.39 (read01 round 48) — keep the name.
11383                        let con_name = self.expect_ident_like()?;
11384                        // v7.22 (mailrs round-13 gap 6) — delegate so
11385                        // the optional `NULLS [NOT] DISTINCT` modifier
11386                        // parses here too (pg_dump emits the ALTER
11387                        // form; semantics enforced by the engine
11388                        // since v7.13).
11389                        let mut uc = self.parse_table_level_unique()?;
11390                        if let crate::ast::TableConstraint::Unique { name, .. } = &mut uc {
11391                            *name = Some(con_name);
11392                        }
11393                        return Ok(alloc::vec![
11394                            crate::ast::AlterTableTarget::AddTableConstraint(uc)
11395                        ]);
11396                    }
11397                    if matches!(&kind, Some(Token::Ident(s)) if s.eq_ignore_ascii_case("check"))
11398                    {
11399                        self.advance(); // CONSTRAINT
11400                        // v7.39 (read01 round 48) — keep the name.
11401                        let con_name = self.expect_ident_like()?;
11402                        self.advance(); // CHECK
11403                        if !matches!(self.peek(), Token::LParen) {
11404                            return Err(self.err(alloc::format!(
11405                                "expected '(' after CHECK, got {:?}", self.peek()
11406                            )));
11407                        }
11408                        self.advance();
11409                        let expr = self.parse_expr(0)?;
11410                        if matches!(self.peek(), Token::RParen) {
11411                            self.advance();
11412                        }
11413                        let not_valid = self.parse_not_valid_suffix();
11414                        return Ok(alloc::vec![
11415                            crate::ast::AlterTableTarget::AddTableConstraint(
11416                                crate::ast::TableConstraint::Check {
11417                                    name: Some(con_name),
11418                                    expr,
11419                                    not_valid,
11420                                }
11421                            )
11422                        ]);
11423                    }
11424                    // v7.39 (round 211) — ADD CONSTRAINT <name> EXCLUDE
11425                    // [USING <am>] (<col> WITH <op>[, …]). pg_dump emits
11426                    // exclusion constraints via this ALTER form.
11427                    if matches!(&kind, Some(Token::Ident(s)) if s.eq_ignore_ascii_case("exclude"))
11428                    {
11429                        self.advance(); // CONSTRAINT
11430                        let con_name = self.expect_ident_like()?;
11431                        let mut ex = self.parse_table_level_exclude()?;
11432                        if let crate::ast::TableConstraint::Exclude { name, .. } = &mut ex {
11433                            *name = Some(con_name);
11434                        }
11435                        return Ok(alloc::vec![
11436                            crate::ast::AlterTableTarget::AddTableConstraint(ex)
11437                        ]);
11438                    }
11439                    // Unknown kind — fall through to FK path which
11440                    // produces a descriptive parse error.
11441                }
11442                let is_fk = matches!(
11443                    self.peek(),
11444                    Token::Ident(s) if s.eq_ignore_ascii_case("constraint")
11445                        || s.eq_ignore_ascii_case("foreign")
11446                );
11447                if is_fk {
11448                    let fk = self.parse_table_level_fk()?;
11449                    return Ok(alloc::vec![crate::ast::AlterTableTarget::AddForeignKey(fk)]);
11450                }
11451                // v7.14.0 — bare ADD PRIMARY KEY / UNIQUE / CHECK
11452                // (no CONSTRAINT prefix) — same dispatch.
11453                match self.peek().clone() {
11454                    Token::Ident(s) if s.eq_ignore_ascii_case("primary") => {
11455                        self.advance();
11456                        self.expect_keyword_ident("key")?;
11457                        let cols = self.parse_paren_ident_list("PRIMARY KEY")?;
11458                        let (deferrable, initially_deferred) =
11459                            self.consume_deferrable_clauses_timed()?;
11460                        return Ok(alloc::vec![
11461                            crate::ast::AlterTableTarget::AddTableConstraint(
11462                                crate::ast::TableConstraint::PrimaryKey {
11463                                    name: None,
11464                                    columns: cols,
11465                                    deferrable,
11466                                    initially_deferred,
11467                                }
11468                            )
11469                        ]);
11470                    }
11471                    Token::Ident(s) if s.eq_ignore_ascii_case("unique") => {
11472                        // v7.22 — delegate (NULLS [NOT] DISTINCT).
11473                        let uc = self.parse_table_level_unique()?;
11474                        return Ok(alloc::vec![
11475                            crate::ast::AlterTableTarget::AddTableConstraint(uc)
11476                        ]);
11477                    }
11478                    // v7.39 (round 652) — bare ADD CHECK (no CONSTRAINT
11479                    // prefix). The other three bare forms were here and
11480                    // this one was not, so it fell through to the column
11481                    // path and came back as "unexpected reserved keyword
11482                    // 'check' at start of column definition".
11483                    _ if self.peek_table_level_check_start() => {
11484                        let chk = self.parse_table_level_check()?;
11485                        let not_valid = self.parse_not_valid_suffix();
11486                        let crate::ast::TableConstraint::Check { expr, .. } = chk else {
11487                            unreachable!("parse_table_level_check returns Check")
11488                        };
11489                        return Ok(alloc::vec![
11490                            crate::ast::AlterTableTarget::AddTableConstraint(
11491                                crate::ast::TableConstraint::Check {
11492                                    name: None,
11493                                    expr,
11494                                    not_valid,
11495                                }
11496                            )
11497                        ]);
11498                    }
11499                    // v7.39 (round 211) — bare ADD EXCLUDE (no CONSTRAINT prefix).
11500                    Token::Ident(s) if s.eq_ignore_ascii_case("exclude") => {
11501                        let ex = self.parse_table_level_exclude()?;
11502                        return Ok(alloc::vec![
11503                            crate::ast::AlterTableTarget::AddTableConstraint(ex)
11504                        ]);
11505                    }
11506                    _ => {}
11507                }
11508                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("column")) {
11509                    self.advance();
11510                }
11511                let mut if_not_exists = false;
11512                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("if")) {
11513                    self.advance();
11514                    if !matches!(self.peek(), Token::Not) {
11515                        return Err(self.err(alloc::format!(
11516                            "expected NOT after IF in ALTER TABLE ADD COLUMN, got {:?}",
11517                            self.peek()
11518                        )));
11519                    }
11520                    self.advance();
11521                    if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("exists")) {
11522                        return Err(self.err(alloc::format!(
11523                            "expected EXISTS after IF NOT in ALTER TABLE ADD COLUMN, got {:?}",
11524                            self.peek()
11525                        )));
11526                    }
11527                    self.advance();
11528                    if_not_exists = true;
11529                }
11530                // v7.13.2 — mailrs round-6 S3: `ADD COLUMN col TYPE
11531                // REFERENCES other(col) [ON DELETE …]`. parse_column_def
11532                // returns ColumnDef + an optional inline FK.
11533                let (column, col_level_fk) = self.parse_column_def_with_fk()?;
11534                let col_name = column.name.clone();
11535                // v7.39.9 — MySQL says where the column goes.
11536                let position = self.parse_column_position();
11537                let mut out = alloc::vec![crate::ast::AlterTableTarget::AddColumn {
11538                    column,
11539                    if_not_exists,
11540                    position,
11541                }];
11542                if let Some(mut fk) = col_level_fk {
11543                    if fk.columns.is_empty() {
11544                        fk.columns.push(col_name);
11545                    }
11546                    out.push(crate::ast::AlterTableTarget::AddForeignKey(fk));
11547                }
11548                Ok(out)
11549            }
11550            Token::Drop => {
11551                self.advance();
11552                // v7.13.3 — dispatch on the next token. mailrs round-7
11553                // S8 closed DROP COLUMN; round-6 S7 closed
11554                // DROP CONSTRAINT. Both share IF EXISTS / CASCADE /
11555                // RESTRICT modifiers.
11556                //   DROP CONSTRAINT [IF EXISTS] <name> [CASCADE|RESTRICT]
11557                //   DROP [COLUMN] [IF EXISTS] <col> [CASCADE|RESTRICT]
11558                let subject = match self.peek() {
11559                    Token::Ident(s) if s.eq_ignore_ascii_case("constraint") => {
11560                        self.advance();
11561                        "constraint"
11562                    }
11563                    Token::Ident(s) if s.eq_ignore_ascii_case("column") => {
11564                        self.advance();
11565                        "column"
11566                    }
11567                    // v7.39 (round 431) — MySQL `DROP {INDEX|KEY} name`.
11568                    // `INDEX` lexes as the reserved Token::Index, so it is
11569                    // unambiguous. `KEY` is a plain ident, and PG allows a
11570                    // column literally named "key", so only read it as the
11571                    // keyword when a name follows it.
11572                    Token::Index => {
11573                        self.advance();
11574                        "index"
11575                    }
11576                    Token::Ident(s)
11577                        if s.eq_ignore_ascii_case("key")
11578                            && matches!(
11579                                self.tokens.get(self.pos + 1),
11580                                Some(Token::Ident(_) | Token::QuotedIdent(_))
11581                            ) =>
11582                    {
11583                        self.advance();
11584                        "index"
11585                    }
11586                    // PG-canonical bare `DROP <col>` without COLUMN
11587                    // keyword is also valid; treat any other ident
11588                    // as the column name.
11589                    Token::Ident(_) | Token::QuotedIdent(_) => "column",
11590                    other => {
11591                        return Err(self.err(alloc::format!(
11592                            "expected COLUMN / CONSTRAINT after DROP in ALTER TABLE, got {other:?}"
11593                        )));
11594                    }
11595                };
11596                let mut if_exists = false;
11597                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("if")) {
11598                    let n1 = self.tokens.get(self.pos + 1);
11599                    if matches!(n1, Some(Token::Ident(s)) if s.eq_ignore_ascii_case("exists")) {
11600                        self.advance();
11601                        self.advance();
11602                        if_exists = true;
11603                    }
11604                }
11605                let name = self.expect_ident_like()?;
11606                let mut cascade = false;
11607                if matches!(
11608                    self.peek(),
11609                    Token::Ident(s) if s.eq_ignore_ascii_case("cascade")
11610                        || s.eq_ignore_ascii_case("restrict")
11611                ) {
11612                    if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("cascade"))
11613                    {
11614                        cascade = true;
11615                    }
11616                    self.advance();
11617                }
11618                if subject == "index" {
11619                    Ok(alloc::vec![crate::ast::AlterTableTarget::DropIndex {
11620                        name,
11621                        if_exists,
11622                    }])
11623                } else if subject == "constraint" {
11624                    Ok(alloc::vec![crate::ast::AlterTableTarget::DropForeignKey {
11625                        name,
11626                        if_exists,
11627                    }])
11628                } else {
11629                    Ok(alloc::vec![crate::ast::AlterTableTarget::DropColumn {
11630                        column: name,
11631                        if_exists,
11632                        cascade,
11633                    }])
11634                }
11635            }
11636            Token::Ident(s) if s.eq_ignore_ascii_case("alter") => {
11637                self.advance();
11638                // v7.37.18 (18.16) — `ALTER TABLE … ALTER CONSTRAINT
11639                // <name> {DEFERRABLE|NOT DEFERRABLE} [INITIALLY
11640                // {IMMEDIATE|DEFERRED}]`. SPG enforces constraints
11641                // immediately; accept-and-no-op.
11642                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("constraint")) {
11643                    self.advance();
11644                    self.consume_until_statement_boundary();
11645                    return Ok(Vec::new());
11646                }
11647                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("column")) {
11648                    self.advance();
11649                }
11650                let col_name = self.expect_ident_like()?;
11651                match self.peek() {
11652                    Token::Ident(s) if s.eq_ignore_ascii_case("type") => {
11653                        self.advance();
11654                    }
11655                    // v7.14.0 — pg_dump emits BIGSERIAL via
11656                    // `ALTER TABLE … ALTER COLUMN id SET DEFAULT
11657                    // nextval('seq')` (the sequence is created
11658                    // separately). SPG's BIGSERIAL already uses
11659                    // AUTO_INCREMENT; accept SET DEFAULT / DROP
11660                    // DEFAULT / SET NOT NULL / DROP NOT NULL as
11661                    // engine no-ops by consuming the tail.
11662                    Token::Ident(s) if s.eq_ignore_ascii_case("set") => {
11663                        // v7.22 (round-13 T2) — `SET DEFAULT
11664                        // nextval('…')` is how pg_dump spells a
11665                        // SERIAL column (plain integer in CREATE
11666                        // TABLE + this ALTER). It used to be
11667                        // swallowed as a no-op, which silently
11668                        // STRIPPED auto-increment from imported
11669                        // schemas — the first post-import INSERT
11670                        // without an explicit id then violated NOT
11671                        // NULL. Lower it to the auto-increment
11672                        // marker instead.
11673                        let is_default_nextval =
11674                            matches!(self.tokens.get(self.pos + 1), Some(Token::Default))
11675                                && matches!(
11676                                    self.tokens.get(self.pos + 2),
11677                                    Some(Token::Ident(f)) if f.eq_ignore_ascii_case("nextval")
11678                                );
11679                        if is_default_nextval {
11680                            let seq_name = self.scan_sequence_name_until_boundary();
11681                            return Ok(alloc::vec![
11682                                crate::ast::AlterTableTarget::SetColumnAutoIncrement {
11683                                    column: col_name,
11684                                    seq_name,
11685                                }
11686                            ]);
11687                        }
11688                        // v7.37.18 (18.1 + 18.2) — proper lowering.
11689                        self.advance(); // consume "set"
11690                        match self.peek().clone() {
11691                            Token::Default => {
11692                                self.advance();
11693                                let default_expr = self.parse_expr(0)?;
11694                                return Ok(alloc::vec![
11695                                    crate::ast::AlterTableTarget::AlterColumnSetDefault {
11696                                        column: col_name,
11697                                        default_expr,
11698                                    }
11699                                ]);
11700                            }
11701                            Token::Not => {
11702                                self.advance();
11703                                if !matches!(self.peek(), Token::Null) {
11704                                    return Err(self.err(alloc::format!(
11705                                        "expected NULL after ALTER COLUMN SET NOT, got {:?}",
11706                                        self.peek()
11707                                    )));
11708                                }
11709                                self.advance();
11710                                return Ok(alloc::vec![
11711                                    crate::ast::AlterTableTarget::AlterColumnSetNotNull {
11712                                        column: col_name,
11713                                    }
11714                                ]);
11715                            }
11716                            // `SET EXPRESSION AS (expr)` (PG 17) — change a
11717                            // stored generated column's expression and
11718                            // recompute existing rows.
11719                            Token::Ident(s) if s.eq_ignore_ascii_case("expression") => {
11720                                self.advance(); // EXPRESSION
11721                                if matches!(self.peek(), Token::As) {
11722                                    self.advance();
11723                                }
11724                                let expr = self.parse_expr(0)?;
11725                                return Ok(alloc::vec![
11726                                    crate::ast::AlterTableTarget::AlterColumnSetExpression {
11727                                        column: col_name,
11728                                        expr,
11729                                    }
11730                                ]);
11731                            }
11732                            other => {
11733                                // Other SET subjects (STATISTICS,
11734                                // STORAGE, COMPRESSION, …) stay no-ops —
11735                                // storage hints with no SPG semantics.
11736                                let _ = other;
11737                                self.consume_until_statement_boundary();
11738                                return Ok(Vec::new());
11739                            }
11740                        }
11741                    }
11742                    Token::Ident(s) if s.eq_ignore_ascii_case("drop") => {
11743                        self.advance(); // consume "drop"
11744                        return self.parse_alter_column_drop_tail(col_name);
11745                    }
11746                    Token::Drop => {
11747                        self.advance(); // consume Drop token
11748                        return self.parse_alter_column_drop_tail(col_name);
11749                    }
11750                    Token::Ident(s) if s.eq_ignore_ascii_case("add") => {
11751                        // v7.22 (round-13 T2) — `ALTER COLUMN c ADD
11752                        // GENERATED { ALWAYS | BY DEFAULT } AS
11753                        // IDENTITY ( … )`: pg_dump's spelling for
11754                        // identity columns. Same auto-increment
11755                        // lowering as the nextval default; the
11756                        // sequence options inside the parens are
11757                        // no-ops under SPG's max+1 semantics.
11758                        let is_generated = matches!(
11759                            self.tokens.get(self.pos + 1),
11760                            Some(Token::Ident(g)) if g.eq_ignore_ascii_case("generated")
11761                        );
11762                        if !is_generated {
11763                            return Err(self.err(alloc::format!(
11764                                "expected GENERATED after ALTER COLUMN {col_name} ADD, got {:?}",
11765                                self.tokens.get(self.pos + 1)
11766                            )));
11767                        }
11768                        let seq_name = self.scan_sequence_name_until_boundary();
11769                        return Ok(alloc::vec![
11770                            crate::ast::AlterTableTarget::SetColumnAutoIncrement {
11771                                column: col_name,
11772                                seq_name,
11773                            }
11774                        ]);
11775                    }
11776                    // v7.39 (round 220) — `RESTART [WITH n]` on an identity
11777                    // column: floor the next allocated value at n (bare
11778                    // RESTART = restart from the start value, 1).
11779                    Token::Ident(s) if s.eq_ignore_ascii_case("restart") => {
11780                        self.advance();
11781                        let with = if matches!(self.peek(), Token::Ident(w) if w.eq_ignore_ascii_case("with"))
11782                        {
11783                            self.advance();
11784                            let neg = if matches!(self.peek(), Token::Minus) {
11785                                self.advance();
11786                                true
11787                            } else {
11788                                false
11789                            };
11790                            match self.advance() {
11791                                Token::Integer(v) => Some(if neg { -v } else { v }),
11792                                other => {
11793                                    return Err(self.err(alloc::format!(
11794                                        "expected integer after RESTART WITH, got {other:?}"
11795                                    )));
11796                                }
11797                            }
11798                        } else {
11799                            None
11800                        };
11801                        return Ok(alloc::vec![
11802                            crate::ast::AlterTableTarget::AlterColumnRestart {
11803                                column: col_name,
11804                                with,
11805                            }
11806                        ]);
11807                    }
11808                    other => {
11809                        return Err(self.err(alloc::format!(
11810                            "expected TYPE / SET / DROP / ADD after ALTER COLUMN <name>, got {other:?}"
11811                        )));
11812                    }
11813                }
11814                // v7.39 (round 713) — the type parser has consumed a
11815                // trailing `COLLATE <name>` since Phase 2.5, and
11816                // `parse_column_type_name` discarded it: `ALTER COLUMN t
11817                // TYPE text COLLATE "C"` parsed clean and changed
11818                // nothing. Keep the clause; the engine re-collates.
11819                let (new_type, _, _, _, coll, coll_explicit, coll_name, _, _, _, _, _, _, _) =
11820                    self.parse_type_with_implied_flags()?;
11821                let collation = if coll_explicit {
11822                    coll_name.map(|n| (coll, n))
11823                } else {
11824                    None
11825                };
11826                let using = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("using"))
11827                {
11828                    self.advance();
11829                    Some(self.parse_expr(0)?)
11830                } else {
11831                    None
11832                };
11833                Ok(alloc::vec![crate::ast::AlterTableTarget::AlterColumnType {
11834                    column: col_name,
11835                    new_type,
11836                    using,
11837                    collation,
11838                }])
11839            }
11840            // v7.15.0 — `ALTER TABLE t RENAME [COLUMN] old TO new`.
11841            // PG also supports `RENAME TO new_table` for table-name
11842            // rename; that surface is deferred (pg_dump never emits
11843            // it). If the first post-RENAME ident is `TO`, the user
11844            // is asking for table rename — error with a clear
11845            // message rather than misparsing `TO` as a column name.
11846            Token::Ident(s) if s.eq_ignore_ascii_case("rename") => {
11847                self.advance();
11848                // v7.16.2 — `ALTER TABLE t RENAME TO new_table`
11849                // table-name rename (mailrs round-10 A.5 — used
11850                // by migrate-042's `RENAME TO email_contacts`).
11851                // `TO` lexes as Token::To.
11852                if matches!(self.peek(), Token::To)
11853                    || matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("to"))
11854                {
11855                    self.advance();
11856                    let new = self.expect_ident_like()?;
11857                    return Ok(alloc::vec![crate::ast::AlterTableTarget::RenameTable {
11858                        new,
11859                    }]);
11860                }
11861                // v7.39 (read01 round 48) — `RENAME CONSTRAINT old TO new`.
11862                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("constraint")) {
11863                    self.advance();
11864                    let old = self.expect_ident_like()?;
11865                    if matches!(self.peek(), Token::To) {
11866                        self.advance();
11867                    } else {
11868                        self.expect_keyword_ident("to")?;
11869                    }
11870                    let new = self.expect_ident_like()?;
11871                    return Ok(alloc::vec![
11872                        crate::ast::AlterTableTarget::RenameConstraint { old, new }
11873                    ]);
11874                }
11875                // v7.39.9 — MySQL's `RENAME {INDEX|KEY} old TO new`.
11876                // PostgreSQL renames an index with its own top-level
11877                // `ALTER INDEX`, so this spelling had nowhere to go and
11878                // answered 1064; MySQL 9.7.2 parses it and answers 1176
11879                // when the key is not there.
11880                if matches!(self.peek(), Token::Index)
11881                    || matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("key"))
11882                {
11883                    self.advance();
11884                    let old = self.expect_ident_like()?;
11885                    if matches!(self.peek(), Token::To) {
11886                        self.advance();
11887                    } else {
11888                        self.expect_keyword_ident("to")?;
11889                    }
11890                    let new = self.expect_ident_like()?;
11891                    return Ok(alloc::vec![crate::ast::AlterTableTarget::RenameIndex {
11892                        old,
11893                        new,
11894                    }]);
11895                }
11896                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("column")) {
11897                    self.advance();
11898                }
11899                let old = self.expect_ident_like()?;
11900                // `TO` is a reserved keyword token; accept both
11901                // Token::To and Token::Ident("to") for consistency.
11902                if matches!(self.peek(), Token::To) {
11903                    self.advance();
11904                } else {
11905                    self.expect_keyword_ident("to")?;
11906                }
11907                let new = self.expect_ident_like()?;
11908                Ok(alloc::vec![crate::ast::AlterTableTarget::RenameColumn {
11909                    old,
11910                    new,
11911                }])
11912            }
11913            // v7.16.1 — `ALTER TABLE t { ENABLE | DISABLE } TRIGGER
11914            // { ALL | <name> }`. pg_dump --disable-triggers wraps
11915            // every data block with these. Real disable semantics —
11916            // not no-op — because reload correctness assumes the
11917            // triggers don't fire (rows already carry their
11918            // computed values from prod).
11919            Token::Ident(s)
11920                if s.eq_ignore_ascii_case("enable") || s.eq_ignore_ascii_case("disable") =>
11921            {
11922                let enabled = s.eq_ignore_ascii_case("enable");
11923                self.advance();
11924                // PG also accepts ENABLE/DISABLE { REPLICA | ALWAYS }
11925                // TRIGGER … and ENABLE/DISABLE RULE / ROW LEVEL
11926                // SECURITY. v7.16.1 only matches TRIGGER (mailrs's
11927                // pg_dump output) — anything else falls through to
11928                // the catch-all error below.
11929                // v7.22 (round-13 T3) — mysqldump wraps every data
11930                // section in `/*!40000 ALTER TABLE t DISABLE KEYS */`
11931                // + ENABLE KEYS (a MyISAM index-rebuild hint). SPG
11932                // maintains indexes incrementally — engine no-op.
11933                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("keys")) {
11934                    self.advance();
11935                    return Ok(Vec::new());
11936                }
11937                // v7.37.18 (18.12) — ENABLE/DISABLE ALWAYS TRIGGER
11938                // and ENABLE/DISABLE REPLICA TRIGGER. PG uses these
11939                // to gate triggers on session_replication_role; SPG
11940                // has no replica role, so the prefix is consumed and
11941                // treated identically to the plain ENABLE/DISABLE
11942                // TRIGGER form.
11943                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("always"))
11944                    || matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("replica"))
11945                {
11946                    self.advance();
11947                }
11948                if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("trigger")) {
11949                    return Err(self.err(alloc::format!(
11950                        "expected TRIGGER after {}, got {:?}",
11951                        if enabled { "ENABLE" } else { "DISABLE" },
11952                        self.peek()
11953                    )));
11954                }
11955                self.advance();
11956                // `ALL` lexes as Token::All (reserved); also
11957                // accept Token::Ident("all") for symmetry.
11958                // v7.37.18 (18.12) — USER / REPLICA / ALWAYS post-
11959                // TRIGGER selectors. USER (= all user triggers) is
11960                // semantically ALL here; REPLICA / ALWAYS gate on
11961                // session_replication_role which SPG doesn't track.
11962                // All map to TriggerSelector::All.
11963                let which = if matches!(self.peek(), Token::All)
11964                    || matches!(self.peek(), Token::Ident(s)
11965                        if s.eq_ignore_ascii_case("all")
11966                            || s.eq_ignore_ascii_case("user")
11967                            || s.eq_ignore_ascii_case("replica")
11968                            || s.eq_ignore_ascii_case("always"))
11969                {
11970                    self.advance();
11971                    crate::ast::TriggerSelector::All
11972                } else {
11973                    let name = self.expect_ident_like()?;
11974                    crate::ast::TriggerSelector::Named(name)
11975                };
11976                Ok(alloc::vec![crate::ast::AlterTableTarget::SetTriggerEnabled {
11977                    which,
11978                    enabled,
11979                }])
11980            }
11981            // v7.37.16 (16.3) — ATTACH PARTITION child <bounds>
11982            Token::Ident(s) if s.eq_ignore_ascii_case("attach") => {
11983                self.advance();
11984                if !matches!(self.peek(), Token::Partition)
11985                    && !matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
11986                        if s.eq_ignore_ascii_case("partition"))
11987                {
11988                    return Err(self.err(alloc::format!(
11989                        "expected PARTITION after ATTACH, got {:?}",
11990                        self.peek()
11991                    )));
11992                }
11993                self.advance();
11994                let child = self.expect_ident_like()?;
11995                let bounds = self.parse_partition_bounds_tail()?;
11996                Ok(alloc::vec![
11997                    crate::ast::AlterTableTarget::AttachPartition { child, bounds }
11998                ])
11999            }
12000            // v7.37.16 (16.4 + 16.5) — DETACH PARTITION child [CONCURRENTLY] [FINALIZE]
12001            Token::Ident(s) if s.eq_ignore_ascii_case("detach") => {
12002                self.advance();
12003                if !matches!(self.peek(), Token::Partition)
12004                    && !matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
12005                        if s.eq_ignore_ascii_case("partition"))
12006                {
12007                    return Err(self.err(alloc::format!(
12008                        "expected PARTITION after DETACH, got {:?}",
12009                        self.peek()
12010                    )));
12011                }
12012                self.advance();
12013                let child = self.expect_ident_like()?;
12014                let mut concurrently = false;
12015                let mut finalize = false;
12016                loop {
12017                    match self.peek().clone() {
12018                        Token::Ident(s) | Token::QuotedIdent(s)
12019                            if s.eq_ignore_ascii_case("concurrently") =>
12020                        {
12021                            self.advance();
12022                            concurrently = true;
12023                        }
12024                        Token::Ident(s) | Token::QuotedIdent(s)
12025                            if s.eq_ignore_ascii_case("finalize") =>
12026                        {
12027                            self.advance();
12028                            finalize = true;
12029                        }
12030                        _ => break,
12031                    }
12032                }
12033                Ok(alloc::vec![crate::ast::AlterTableTarget::DetachPartition {
12034                    child,
12035                    concurrently,
12036                    finalize,
12037                }])
12038            }
12039            other => Err(self.err(alloc::format!(
12040                "expected SET / ADD / DROP / ALTER / RENAME / ENABLE / DISABLE / ATTACH / DETACH in ALTER TABLE, got {other:?}"
12041            ))),
12042        }
12043    }
12044
12045    /// v7.37.16 (16.3) — parse the `FOR VALUES …` / `DEFAULT`
12046    /// tail used by both CREATE TABLE … PARTITION OF and ALTER
12047    /// TABLE … ATTACH PARTITION. Shares the same grammar as
12048    /// `parse_partition_of_tail`'s bounds branch.
12049    /// v7.37.18 (18.1 + 18.2) — parse the tail of `ALTER COLUMN
12050    /// col DROP …`. Accepts `DROP DEFAULT` and `DROP NOT NULL`,
12051    /// lowering each to the respective AlterTableTarget. Any
12052    /// other DROP subject (IDENTITY, EXPRESSION, etc.) stays a
12053    /// no-op via consume_until_statement_boundary.
12054    fn parse_alter_column_drop_tail(
12055        &mut self,
12056        col_name: String,
12057    ) -> Result<Vec<crate::ast::AlterTableTarget>, ParseError> {
12058        match self.peek().clone() {
12059            Token::Default => {
12060                self.advance();
12061                Ok(alloc::vec![
12062                    crate::ast::AlterTableTarget::AlterColumnDropDefault { column: col_name }
12063                ])
12064            }
12065            Token::Not => {
12066                self.advance();
12067                if !matches!(self.peek(), Token::Null) {
12068                    return Err(self.err(alloc::format!(
12069                        "expected NULL after ALTER COLUMN DROP NOT, got {:?}",
12070                        self.peek()
12071                    )));
12072                }
12073                self.advance();
12074                Ok(alloc::vec![
12075                    crate::ast::AlterTableTarget::AlterColumnDropNotNull { column: col_name }
12076                ])
12077            }
12078            // `DROP EXPRESSION [IF EXISTS]` — de-generate a stored
12079            // generated column into a plain column.
12080            Token::Ident(s) if s.eq_ignore_ascii_case("expression") => {
12081                self.advance();
12082                // v7.39 (round 187, U10) — IF EXISTS was consumed but
12083                // dropped, so the engine still errored on a plain
12084                // column; PG's semantics are NOTICE + skip.
12085                let mut if_exists = false;
12086                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("if")) {
12087                    self.advance();
12088                    if matches!(self.peek(), Token::Ident(e) if e.eq_ignore_ascii_case("exists")) {
12089                        self.advance();
12090                        if_exists = true;
12091                    }
12092                }
12093                Ok(alloc::vec![
12094                    crate::ast::AlterTableTarget::AlterColumnDropExpression {
12095                        column: col_name,
12096                        if_exists,
12097                    }
12098                ])
12099            }
12100            // v7.38 (read01, T28) — `DROP IDENTITY [IF EXISTS]` — de-generate an
12101            // identity column into a plain column.
12102            Token::Ident(s) if s.eq_ignore_ascii_case("identity") => {
12103                self.advance();
12104                let mut if_exists = false;
12105                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("if")) {
12106                    self.advance();
12107                    if matches!(self.peek(), Token::Ident(e) if e.eq_ignore_ascii_case("exists")) {
12108                        self.advance();
12109                        if_exists = true;
12110                    }
12111                }
12112                Ok(alloc::vec![
12113                    crate::ast::AlterTableTarget::AlterColumnDropIdentity {
12114                        column: col_name,
12115                        if_exists,
12116                    }
12117                ])
12118            }
12119            _ => {
12120                self.consume_until_statement_boundary();
12121                Ok(Vec::new())
12122            }
12123        }
12124    }
12125
12126    /// Parse the optional trailer of `COPY … TO STDOUT`: nothing (text
12127    /// format, no header), the modern `[WITH] ( opt [, opt]* )` list, or
12128    /// the legacy space-separated `[WITH] CSV|TEXT [HEADER] [DELIMITER
12129    /// 'c'] [NULL 'str'] [QUOTE 'c']` spelling.
12130    fn parse_copy_to_options(&mut self) -> Result<crate::ast::CopyOptions, ParseError> {
12131        let mut opts = crate::ast::CopyOptions::default();
12132        if matches!(self.peek(), Token::Eof | Token::Semicolon) {
12133            return Ok(opts);
12134        }
12135        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("with")) {
12136            self.advance();
12137        }
12138        if matches!(self.peek(), Token::LParen) {
12139            self.advance();
12140            loop {
12141                self.parse_one_copy_option(&mut opts)?;
12142                match self.peek() {
12143                    Token::Comma => {
12144                        self.advance();
12145                    }
12146                    Token::RParen => {
12147                        self.advance();
12148                        break;
12149                    }
12150                    other => {
12151                        return Err(self.err(alloc::format!(
12152                            "expected ',' or ')' in COPY options, got {other:?}"
12153                        )));
12154                    }
12155                }
12156            }
12157        } else {
12158            while !matches!(self.peek(), Token::Eof | Token::Semicolon) {
12159                self.parse_one_copy_option(&mut opts)?;
12160            }
12161        }
12162        if !matches!(self.peek(), Token::Eof | Token::Semicolon) {
12163            return Err(self.err(alloc::format!(
12164                "unexpected token after COPY options: {:?}",
12165                self.peek()
12166            )));
12167        }
12168        Ok(opts)
12169    }
12170
12171    fn parse_one_copy_option(
12172        &mut self,
12173        opts: &mut crate::ast::CopyOptions,
12174    ) -> Result<(), ParseError> {
12175        use crate::ast::CopyFormat;
12176        // The option keyword. NULL lexes as its own token; the rest are
12177        // bare identifiers.
12178        let kw = match self.advance() {
12179            Token::Null => alloc::string::String::from("NULL"),
12180            Token::Ident(s) => s.to_uppercase(),
12181            other => {
12182                return Err(self.err(alloc::format!(
12183                    "expected a COPY option keyword, got {other:?}"
12184                )));
12185            }
12186        };
12187        match kw.as_str() {
12188            "FORMAT" => {
12189                let fmt = self.expect_ident_like()?;
12190                match fmt.to_ascii_uppercase().as_str() {
12191                    "CSV" => opts.format = CopyFormat::Csv,
12192                    "TEXT" => opts.format = CopyFormat::Text,
12193                    other => {
12194                        return Err(self.err(alloc::format!(
12195                            "COPY format \"{}\" not recognized",
12196                            other.to_ascii_lowercase()
12197                        )));
12198                    }
12199                }
12200            }
12201            // Legacy bare format keywords.
12202            "CSV" => opts.format = CopyFormat::Csv,
12203            "TEXT" => opts.format = CopyFormat::Text,
12204            "HEADER" => {
12205                opts.header = match self.peek() {
12206                    Token::True => {
12207                        self.advance();
12208                        true
12209                    }
12210                    Token::False => {
12211                        self.advance();
12212                        false
12213                    }
12214                    Token::Ident(s) if s.eq_ignore_ascii_case("on") => {
12215                        self.advance();
12216                        true
12217                    }
12218                    Token::Ident(s) if s.eq_ignore_ascii_case("off") => {
12219                        self.advance();
12220                        false
12221                    }
12222                    // Bare HEADER (no boolean) means HEADER true.
12223                    _ => true,
12224                };
12225            }
12226            // r1066 (7.38 S5.1) — pgbench 14+ loads with
12227            // `COPY … WITH (FREEZE ON)`. The hint's PG effect is
12228            // vacuum bookkeeping on a freshly created/truncated
12229            // table; SPG's per-statement visibility makes it a
12230            // faithful no-op, and rejecting it aborted `pgbench -i`
12231            // against the drop-in. Accept ON/OFF/bare, change nothing.
12232            "FREEZE" => match self.peek() {
12233                Token::True | Token::False => {
12234                    self.advance();
12235                }
12236                Token::Ident(s)
12237                    if s.eq_ignore_ascii_case("on") || s.eq_ignore_ascii_case("off") =>
12238                {
12239                    self.advance();
12240                }
12241                _ => {}
12242            },
12243            "DELIMITER" | "QUOTE" | "ESCAPE" => {
12244                let s = match self.advance() {
12245                    Token::String(s) => s,
12246                    other => {
12247                        return Err(self.err(alloc::format!(
12248                            "COPY {kw} expects a single-character string, got {other:?}"
12249                        )));
12250                    }
12251                };
12252                // v7.39 (round 247) — PG's wording (0A000), keyword in
12253                // lowercase: "COPY delimiter must be a single one-byte
12254                // character".
12255                let one_byte_err = || {
12256                    self.err(alloc::format!(
12257                        "COPY {} must be a single one-byte character",
12258                        kw.to_ascii_lowercase()
12259                    ))
12260                };
12261                let mut chars = s.chars();
12262                let c = chars.next().ok_or_else(one_byte_err)?;
12263                if chars.next().is_some() || c.len_utf8() != 1 {
12264                    return Err(one_byte_err());
12265                }
12266                match kw.as_str() {
12267                    "DELIMITER" => opts.delimiter = Some(c),
12268                    "QUOTE" => opts.quote = Some(c),
12269                    _ => opts.escape = Some(c),
12270                }
12271            }
12272            // v7.39 (round 247) — `FORCE_QUOTE (col, …)` / `FORCE_QUOTE *`.
12273            "FORCE_QUOTE" => {
12274                if matches!(self.peek(), Token::Star) {
12275                    self.advance();
12276                    opts.force_quote = Some(Vec::new());
12277                } else {
12278                    if !matches!(self.peek(), Token::LParen) {
12279                        return Err(self.err(alloc::format!(
12280                            "expected '(' or '*' after FORCE_QUOTE, got {:?}",
12281                            self.peek()
12282                        )));
12283                    }
12284                    self.advance();
12285                    let mut cols = Vec::new();
12286                    loop {
12287                        cols.push(self.expect_ident_like()?);
12288                        match self.peek() {
12289                            Token::Comma => {
12290                                self.advance();
12291                            }
12292                            Token::RParen => {
12293                                self.advance();
12294                                break;
12295                            }
12296                            other => {
12297                                return Err(self.err(alloc::format!(
12298                                    "expected ',' or ')' in FORCE_QUOTE list, got {other:?}"
12299                                )));
12300                            }
12301                        }
12302                    }
12303                    opts.force_quote = Some(cols);
12304                }
12305            }
12306            "NULL" => {
12307                opts.null_str = Some(match self.advance() {
12308                    Token::String(s) => s,
12309                    other => {
12310                        return Err(self.err(alloc::format!(
12311                            "COPY NULL expects a quoted string, got {other:?}"
12312                        )));
12313                    }
12314                });
12315            }
12316            // v7.39 (round 265) — the two CSV FROM-side column lists. Same
12317            // grammar as FORCE_QUOTE; PG accepts `*` for FORCE_NOT_NULL /
12318            // FORCE_NULL too.
12319            "FORCE_NOT_NULL" | "FORCE_NULL" => {
12320                let cols = self.parse_copy_column_list(&kw)?;
12321                if kw == "FORCE_NOT_NULL" {
12322                    opts.force_not_null = Some(cols);
12323                } else {
12324                    opts.force_null = Some(cols);
12325                }
12326            }
12327            other => {
12328                // PG's wording, lowercased option name.
12329                return Err(self.err(alloc::format!(
12330                    "option \"{}\" not recognized",
12331                    other.to_ascii_lowercase()
12332                )));
12333            }
12334        }
12335        Ok(())
12336    }
12337
12338    /// v7.39 (round 265) — `( col, … )` or `*` after a COPY column-list
12339    /// option (FORCE_QUOTE / FORCE_NOT_NULL / FORCE_NULL). An empty vec
12340    /// is the `*` spelling.
12341    fn parse_copy_column_list(&mut self, kw: &str) -> Result<Vec<String>, ParseError> {
12342        if matches!(self.peek(), Token::Star) {
12343            self.advance();
12344            return Ok(Vec::new());
12345        }
12346        if !matches!(self.peek(), Token::LParen) {
12347            return Err(self.err(alloc::format!(
12348                "expected '(' or '*' after {kw}, got {:?}",
12349                self.peek()
12350            )));
12351        }
12352        self.advance();
12353        let mut cols = Vec::new();
12354        loop {
12355            cols.push(self.expect_ident_like()?);
12356            match self.peek() {
12357                Token::Comma => {
12358                    self.advance();
12359                }
12360                Token::RParen => {
12361                    self.advance();
12362                    break;
12363                }
12364                other => {
12365                    return Err(self.err(alloc::format!(
12366                        "expected ',' or ')' in {kw} list, got {other:?}"
12367                    )));
12368                }
12369            }
12370        }
12371        Ok(cols)
12372    }
12373
12374    fn parse_partition_bounds_tail(
12375        &mut self,
12376    ) -> Result<crate::ast::PartitionOfBoundsAst, ParseError> {
12377        use crate::ast::PartitionOfBoundsAst;
12378        match self.peek() {
12379            Token::Default => {
12380                self.advance();
12381                Ok(PartitionOfBoundsAst::Default)
12382            }
12383            Token::For => {
12384                self.advance();
12385                if !matches!(self.peek(), Token::Values) {
12386                    return Err(
12387                        self.err(format!("expected VALUES after FOR, got {:?}", self.peek()))
12388                    );
12389                }
12390                self.advance();
12391                let want_with = matches!(
12392                    self.peek(),
12393                    Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("with")
12394                );
12395                if want_with {
12396                    self.advance();
12397                    if !matches!(self.peek(), Token::LParen) {
12398                        return Err(self.err(format!(
12399                            "expected '(' after FOR VALUES WITH, got {:?}",
12400                            self.peek()
12401                        )));
12402                    }
12403                    self.advance();
12404                    let (mut modulus, mut remainder): (Option<u32>, Option<u32>) = (None, None);
12405                    loop {
12406                        let key = self.expect_ident_like()?;
12407                        let n = match self.peek().clone() {
12408                            Token::Integer(v) if u32::try_from(v).is_ok() => {
12409                                self.advance();
12410                                v as u32
12411                            }
12412                            other => {
12413                                return Err(self.err(format!(
12414                                    "FOR VALUES WITH: expected unsigned integer literal, got {other:?}"
12415                                )));
12416                            }
12417                        };
12418                        match key.to_ascii_uppercase().as_str() {
12419                            "MODULUS" => modulus = Some(n),
12420                            "REMAINDER" => remainder = Some(n),
12421                            other => {
12422                                return Err(self.err(format!(
12423                                    "FOR VALUES WITH: unknown key {other:?}; \
12424                                     expected MODULUS or REMAINDER"
12425                                )));
12426                            }
12427                        }
12428                        match self.peek() {
12429                            Token::Comma => {
12430                                self.advance();
12431                            }
12432                            Token::RParen => {
12433                                self.advance();
12434                                break;
12435                            }
12436                            other => {
12437                                return Err(self.err(format!(
12438                                    "expected ',' or ')' in FOR VALUES WITH list, got {other:?}"
12439                                )));
12440                            }
12441                        }
12442                    }
12443                    let modulus = modulus
12444                        .ok_or_else(|| self.err("FOR VALUES WITH: missing MODULUS".to_string()))?;
12445                    let remainder = remainder.ok_or_else(|| {
12446                        self.err("FOR VALUES WITH: missing REMAINDER".to_string())
12447                    })?;
12448                    if modulus == 0 {
12449                        return Err(self.err("FOR VALUES WITH: MODULUS must be > 0".to_string()));
12450                    }
12451                    if remainder >= modulus {
12452                        return Err(self.err(format!(
12453                            "FOR VALUES WITH: REMAINDER ({remainder}) must be < MODULUS ({modulus})"
12454                        )));
12455                    }
12456                    return Ok(PartitionOfBoundsAst::Hash { modulus, remainder });
12457                }
12458                match self.peek() {
12459                    Token::From => {
12460                        self.advance();
12461                        let lower = Box::new(self.parse_partition_bound_expr()?);
12462                        if !matches!(self.peek(), Token::To) {
12463                            return Err(self.err(format!(
12464                                "expected TO after FROM (...), got {:?}",
12465                                self.peek()
12466                            )));
12467                        }
12468                        self.advance();
12469                        let upper = Box::new(self.parse_partition_bound_expr()?);
12470                        Ok(PartitionOfBoundsAst::Range { lower, upper })
12471                    }
12472                    Token::In => {
12473                        self.advance();
12474                        if !matches!(self.peek(), Token::LParen) {
12475                            return Err(self.err(format!(
12476                                "expected '(' after FOR VALUES IN, got {:?}",
12477                                self.peek()
12478                            )));
12479                        }
12480                        self.advance();
12481                        let mut values = Vec::new();
12482                        loop {
12483                            values.push(self.parse_expr(0)?);
12484                            match self.peek() {
12485                                Token::Comma => {
12486                                    self.advance();
12487                                }
12488                                Token::RParen => {
12489                                    self.advance();
12490                                    break;
12491                                }
12492                                other => {
12493                                    return Err(self.err(format!(
12494                                        "expected ',' or ')' in FOR VALUES IN list, got {other:?}"
12495                                    )));
12496                                }
12497                            }
12498                        }
12499                        if values.is_empty() {
12500                            return Err(
12501                                self.err("FOR VALUES IN requires at least one literal".to_string())
12502                            );
12503                        }
12504                        Ok(PartitionOfBoundsAst::List { values })
12505                    }
12506                    other => Err(self.err(format!(
12507                        "expected FROM / IN / WITH after FOR VALUES, got {other:?}"
12508                    ))),
12509                }
12510            }
12511            other => Err(self.err(format!(
12512                "expected DEFAULT or FOR VALUES after ATTACH PARTITION child, got {other:?}"
12513            ))),
12514        }
12515    }
12516
12517    /// v7.16.2 — peek for `information_schema.<tbl>` /
12518    /// `pg_catalog.<tbl>` triples and, if matched, consume all
12519    /// three tokens + return a synthetic table name the engine's
12520    /// SELECT path recognises as a virtual view. Returns `None`
12521    /// when the head doesn't look like a meta-qualified name.
12522    /// Used by `parse_table_ref` to bypass the
12523    /// `expect_ident_like` schema-strip for these specific PG
12524    /// meta schemas (mailrs round-10 A.3).
12525    fn try_peek_meta_qualified(&mut self) -> Option<(String, String)> {
12526        // Extract the schema name. Must be a plain ident token.
12527        let schema = match self.tokens.get(self.pos) {
12528            Some(Token::Ident(s) | Token::QuotedIdent(s)) => s.clone(),
12529            _ => return None,
12530        };
12531        // Dot.
12532        if !matches!(self.tokens.get(self.pos + 1), Some(Token::Dot)) {
12533            return None;
12534        }
12535        // The table-side ident may lex as a reserved keyword
12536        // (e.g. `Token::Tables`). Tolerate the common ones via a
12537        // helper that reads the trailing token's underlying name.
12538        let tbl = match self.tokens.get(self.pos + 2)? {
12539            Token::Ident(t) | Token::QuotedIdent(t) => t.clone(),
12540            Token::Tables => "tables".to_string(),
12541            // Other PG meta table names that may collide with
12542            // reserved keywords land here as needed.
12543            _ => return None,
12544        };
12545        // Strip the `pg_` prefix from `pg_catalog.pg_class`-style
12546        // names so the synthetic name doesn't double-prefix
12547        // (`__spg_pg_class`, not `__spg_pg_pg_class`).
12548        let (prefix, normalised) = if schema.eq_ignore_ascii_case("information_schema") {
12549            ("__spg_info_", tbl.to_ascii_lowercase())
12550        } else if schema.eq_ignore_ascii_case("pg_catalog") {
12551            // v7.39 (round 541) — only the catalogs SPG actually
12552            // synthesises are rewritten, which is what the BARE path
12553            // has always checked. Anything else keeps its own name and
12554            // takes the ordinary route: `pg_stat_activity` and friends
12555            // resolve through meta_view_result, and a name that is no
12556            // catalog at all gets PG's "relation does not exist"
12557            // instead of a message about a view SPG cannot materialise.
12558            let lowered = tbl.to_ascii_lowercase();
12559            if !SYNTHESISED_PG_CATALOGS.contains(&lowered.as_str()) {
12560                self.advance(); // schema
12561                self.advance(); // dot
12562                self.advance(); // tbl
12563                return Some((lowered.clone(), lowered));
12564            }
12565            let bare = lowered
12566                .strip_prefix("pg_")
12567                .map(alloc::string::String::from)
12568                .unwrap_or(lowered);
12569            ("__spg_pg_", bare)
12570        } else if schema.eq_ignore_ascii_case("mysql") {
12571            // v7.17.0 Phase 3.P0-65 — MySQL system schema
12572            // (`mysql.user`, `mysql.db`). Same synthetic-name
12573            // shape as pg_catalog.
12574            ("__spg_mysql_", tbl.to_ascii_lowercase())
12575        } else {
12576            return None;
12577        };
12578        self.advance(); // schema
12579        self.advance(); // dot
12580        self.advance(); // tbl
12581        Some((
12582            alloc::format!("{prefix}{normalised}"),
12583            tbl.to_ascii_lowercase(),
12584        ))
12585    }
12586
12587    /// Unqualified PG meta-table names (`FROM pg_extension`, `FROM
12588    /// pg_class`) resolve the same way: PG puts `pg_catalog` at the
12589    /// implicit front of every search_path, so a bare reference to a
12590    /// known catalog table always means the catalog table. Only the
12591    /// names the engine actually synthesises are recognised — any
12592    /// other `pg_*` ident stays a user table (mailrs embed round-12).
12593    fn try_peek_meta_bare(&mut self) -> Option<(String, String)> {
12594        // v7.38 (read01 P3.21) — every catalog view SPG synthesises
12595        // (`__spg_pg_*`) is bare-resolvable, matching PG's implicit
12596        // `pg_catalog` at the front of every search_path. (pg_stat_activity
12597        // / pg_stat_statements / pg_locks / pg_statio_user_tables route
12598        // through the meta_view_result path instead, and already resolve
12599        // bare — they must NOT be listed here or the __spg_ rewrite would
12600        // mis-target them.)
12601        const PG_META_TABLES: &[&str] = SYNTHESISED_PG_CATALOGS;
12602        let name = match self.tokens.get(self.pos) {
12603            Some(Token::Ident(s)) => s.to_ascii_lowercase(),
12604            _ => return None,
12605        };
12606        // A following dot means this ident is a schema qualifier,
12607        // not a table name — let the qualified path handle it.
12608        if matches!(self.tokens.get(self.pos + 1), Some(Token::Dot)) {
12609            return None;
12610        }
12611        if !PG_META_TABLES.contains(&name.as_str()) {
12612            return None;
12613        }
12614        self.advance();
12615        let bare = name.strip_prefix("pg_").unwrap_or(&name);
12616        Some((alloc::format!("__spg_pg_{bare}"), name.clone()))
12617    }
12618
12619    /// Consume a bare ident if its lowercase matches `kw`, else err.
12620    /// v7.39 (read01 round 57) — is the next token this bare keyword-ident?
12621    /// Peeks only; the caller advances.
12622    fn peek_keyword_ident(&self, kw: &str) -> bool {
12623        matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case(kw))
12624    }
12625
12626    fn expect_keyword_ident(&mut self, kw: &str) -> Result<(), ParseError> {
12627        match self.advance() {
12628            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case(kw) => Ok(()),
12629            other => Err(ParseError {
12630                message: format!("expected {kw:?}, got {other:?}"),
12631                token_pos: self.consumed_pos(),
12632            }),
12633        }
12634    }
12635
12636    /// Accept either a quoted identifier (`"foo"`) or a quoted string
12637    /// literal (`'foo'`) — same shape used by CREATE USER for the
12638    /// username slot.
12639    fn expect_ident_or_string(&mut self) -> Result<String, ParseError> {
12640        match self.advance() {
12641            Token::Ident(s) | Token::QuotedIdent(s) | Token::String(s) => Ok(s),
12642            other => Err(ParseError {
12643                message: format!("expected identifier or string, got {other:?}"),
12644                token_pos: self.consumed_pos(),
12645            }),
12646        }
12647    }
12648
12649    fn expect_string_literal(&mut self) -> Result<String, ParseError> {
12650        match self.advance() {
12651            Token::String(s) => Ok(s),
12652            other => Err(ParseError {
12653                message: format!("expected quoted string, got {other:?}"),
12654                token_pos: self.consumed_pos(),
12655            }),
12656        }
12657    }
12658
12659    fn parse_select_stmt(&mut self) -> Result<Statement, ParseError> {
12660        // v7.30.2 (mailrs round-25 ask 2) — derived tables /
12661        // subqueries recurse through here without passing
12662        // parse_expr; share the same nesting budget.
12663        self.enter_nested()?;
12664        let r = self.parse_select_stmt_inner();
12665        self.nest_depth -= 1;
12666        r
12667    }
12668
12669    fn parse_select_stmt_inner(&mut self) -> Result<Statement, ParseError> {
12670        // Caller dispatches on Token::Select; the inner helper handles
12671        // the rest. ORDER BY / LIMIT bind at this top level; UNION peers
12672        // get a fresh bare-select parse and may not have their own ORDER
12673        // BY / LIMIT.
12674        let mut head = self.parse_bare_select()?;
12675        let into = self.pending_select_into.take();
12676        self.parse_setop_chain_into(&mut head)?;
12677        self.parse_select_tail_into(&mut head)?;
12678        // v7.38.19 — `SELECT … INTO t` lowers to the SAME node as
12679        // `CREATE TABLE t AS SELECT …`, which is what a comment in
12680        // `ast.rs` has claimed since v7.38 and what only CTAS actually
12681        // did. The tail (ORDER BY / LIMIT) is parsed first so it belongs
12682        // to the body, as it does in PostgreSQL.
12683        if let Some((name, temporary)) = into {
12684            return Ok(Statement::CreateMaterializedView(
12685                crate::ast::CreateMaterializedViewStatement {
12686                    temporary,
12687                    name,
12688                    if_not_exists: false,
12689                    columns: Vec::new(),
12690                    body: head,
12691                    with_data: true,
12692                    as_plain_table: true,
12693                },
12694            ));
12695        }
12696        Ok(Statement::Select(head))
12697    }
12698
12699    /// v7.37.17 (17.6 siblings) — the three SQL set operations
12700    /// share the peer chain: UNION [ALL], EXCEPT [ALL] (a reserved
12701    /// token), and INTERSECT [ALL] (a bare ident — it was never
12702    /// reserved in SPG's lexer). PG precedence: INTERSECT binds
12703    /// tighter than UNION / EXCEPT — the executor folds the chain
12704    /// left-to-right, which is already correct for LEADING
12705    /// intersects; an INTERSECT pair that FOLLOWS a union/except
12706    /// pair nests into that previous peer, so A UNION B INTERSECT C
12707    /// = A ∪ (B ∩ C). Shared by the top level and parenthesized
12708    /// groups.
12709    fn parse_setop_chain_into(&mut self, head: &mut SelectStatement) -> Result<(), ParseError> {
12710        // A parenthesized group arrives with its own (already
12711        // regrouped) unions on `head`; only the pairs THIS chain
12712        // appends participate in the precedence regroup below —
12713        // nesting an outer INTERSECT into a group-internal peer
12714        // would dissolve the explicit grouping.
12715        let boundary = head.unions.len();
12716        loop {
12717            let base = match self.peek() {
12718                Token::Union => UnionKind::Distinct,
12719                Token::Except => UnionKind::Except,
12720                Token::Ident(s) if s.eq_ignore_ascii_case("intersect") => UnionKind::Intersect,
12721                _ => break,
12722            };
12723            self.advance();
12724            let kind = if matches!(self.peek(), Token::All) {
12725                self.advance();
12726                match base {
12727                    UnionKind::Distinct => UnionKind::All,
12728                    UnionKind::Except => UnionKind::ExceptAll,
12729                    _ => UnionKind::IntersectAll,
12730                }
12731            } else {
12732                base
12733            };
12734            let peer = self.parse_bare_select()?;
12735            head.unions.push((kind, peer));
12736        }
12737        let mut pairs = core::mem::take(&mut head.unions);
12738        let tail = pairs.split_off(boundary);
12739        let mut regrouped: Vec<(UnionKind, SelectStatement)> = pairs;
12740        for (kind, peer) in tail {
12741            let is_intersect = matches!(kind, UnionKind::Intersect | UnionKind::IntersectAll);
12742            // An intersect nests into the previous element of THIS
12743            // chain only; with no new previous element it stays at
12744            // the outer level (the left fold applies it to the
12745            // whole head, group included).
12746            match (
12747                is_intersect,
12748                regrouped.len() > boundary,
12749                regrouped.last_mut(),
12750            ) {
12751                (true, true, Some((_, prev))) => prev.unions.push((kind, peer)),
12752                _ => regrouped.push((kind, peer)),
12753            }
12754        }
12755        head.unions = regrouped;
12756        Ok(())
12757    }
12758
12759    /// v7.37.17 (17.6 siblings) — the shared SELECT tail: ORDER BY /
12760    /// LIMIT / OFFSET / FETCH FIRST / FOR-lock clauses. Extracted so
12761    /// the top-level bare VALUES statement reuses it verbatim.
12762    /// v6.4.0 — parse an optional `ORDER BY <expr> [ASC|DESC] [NULLS …], …`
12763    /// clause into its key list (empty when no `ORDER BY` follows). Extracted
12764    /// (v7.39 round 135) so the grouping-set path can parse ORDER BY early,
12765    /// where the grouping-set universe is still in scope.
12766    fn parse_order_by_keys(&mut self) -> Result<Vec<OrderBy>, ParseError> {
12767        if !matches!(self.peek(), Token::Order) {
12768            return Ok(Vec::new());
12769        }
12770        self.advance();
12771        if !self.peek_is_by() {
12772            return Err(self.err(format!("expected BY after ORDER, got {:?}", self.peek())));
12773        }
12774        self.advance();
12775        let mut keys = Vec::new();
12776        loop {
12777            // v7.39 (round 691) — save/restore, the discipline this parser
12778            // already uses around `pending_sample_preds`, so a subquery inside
12779            // a key neither inherits nor leaks the channel.
12780            let saved_flag = core::mem::replace(&mut self.in_order_by_key, true);
12781            let saved_coll = self.order_key_collation.take();
12782            let parsed = self.parse_expr(0);
12783            self.in_order_by_key = saved_flag;
12784            let collation = core::mem::replace(&mut self.order_key_collation, saved_coll);
12785            let expr = parsed?;
12786            let desc = if matches!(self.peek(), Token::Desc) {
12787                self.advance();
12788                true
12789            } else if matches!(self.peek(), Token::Asc) {
12790                self.advance();
12791                false
12792            } else if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("using")) {
12793                // `ORDER BY x USING <op>` — PG's operator-class spelling. SPG has
12794                // one ordering per type, so the btree comparison operators map
12795                // onto it: < / <= are ASC, > / >= are DESC. Any other operator
12796                // would need a custom operator class — honest error.
12797                self.advance();
12798                match self.advance() {
12799                    Token::Lt | Token::LtEq => false,
12800                    Token::Gt | Token::GtEq => true,
12801                    other => {
12802                        return Err(self.err(alloc::format!(
12803                            "ORDER BY USING supports the btree comparison \
12804                             operators (< <= > >=); got {other:?}"
12805                        )));
12806                    }
12807                }
12808            } else {
12809                false
12810            };
12811            // v7.24 (round-16 A) — explicit NULLS FIRST/LAST.
12812            let nulls_first = self.parse_optional_nulls_placement()?;
12813            keys.push(OrderBy {
12814                expr,
12815                desc,
12816                nulls_first,
12817                collation,
12818            });
12819            if matches!(self.peek(), Token::Comma) {
12820                self.advance();
12821            } else {
12822                break;
12823            }
12824        }
12825        Ok(keys)
12826    }
12827
12828    fn parse_select_tail_into(&mut self, head: &mut SelectStatement) -> Result<(), ParseError> {
12829        // v7.39 (round 135) — a grouping-set query may have already parsed +
12830        // rewritten its ORDER BY (to reference synthetic grouping columns); if
12831        // no ORDER BY token is present, keep that pre-set order_by rather than
12832        // clobbering it with an empty list.
12833        let parsed_keys = self.parse_order_by_keys()?;
12834        head.order_by = if parsed_keys.is_empty() {
12835            core::mem::take(&mut head.order_by)
12836        } else {
12837            parsed_keys
12838        };
12839        // v7.39 (round 314, V39) — the row-count clauses come in EITHER
12840        // order. PG's grammar takes a limit clause and an offset clause
12841        // as an unordered pair, so `OFFSET 2 LIMIT 3` means exactly what
12842        // `LIMIT 3 OFFSET 2` does (measured: same rows). This used to
12843        // parse them in a fixed LIMIT-then-OFFSET sequence, so the other
12844        // spelling died on `expected end of input, got Limit`.
12845        //
12846        // Each may appear at most once, and LIMIT and FETCH FIRST are
12847        // two spellings of the same clause — PG rejects `LIMIT 1 LIMIT 2`,
12848        // `OFFSET 1 OFFSET 2` and `LIMIT 2 FETCH FIRST 3 ROWS ONLY` alike.
12849        // A second one is left unconsumed here, which the caller reports
12850        // as trailing input rather than silently taking the last.
12851        let mut saw_limit = false;
12852        let mut saw_offset = false;
12853        loop {
12854            if !saw_limit && matches!(self.peek(), Token::Limit) {
12855                self.advance();
12856                // v7.17.0 Phase 5.1 — `LIMIT NULL` / `LIMIT ALL` are
12857                // PG synonyms for "no limit". Treat both as None
12858                // (no head.limit set) so the engine's existing
12859                // unlimited-result path takes over. Reject was the
12860                // pre-5.1 behaviour and broke pg_dump-flavoured
12861                // tooling that occasionally emits LIMIT NULL.
12862                if self.consume_limit_unbounded_sentinel() {
12863                    head.limit = None;
12864                } else {
12865                    let first = self.parse_limit_expr("LIMIT")?;
12866                    // MySQL `LIMIT offset, count` — the first number is
12867                    // the offset when a comma follows.
12868                    if matches!(self.peek(), Token::Comma) {
12869                        self.advance();
12870                        let count = self.parse_limit_expr("LIMIT")?;
12871                        head.offset = Some(first);
12872                        saw_offset = true;
12873                        head.limit = Some(count);
12874                    } else {
12875                        head.limit = Some(first);
12876                    }
12877                }
12878                saw_limit = true;
12879                continue;
12880            }
12881            if !saw_offset && matches!(self.peek(), Token::Offset) {
12882                self.advance();
12883                // PG also accepts an optional `ROW` / `ROWS` trailer
12884                // after the offset value (`OFFSET 10 ROWS`). The
12885                // FETCH-FIRST branch below relies on the same.
12886                let off = self.parse_limit_expr("OFFSET")?;
12887                self.consume_optional_rows_keyword();
12888                head.offset = Some(off);
12889                saw_offset = true;
12890                continue;
12891            }
12892            // v7.17.0 Phase 5.1 — `FETCH FIRST <int|$N> ROWS ONLY` is
12893            // the SQL-standard alias for LIMIT. PG accepts both
12894            // spellings interchangeably; pg_dump emits FETCH FIRST in
12895            // newer versions. We map it onto `head.limit` so the
12896            // engine path is unified.
12897            if !saw_limit
12898                && matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
12899                    if s.eq_ignore_ascii_case("fetch"))
12900            {
12901                self.advance(); // FETCH
12902                // `FIRST` or `NEXT` (both legal per SQL standard).
12903                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
12904                    if s.eq_ignore_ascii_case("first") || s.eq_ignore_ascii_case("next"))
12905                {
12906                    self.advance();
12907                }
12908                // Count (optional in the bare `FETCH FIRST ROW ONLY` —
12909                // implicit 1 — but we always consume one if present).
12910                let count = if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
12911                    if s.eq_ignore_ascii_case("row") || s.eq_ignore_ascii_case("rows"))
12912                {
12913                    // Bare `FETCH FIRST ROW ONLY` = LIMIT 1.
12914                    crate::ast::LimitExpr::Literal(1)
12915                } else {
12916                    self.parse_limit_expr("FETCH FIRST")?
12917                };
12918                // Eat `ROW` / `ROWS` if not already consumed above.
12919                self.consume_optional_rows_keyword();
12920                // Optional `ONLY` (the spec form) — or the SQL:2008
12921                // `WITH TIES` form. v7.17.0 Phase 3.P0-49: the executor
12922                // now honours WITH TIES by extending past the LIMIT
12923                // truncation point through every row that shares the
12924                // last-kept row's ORDER BY key.
12925                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
12926                    if s.eq_ignore_ascii_case("only"))
12927                {
12928                    self.advance();
12929                } else if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
12930                    if s.eq_ignore_ascii_case("with"))
12931                {
12932                    self.advance(); // WITH
12933                    if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
12934                        if s.eq_ignore_ascii_case("ties"))
12935                    {
12936                        self.advance();
12937                        head.limit_with_ties = true;
12938                    }
12939                }
12940                head.limit = Some(count);
12941                saw_limit = true;
12942                continue;
12943            }
12944            break;
12945        }
12946        // v7.17.0 Phase 3.4 — trailing row-lock clauses:
12947        //   FOR { UPDATE | NO KEY UPDATE | SHARE | KEY SHARE }
12948        //       [ OF table_name [, …] ]
12949        //       [ NOWAIT | SKIP LOCKED ]
12950        // Multiple FOR clauses may stack (PG: `FOR UPDATE OF t1
12951        // FOR SHARE OF t2`). SPG is a single-writer engine — every
12952        // SELECT already returns a consistent snapshot — so these
12953        // are accept-and-discard: the parser absorbs them so
12954        // mailrs / Rails / Django code paths that emit `SELECT
12955        // … FOR UPDATE` for advisory pessimistic locking load
12956        // without a parser error. The on-disk locking model is
12957        // unchanged; callers that rely on FOR UPDATE for read-
12958        // through-write ordering still get the right answer
12959        // because SPG serialises writes anyway.
12960        head.locking = self
12961            .consume_optional_for_lock_clauses()
12962            .map(alloc::boxed::Box::new);
12963        Ok(())
12964    }
12965
12966    /// v7.17.0 Phase 3.4 — eat zero or more `FOR { UPDATE | NO KEY
12967    /// UPDATE | SHARE | KEY SHARE } [ OF tbl[, …] ] [ NOWAIT | SKIP
12968    /// LOCKED ]` trailers. Each clause is fully accepted and
12969    /// discarded — SPG's single-writer model already satisfies the
12970    /// callers' implicit ordering requirement. Stops at the first
12971    /// token that isn't `FOR`.
12972    fn consume_optional_for_lock_clauses(&mut self) -> Option<crate::ast::LockingClause> {
12973        // v7.39 (round 293, E3 Phase 1) — the clause is REPORTED now,
12974        // not discarded. PG keeps the strongest of several clauses; the
12975        // policy of the last one wins, which is what this loop records.
12976        let mut seen: Option<crate::ast::LockingClause> = None;
12977        while matches!(self.peek(), Token::For) {
12978            // v7.37.14 (A2.5-stub) — record that this query asked
12979            // for a row lock the parser is about to silently
12980            // discard. Operators surface the count via
12981            // `spg_sql::silent_for_update_count()` so they can
12982            // gauge how much of the workload depends on advisory
12983            // FOR UPDATE / FOR SHARE / FOR KEY SHARE semantics
12984            // before v7.37.15's per-row tuple locking lands.
12985            crate::record_silent_for_update_clause();
12986            self.advance(); // FOR
12987            // `NO KEY` prefix (PG) — `NO` is reserved-keyword-shaped
12988            // (`Token::Not` isn't it; PG `NO` lexes as Token::Ident).
12989            let mut no_key = false;
12990            let mut key = false;
12991            if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
12992                if s.eq_ignore_ascii_case("no"))
12993            {
12994                self.advance(); // NO
12995                no_key = true;
12996                // The next ident should be KEY but be generous;
12997                // anything followed by UPDATE/SHARE is accepted.
12998                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
12999                    if s.eq_ignore_ascii_case("key"))
13000                {
13001                    self.advance(); // KEY
13002                }
13003            }
13004            // `KEY` prefix (PG `FOR KEY SHARE`).
13005            if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
13006                if s.eq_ignore_ascii_case("key"))
13007            {
13008                self.advance(); // KEY
13009                key = true;
13010            }
13011            // Lock-strength keyword: UPDATE / SHARE. Required, but
13012            // we're lenient — an unexpected token here just bails
13013            // (we already consumed FOR; caller's downstream
13014            // dispatch will error if anything actually depends on
13015            // the trailing tokens).
13016            let is_update = matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
13017                if s.eq_ignore_ascii_case("update"));
13018            if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
13019                if s.eq_ignore_ascii_case("update") || s.eq_ignore_ascii_case("share"))
13020            {
13021                self.advance();
13022                use crate::ast::LockStrength as LS;
13023                let strength = match (is_update, no_key, key) {
13024                    (true, true, _) => LS::NoKeyUpdate,
13025                    (true, _, _) => LS::Update,
13026                    (false, _, true) => LS::KeyShare,
13027                    (false, _, _) => LS::Share,
13028                };
13029                seen = Some(crate::ast::LockingClause {
13030                    strength,
13031                    of_tables: alloc::vec::Vec::new(),
13032                    policy: crate::ast::LockWait::Wait,
13033                });
13034            } else {
13035                // FOR by itself (or `FOR KEY` with nothing after) —
13036                // give up on the lock-clause path. We've already
13037                // advanced past FOR; further attempts to parse
13038                // here would clobber state.
13039                return seen;
13040            }
13041            // Optional `OF tbl[, tbl …]`. mailrs emits this when
13042            // joining and locking only a subset of tables.
13043            if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
13044                if s.eq_ignore_ascii_case("of"))
13045            {
13046                self.advance(); // OF
13047                #[allow(clippy::while_let_loop)]
13048                loop {
13049                    match self.peek() {
13050                        Token::Ident(_) | Token::QuotedIdent(_) => {
13051                            // v7.39 (round 294) — the name is CAPTURED now: PG
13052                            // validates it against the FROM clause, and an
13053                            // uncaptured list silently means "lock everything".
13054                            let mut nm = match self.advance() {
13055                                Token::Ident(n) | Token::QuotedIdent(n) => n,
13056                                _ => alloc::string::String::new(),
13057                            };
13058                            // Optional schema-qualified `schema.table`.
13059                            if matches!(self.peek(), Token::Dot) {
13060                                self.advance();
13061                                if let Token::Ident(n) | Token::QuotedIdent(n) = self.peek().clone()
13062                                {
13063                                    self.advance();
13064                                    nm = n;
13065                                }
13066                            }
13067                            if let Some(c) = seen.as_mut() {
13068                                c.of_tables.push(nm);
13069                            }
13070                        }
13071                        _ => break,
13072                    }
13073                    if matches!(self.peek(), Token::Comma) {
13074                        self.advance();
13075                    } else {
13076                        break;
13077                    }
13078                }
13079            }
13080            // Optional `NOWAIT` | `SKIP LOCKED`.
13081            match self.peek().clone() {
13082                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("nowait") => {
13083                    self.advance();
13084                    if let Some(c) = seen.as_mut() {
13085                        c.policy = crate::ast::LockWait::NoWait;
13086                    }
13087                }
13088                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("skip") => {
13089                    self.advance(); // SKIP
13090                    if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
13091                        if s.eq_ignore_ascii_case("locked"))
13092                    {
13093                        self.advance(); // LOCKED
13094                        if let Some(c) = seen.as_mut() {
13095                            c.policy = crate::ast::LockWait::SkipLocked;
13096                        }
13097                    }
13098                }
13099                _ => {}
13100            }
13101            // Loop: PG allows multiple FOR clauses chained.
13102        }
13103        seen
13104    }
13105
13106    /// v7.9.24 — accept `LIMIT <int>` or `LIMIT $N`. mailrs H2.
13107    /// Bind value gets resolved during prepared-statement Execute;
13108    /// the Pratt expression parser would over-accept here (e.g.
13109    /// `LIMIT 5 + 5`), so we narrowly accept only the two PG forms.
13110    /// v7.17.0 Phase 5.1 — consume the `LIMIT NULL` / `LIMIT ALL`
13111    /// sentinel tokens (PG synonyms for "no limit"). Returns true
13112    /// when one was consumed; caller skips the regular
13113    /// limit-value parse and leaves `head.limit` at None.
13114    fn consume_limit_unbounded_sentinel(&mut self) -> bool {
13115        if matches!(self.peek(), Token::Null) {
13116            self.advance();
13117            return true;
13118        }
13119        if matches!(self.peek(), Token::All) {
13120            self.advance();
13121            return true;
13122        }
13123        false
13124    }
13125
13126    /// v7.17.0 Phase 5.1 — eat an optional trailing `ROW` / `ROWS`
13127    /// keyword after a LIMIT / OFFSET / FETCH FIRST value, the
13128    /// SQL-standard shape. No-op when missing.
13129    fn consume_optional_rows_keyword(&mut self) {
13130        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
13131            if s.eq_ignore_ascii_case("row") || s.eq_ignore_ascii_case("rows"))
13132        {
13133            self.advance();
13134        }
13135    }
13136
13137    /// v7.39 (round 284) — `LIMIT` / `OFFSET` over a general expression.
13138    ///
13139    /// PG's row-count clause takes an `a_expr`, so `LIMIT 1+1` and
13140    /// `OFFSET 2+3` are legal; only `FETCH FIRST` is restricted to a
13141    /// constant, which is why that spelling keeps the token path below.
13142    ///
13143    /// Constants are folded here rather than carried into the tree: the
13144    /// 15+ execution paths that read the row count go through
13145    /// `limit_literal()`, which answers `Option<u32>` — and `None` there
13146    /// means "no limit". A clause the engine could not resolve would
13147    /// therefore return the WHOLE table instead of failing. Folding at
13148    /// parse time keeps that impossible; a non-constant clause is still
13149    /// a clean error (recorded residual — closing it wants a resolution
13150    /// pre-pass on the simple-query path, where `substitute_placeholders`
13151    /// does not run).
13152    fn parse_limit_expr(&mut self, label: &str) -> Result<crate::ast::LimitExpr, ParseError> {
13153        // PG restricts FETCH FIRST to a constant or a PARENTHESISED
13154        // expression: `FETCH FIRST 1+1 ROWS ONLY` is a syntax error, but
13155        // `FETCH FIRST (1+1) ROWS ONLY` and `FETCH FIRST (SELECT 3) ROWS
13156        // ONLY` both work (its grammar takes a c_expr). Both measured
13157        // against PG 18.4 in round 305.
13158        if label == "FETCH FIRST" && !matches!(self.peek(), Token::LParen) {
13159            return self.parse_limit_constant(label);
13160        }
13161        // One pass, no rewind: `advance()` takes each token by
13162        // `mem::replace`, so a consumed token reads back as Eof and this
13163        // parser cannot backtrack. Everything — bare literal included —
13164        // is therefore folded from the parsed expression rather than
13165        // re-read from the token stream.
13166        let start = self.pos;
13167        let e = self.parse_expr(0)?;
13168        if let crate::ast::Expr::Placeholder(n) = e {
13169            return Ok(crate::ast::LimitExpr::Placeholder(n));
13170        }
13171        let neg_label = if label == "OFFSET" { "OFFSET" } else { "LIMIT" };
13172        match fold_limit_constant(&e) {
13173            Some(Ok(v)) if v < 0 => Err(ParseError {
13174                message: alloc::format!("{neg_label} must not be negative"),
13175                token_pos: start,
13176            }),
13177            Some(Ok(v)) => u32::try_from(v)
13178                .map(crate::ast::LimitExpr::Literal)
13179                .map_err(|_| ParseError {
13180                    message: alloc::format!("{label} value too large: {v}"),
13181                    token_pos: start,
13182                }),
13183            Some(Err(message)) => Err(ParseError {
13184                message: message.replace("{L}", neg_label),
13185                token_pos: start,
13186            }),
13187            // v7.39 (round 305, V23) — not foldable at parse time
13188            // (`LIMIT (SELECT 4)`, `LIMIT greatest(2,3)`). Carry the
13189            // expression; the engine evaluates it once before dispatch.
13190            None => Ok(crate::ast::LimitExpr::Expr(alloc::boxed::Box::new(e))),
13191        }
13192    }
13193
13194    fn parse_limit_constant(&mut self, label: &str) -> Result<crate::ast::LimitExpr, ParseError> {
13195        // v7.39 (round 239) — PG's row-count clause takes a bigint with its
13196        // coercion rules, not just an integer token: a NUMERIC rounds half
13197        // away from zero (`LIMIT 2.5` keeps 3 rows), a negative count is
13198        // refused with PG's wording ("LIMIT must not be negative", 2201W /
13199        // 2201X — FETCH FIRST shares LIMIT's), and a string coerces by its
13200        // content, failing as an input-syntax error on the value. General
13201        // expressions (`LIMIT 1+1`) stay unsupported — a recorded residual;
13202        // they need an Expr-carrying LimitExpr variant.
13203        let neg_label = if label == "OFFSET" { "OFFSET" } else { "LIMIT" };
13204        let err_at = |message: alloc::string::String, pos: usize| ParseError {
13205            message,
13206            token_pos: pos,
13207        };
13208        match self.advance() {
13209            Token::Integer(n) if n >= 0 => u32::try_from(n)
13210                .map(crate::ast::LimitExpr::Literal)
13211                .map_err(|_| ParseError {
13212                    message: alloc::format!("{label} value too large: {n}"),
13213                    token_pos: self.consumed_pos(),
13214                }),
13215            Token::Integer(_) => Err(err_at(
13216                alloc::format!("{neg_label} must not be negative"),
13217                self.pos.saturating_sub(1),
13218            )),
13219            Token::Numeric(t) => {
13220                let pos = self.pos.saturating_sub(1);
13221                let v: f64 = t.parse().map_err(|_| {
13222                    err_at(
13223                        alloc::format!("invalid input syntax for type bigint: \"{t}\""),
13224                        pos,
13225                    )
13226                })?;
13227                if v < 0.0 {
13228                    return Err(err_at(
13229                        alloc::format!("{neg_label} must not be negative"),
13230                        pos,
13231                    ));
13232                }
13233                // Round half away from zero — PG's numeric→bigint cast.
13234                // (no_std: no f64::round; v is non-negative, so truncating
13235                // v + 0.5 is the same thing.)
13236                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
13237                let rounded = (v + 0.5) as u64;
13238                u32::try_from(rounded)
13239                    .map(crate::ast::LimitExpr::Literal)
13240                    .map_err(|_| err_at(alloc::format!("{label} value too large: {t}"), pos))
13241            }
13242            Token::Minus => {
13243                let pos = self.pos.saturating_sub(1);
13244                match self.peek() {
13245                    Token::Integer(_) | Token::Numeric(_) => {
13246                        self.advance();
13247                        Err(err_at(
13248                            alloc::format!("{neg_label} must not be negative"),
13249                            pos,
13250                        ))
13251                    }
13252                    other => Err(err_at(
13253                        alloc::format!(
13254                            "expected non-negative integer or $N placeholder after {label}, got {other:?}"
13255                        ),
13256                        pos,
13257                    )),
13258                }
13259            }
13260            Token::String(t) => {
13261                let pos = self.pos.saturating_sub(1);
13262                match t.trim().parse::<i64>() {
13263                    Ok(n) if n < 0 => Err(err_at(
13264                        alloc::format!("{neg_label} must not be negative"),
13265                        pos,
13266                    )),
13267                    Ok(n) => u32::try_from(n)
13268                        .map(crate::ast::LimitExpr::Literal)
13269                        .map_err(|_| err_at(alloc::format!("{label} value too large: {t}"), pos)),
13270                    Err(_) => Err(err_at(
13271                        alloc::format!("invalid input syntax for type bigint: \"{t}\""),
13272                        pos,
13273                    )),
13274                }
13275            }
13276            Token::Placeholder(n) => Ok(crate::ast::LimitExpr::Placeholder(n)),
13277            other => Err(ParseError {
13278                message: alloc::format!(
13279                    "expected non-negative integer or $N placeholder after {label}, got {other:?}"
13280                ),
13281                token_pos: self.consumed_pos(),
13282            }),
13283        }
13284    }
13285
13286    /// Parse one SELECT block without ORDER BY / LIMIT / UNION chaining —
13287    /// just `[DISTINCT] items [FROM] [WHERE] [GROUP BY]`. Returned with
13288    /// `unions` empty and `order_by` / `limit` `None`; the top-level
13289    /// `parse_select_stmt` is responsible for filling those in.
13290    /// v7.37.17 (17.6 siblings) — rewrite every `grouping(keys…)`
13291    /// call in the expression tree to the per-set integer bitmask
13292    /// (PG semantics: one bit per argument, MSB first; 1 = the key
13293    /// is dropped in this grouping set). Runs during the ROLLUP /
13294    /// CUBE / GROUPING SETS expansion, where the set is known.
13295    /// v7.39 (round 135) — collect the distinct `grouping(...)` calls appearing
13296    /// anywhere in `expr` (an ORDER BY key), without recursing into their args.
13297    fn collect_grouping_calls(expr: &Expr, out: &mut Vec<Expr>) {
13298        if let Expr::FunctionCall { name, .. } = expr
13299            && name.eq_ignore_ascii_case("grouping")
13300        {
13301            if !out.iter().any(|e| e == expr) {
13302                out.push(expr.clone());
13303            }
13304            return;
13305        }
13306        match expr {
13307            Expr::Binary { lhs, rhs, .. } => {
13308                Self::collect_grouping_calls(lhs, out);
13309                Self::collect_grouping_calls(rhs, out);
13310            }
13311            Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
13312                Self::collect_grouping_calls(expr, out)
13313            }
13314            Expr::FunctionCall { args, .. } => {
13315                for a in args {
13316                    Self::collect_grouping_calls(a, out);
13317                }
13318            }
13319            Expr::Case {
13320                operand,
13321                branches,
13322                else_branch,
13323            } => {
13324                if let Some(o) = operand {
13325                    Self::collect_grouping_calls(o, out);
13326                }
13327                for (c, v) in branches {
13328                    Self::collect_grouping_calls(c, out);
13329                    Self::collect_grouping_calls(v, out);
13330                }
13331                if let Some(x) = else_branch {
13332                    Self::collect_grouping_calls(x, out);
13333                }
13334            }
13335            _ => {}
13336        }
13337    }
13338
13339    /// v7.39 (round 135) — replace each `grouping(...)` call in `expr` equal to
13340    /// `grp_exprs[k]` with a reference to the synthetic ordering column
13341    /// `__grp_ord_k` (injected per grouping-set branch).
13342    fn rewrite_grouping_to_col(expr: &mut Expr, grp_exprs: &[Expr]) {
13343        if let Expr::FunctionCall { name, .. } = expr
13344            && name.eq_ignore_ascii_case("grouping")
13345        {
13346            if let Some(k) = grp_exprs.iter().position(|e| e == expr) {
13347                *expr = Expr::Column(crate::ast::ColumnName {
13348                    qualifier: None,
13349                    name: alloc::format!("__grp_ord_{k}"),
13350                });
13351            }
13352            return;
13353        }
13354        match expr {
13355            Expr::Binary { lhs, rhs, .. } => {
13356                Self::rewrite_grouping_to_col(lhs, grp_exprs);
13357                Self::rewrite_grouping_to_col(rhs, grp_exprs);
13358            }
13359            Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
13360                Self::rewrite_grouping_to_col(expr, grp_exprs)
13361            }
13362            Expr::FunctionCall { args, .. } => {
13363                for a in args {
13364                    Self::rewrite_grouping_to_col(a, grp_exprs);
13365                }
13366            }
13367            Expr::Case {
13368                operand,
13369                branches,
13370                else_branch,
13371            } => {
13372                if let Some(o) = operand {
13373                    Self::rewrite_grouping_to_col(o, grp_exprs);
13374                }
13375                for (c, v) in branches {
13376                    Self::rewrite_grouping_to_col(c, grp_exprs);
13377                    Self::rewrite_grouping_to_col(v, grp_exprs);
13378                }
13379                if let Some(x) = else_branch {
13380                    Self::rewrite_grouping_to_col(x, grp_exprs);
13381                }
13382            }
13383            _ => {}
13384        }
13385    }
13386
13387    /// v7.39 (round 242) — one grouping element of PG's GROUP BY grammar,
13388    /// as the list of key sets it contributes. A bare expression is one
13389    /// single-key set; `ROLLUP (u1, …, un)` the n+1 unit-prefixes (largest
13390    /// first); `CUBE` every unit-subset (largest first); `GROUPING SETS`
13391    /// the concatenation of its items' sets, where an item is itself an
13392    /// element, a parenthesized key list, or the empty set `()`. A
13393    /// ROLLUP/CUBE member in parentheses is a composite UNIT: its keys
13394    /// move together.
13395    fn parse_grouping_element(&mut self) -> Result<Vec<Vec<Expr>>, ParseError> {
13396        let is_kw = |t: &Token, kw: &str| matches!(t, Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case(kw));
13397        // ROLLUP ( … ) / CUBE ( … )
13398        if (is_kw(self.peek(), "rollup") || is_kw(self.peek(), "cube"))
13399            && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
13400        {
13401            let is_cube = is_kw(self.peek(), "cube");
13402            self.advance(); // ROLLUP / CUBE
13403            self.advance(); // (
13404            let mut units: Vec<Vec<Expr>> = Vec::new();
13405            loop {
13406                if matches!(self.peek(), Token::LParen) {
13407                    // Composite unit: (a, b) rolls up as one.
13408                    self.advance();
13409                    let mut unit = Vec::new();
13410                    if !matches!(self.peek(), Token::RParen) {
13411                        loop {
13412                            unit.push(self.parse_expr(0)?);
13413                            match self.peek() {
13414                                Token::Comma => {
13415                                    self.advance();
13416                                }
13417                                Token::RParen => break,
13418                                other => {
13419                                    return Err(self.err(format!(
13420                                        "expected ',' or ')' in grouping unit, got {other:?}"
13421                                    )));
13422                                }
13423                            }
13424                        }
13425                    }
13426                    self.advance(); // )
13427                    units.push(unit);
13428                } else {
13429                    units.push(alloc::vec![self.parse_expr(0)?]);
13430                }
13431                match self.peek() {
13432                    Token::Comma => {
13433                        self.advance();
13434                    }
13435                    Token::RParen => break,
13436                    other => {
13437                        return Err(self.err(format!(
13438                            "expected ',' or ')' in grouping list, got {other:?}"
13439                        )));
13440                    }
13441                }
13442            }
13443            self.advance(); // )
13444            let flatten = |unit_sel: &[bool]| -> Vec<Expr> {
13445                units
13446                    .iter()
13447                    .zip(unit_sel.iter())
13448                    .filter(|(_, keep)| **keep)
13449                    .flat_map(|(u, _)| u.iter().cloned())
13450                    .collect()
13451            };
13452            let n = units.len();
13453            if is_cube {
13454                let mut subsets: Vec<Vec<bool>> = (0..(1u32 << n))
13455                    .map(|mask| (0..n).map(|i| mask & (1 << i) != 0).collect())
13456                    .collect();
13457                subsets.sort_by_key(|sel| core::cmp::Reverse(sel.iter().filter(|b| **b).count()));
13458                return Ok(subsets.iter().map(|sel| flatten(sel)).collect());
13459            }
13460            return Ok((0..=n)
13461                .rev()
13462                .map(|keep| {
13463                    let sel: Vec<bool> = (0..n).map(|i| i < keep).collect();
13464                    flatten(&sel)
13465                })
13466                .collect());
13467        }
13468        // GROUPING SETS ( item [, item]* )
13469        if is_kw(self.peek(), "grouping")
13470            && matches!(self.tokens.get(self.pos + 1), Some(t) if is_kw(t, "sets"))
13471        {
13472            self.advance(); // GROUPING
13473            self.advance(); // SETS
13474            if !matches!(self.peek(), Token::LParen) {
13475                return Err(self.err(format!(
13476                    "expected '(' after GROUPING SETS, got {:?}",
13477                    self.peek()
13478                )));
13479            }
13480            self.advance(); // outer (
13481            let mut sets: Vec<Vec<Expr>> = Vec::new();
13482            loop {
13483                if matches!(self.peek(), Token::LParen) {
13484                    // A parenthesized key list (or the empty set).
13485                    self.advance();
13486                    let mut set = Vec::new();
13487                    if !matches!(self.peek(), Token::RParen) {
13488                        loop {
13489                            set.push(self.parse_expr(0)?);
13490                            match self.peek() {
13491                                Token::Comma => {
13492                                    self.advance();
13493                                }
13494                                Token::RParen => break,
13495                                other => {
13496                                    return Err(self.err(format!(
13497                                        "expected ',' or ')' in grouping set, got {other:?}"
13498                                    )));
13499                                }
13500                            }
13501                        }
13502                    }
13503                    self.advance(); // )
13504                    sets.push(set);
13505                } else {
13506                    // A nested element: ROLLUP/CUBE/GROUPING SETS or a
13507                    // bare expression.
13508                    sets.extend(self.parse_grouping_element()?);
13509                }
13510                match self.peek() {
13511                    Token::Comma => {
13512                        self.advance();
13513                    }
13514                    Token::RParen => break,
13515                    other => {
13516                        return Err(self.err(format!(
13517                            "expected ',' or ')' after a grouping set, got {other:?}"
13518                        )));
13519                    }
13520                }
13521            }
13522            self.advance(); // outer )
13523            return Ok(sets);
13524        }
13525        Ok(alloc::vec![alloc::vec![self.parse_expr(0)?]])
13526    }
13527
13528    fn substitute_grouping_calls(expr: &mut Expr, dropped: &[Expr]) {
13529        // v7.38 (read01) — a reference to a key that is dropped in this grouping
13530        // set evaluates to NULL, at any depth. Previously only a *top-level*
13531        // select item equal to a dropped key was nullified, so a key nested in
13532        // an expression (`COALESCE(g,'TOTAL')`, `g || sum(v)`) survived as a raw
13533        // column and failed to resolve against the set's synthetic schema.
13534        if dropped.iter().any(|d| d == expr) {
13535            *expr = Expr::Literal(Literal::Null);
13536            return;
13537        }
13538        if let Expr::FunctionCall { name, args } = expr
13539            && name.eq_ignore_ascii_case("grouping")
13540        {
13541            let mut mask: i64 = 0;
13542            for a in args.iter() {
13543                mask <<= 1;
13544                if dropped.iter().any(|d| d == a) {
13545                    mask |= 1;
13546                }
13547            }
13548            // v7.39 (round 242) — wrapped in a cast, NOT a bare integer
13549            // literal: a bare integer in a select item is indistinguishable
13550            // from a positional reference once `ORDER BY 1` substitutes the
13551            // item back in, and the round-232 position check then read the
13552            // mask value as an out-of-range position. The cast changes
13553            // nothing semantically (grouping() is integer).
13554            *expr = Expr::Cast {
13555                expr: alloc::boxed::Box::new(Expr::Literal(Literal::Integer(mask))),
13556                target: crate::ast::CastTarget::Int,
13557            };
13558            return;
13559        }
13560        // Generic recursion over the common expression shapes the
13561        // SELECT list uses; anything without child expressions is
13562        // left alone.
13563        match expr {
13564            Expr::FunctionCall { args, .. } => {
13565                for a in args {
13566                    Self::substitute_grouping_calls(a, dropped);
13567                }
13568            }
13569            Expr::Binary { lhs, rhs, .. } => {
13570                Self::substitute_grouping_calls(lhs, dropped);
13571                Self::substitute_grouping_calls(rhs, dropped);
13572            }
13573            Expr::Unary { expr: inner, .. } => {
13574                Self::substitute_grouping_calls(inner, dropped);
13575            }
13576            Expr::Cast { expr: inner, .. } => {
13577                Self::substitute_grouping_calls(inner, dropped);
13578            }
13579            Expr::Case {
13580                operand,
13581                branches,
13582                else_branch,
13583            } => {
13584                if let Some(op) = operand {
13585                    Self::substitute_grouping_calls(op, dropped);
13586                }
13587                for (w, t) in branches {
13588                    Self::substitute_grouping_calls(w, dropped);
13589                    Self::substitute_grouping_calls(t, dropped);
13590                }
13591                if let Some(e) = else_branch {
13592                    Self::substitute_grouping_calls(e, dropped);
13593                }
13594            }
13595            // v7.38 (read01) — recurse into the remaining child-bearing shapes
13596            // so a dropped key nested in `IS NULL` / `LIKE` / `IN (…)` / `EXTRACT`
13597            // / a subscript / `ANY`/`ALL` is nullified too (`CASE WHEN g IS NULL
13598            // …` is the canonical rollup-total label idiom).
13599            Expr::IsNull { expr: inner, .. } => Self::substitute_grouping_calls(inner, dropped),
13600            Expr::Like { expr, pattern, .. } => {
13601                Self::substitute_grouping_calls(expr, dropped);
13602                Self::substitute_grouping_calls(pattern, dropped);
13603            }
13604            Expr::InList { expr, list, .. } => {
13605                Self::substitute_grouping_calls(expr, dropped);
13606                for item in list {
13607                    Self::substitute_grouping_calls(item, dropped);
13608                }
13609            }
13610            Expr::Extract { source, .. } => Self::substitute_grouping_calls(source, dropped),
13611            Expr::Array(items) => {
13612                for item in items {
13613                    Self::substitute_grouping_calls(item, dropped);
13614                }
13615            }
13616            Expr::ArraySubscript { target, index } => {
13617                Self::substitute_grouping_calls(target, dropped);
13618                Self::substitute_grouping_calls(index, dropped);
13619            }
13620            Expr::ArraySlice { target, lo, hi } => {
13621                Self::substitute_grouping_calls(target, dropped);
13622                if let Some(lo) = lo {
13623                    Self::substitute_grouping_calls(lo, dropped);
13624                }
13625                if let Some(hi) = hi {
13626                    Self::substitute_grouping_calls(hi, dropped);
13627                }
13628            }
13629            Expr::AnyAll { expr, array, .. } => {
13630                Self::substitute_grouping_calls(expr, dropped);
13631                Self::substitute_grouping_calls(array, dropped);
13632            }
13633            _ => {}
13634        }
13635    }
13636
13637    fn parse_bare_select(&mut self) -> Result<SelectStatement, ParseError> {
13638        // v7.37.17 (17.6 siblings) — parenthesized set-operation
13639        // group: `( <select chain> )` usable anywhere a query block
13640        // is (head or peer of an outer chain). The group's own
13641        // unions ride the returned SelectStatement; the executor's
13642        // nested-peer recursion runs them.
13643        if matches!(self.peek(), Token::LParen)
13644            && matches!(
13645                self.tokens.get(self.pos + 1),
13646                Some(Token::Select | Token::LParen | Token::Values)
13647            )
13648        {
13649            self.advance(); // (
13650            self.enter_nested()?;
13651            // v7.37 D.20 — a group whose head is a VALUES list:
13652            // `(VALUES (1),(2)) UNION (VALUES (3))`. Parse the VALUES body,
13653            // otherwise recurse into a nested SELECT/group head.
13654            let mut head = (if matches!(self.peek(), Token::Values) {
13655                self.advance(); // VALUES
13656                self.parse_values_rows_body()
13657            } else {
13658                self.parse_bare_select()
13659            })
13660            .and_then(|mut h| {
13661                self.parse_setop_chain_into(&mut h)?;
13662                Ok(h)
13663            });
13664            self.nest_depth -= 1;
13665            let mut head = match &mut head {
13666                Ok(h) => core::mem::take(h),
13667                Err(_) => return head,
13668            };
13669            // v7.37.17 (17.6 siblings) — group-internal tail:
13670            // `(A UNION B ORDER BY 1 LIMIT 5)`. Parse it into the
13671            // group head, then wrap the group as a derived table
13672            // (SELECT * FROM (group)) so the outer chain / outer
13673            // tail can't clobber the group's own ordering or limit.
13674            let has_tail = matches!(self.peek(), Token::Order | Token::Limit | Token::Offset)
13675                || matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
13676                    if s.eq_ignore_ascii_case("fetch"));
13677            if has_tail {
13678                self.parse_select_tail_into(&mut head)?;
13679                head = SelectStatement {
13680                    locking: None,
13681                    ctes: Vec::new(),
13682                    distinct: false,
13683                    distinct_on: Vec::new(),
13684                    items: alloc::vec![SelectItem::Wildcard],
13685                    from: Some(FromClause {
13686                        primary: TableRef {
13687                            name: "subquery".to_string(),
13688                            alias: None,
13689                            only: false,
13690                            as_of_segment: None,
13691                            unnest_expr: None,
13692                            unnest_column_aliases: Vec::new(),
13693                            with_ordinality: false,
13694                            generate_series_args: None,
13695                            lateral_subquery: Some(Box::new(head)),
13696                            jsonb_each_text_arg: None,
13697                            table_fn_call: None,
13698                            rows_from: None,
13699                            json_table: None,
13700                            scalar_fn_item: false,
13701                        },
13702                        joins: Vec::new(),
13703                    }),
13704                    where_: None,
13705                    group_by: None,
13706                    group_by_all: false,
13707                    having: None,
13708                    unions: Vec::new(),
13709                    order_by: Vec::new(),
13710                    limit: None,
13711                    offset: None,
13712                    limit_with_ties: false,
13713                    window_check_exprs: Vec::new(),
13714                };
13715            }
13716            if !matches!(self.peek(), Token::RParen) {
13717                return Err(self.err(format!(
13718                    "expected ')' after parenthesized query group, got {:?}",
13719                    self.peek()
13720                )));
13721            }
13722            self.advance();
13723            return Ok(head);
13724        }
13725        // `TABLE name` shorthand as a query block — valid anywhere
13726        // a SELECT head is (set-op peers included).
13727        if matches!(self.peek(), Token::Table)
13728            && matches!(
13729                self.tokens.get(self.pos + 1),
13730                Some(Token::Ident(_) | Token::QuotedIdent(_))
13731            )
13732        {
13733            return self.parse_table_shorthand();
13734        }
13735        if !matches!(self.peek(), Token::Select) {
13736            return Err(self.err(format!(
13737                "expected SELECT to start a query block, got {:?}",
13738                self.peek()
13739            )));
13740        }
13741        self.advance();
13742        // v7.39.9 — MySQL's `SELECT STRAIGHT_JOIN …` join-order hint.
13743        //
13744        // It sits where `DISTINCT` sits and tells the optimiser to join
13745        // in the written order. SPG plans its own joins, so the hint is
13746        // accepted and not acted on — but it has to PARSE, because as a
13747        // bare identifier it became a column: measured on the published
13748        // image, `SELECT STRAIGHT_JOIN a FROM t` answered `Unknown
13749        // column 'straight_join' in 'field list'` where MySQL 9.7.2
13750        // returns the rows. Only in this position, which is the only one
13751        // MySQL accepts either — a trailing `STRAIGHT_JOIN` is its 1064.
13752        if self.mysql_dialect
13753            && matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("straight_join"))
13754        {
13755            self.advance();
13756        }
13757        let distinct = if matches!(self.peek(), Token::Distinct) {
13758            self.advance();
13759            true
13760        } else {
13761            false
13762        };
13763        // v7.37.17 (17.6 siblings) — `DISTINCT ON (expr [, …])`:
13764        // keep the first row (per ORDER BY) of each group the
13765        // expressions define. Django's .distinct('field') shape.
13766        let distinct_on: Vec<Expr> = if distinct && matches!(self.peek(), Token::On) {
13767            self.advance(); // ON
13768            if !matches!(self.peek(), Token::LParen) {
13769                return Err(self.err(format!(
13770                    "expected '(' after DISTINCT ON, got {:?}",
13771                    self.peek()
13772                )));
13773            }
13774            self.advance();
13775            let mut exprs = Vec::new();
13776            loop {
13777                exprs.push(self.parse_expr(0)?);
13778                match self.peek() {
13779                    Token::Comma => {
13780                        self.advance();
13781                    }
13782                    Token::RParen => break,
13783                    other => {
13784                        return Err(self.err(format!(
13785                            "expected ',' or ')' in DISTINCT ON list, got {other:?}"
13786                        )));
13787                    }
13788                }
13789            }
13790            self.advance(); // )
13791            exprs
13792        } else {
13793            Vec::new()
13794        };
13795        let mut items = self.parse_select_list()?;
13796        // v7.38.19 — `SELECT … INTO <table>`, PostgreSQL's other spelling
13797        // of CTAS. It sits exactly here in PG's grammar, right after the
13798        // target list.
13799        //
13800        // A comment in `ast.rs` has said since v7.38 that CTAS and
13801        // `SELECT INTO` lower to the same node. Only CTAS ever did:
13802        // `SELECT i INTO t FROM src` answered `syntax error at or near
13803        // "INTO"`, which the differential found while measuring what
13804        // PostgreSQL tags each of the five materialising forms with. A
13805        // comment describing a capability the code does not have is the
13806        // defect this version has been finding all day, and this is the
13807        // one it found in the parser.
13808        //
13809        // `INTO` is captured rather than consumed here: the name has to
13810        // travel out of a function that returns a `SelectStatement`, and
13811        // the caller lowers the whole thing to the CTAS node.
13812        if matches!(self.peek(), Token::Into) {
13813            self.advance();
13814            // `TEMP` / `TEMPORARY` / `UNLOGGED` / `TABLE` are modifiers on
13815            // the target, not part of its name. SPG has one storage
13816            // class, so `UNLOGGED` is accepted and means nothing, which
13817            // is what it already means on `CREATE TABLE`.
13818            let mut temporary = false;
13819            loop {
13820                match self.peek().clone() {
13821                    Token::Ident(w) | Token::QuotedIdent(w)
13822                        if w.eq_ignore_ascii_case("temp")
13823                            || w.eq_ignore_ascii_case("temporary") =>
13824                    {
13825                        temporary = true;
13826                        self.advance();
13827                    }
13828                    Token::Ident(w) | Token::QuotedIdent(w)
13829                        if w.eq_ignore_ascii_case("unlogged") =>
13830                    {
13831                        self.advance();
13832                    }
13833                    Token::Table => {
13834                        self.advance();
13835                    }
13836                    _ => break,
13837                }
13838            }
13839            let name = match self.peek().clone() {
13840                Token::Ident(w) | Token::QuotedIdent(w) => {
13841                    self.advance();
13842                    w
13843                }
13844                other => {
13845                    return Err(self.err(alloc::format!(
13846                        "expected a table name after SELECT … INTO, got {other:?}"
13847                    )));
13848                }
13849            };
13850            self.pending_select_into = Some((name, temporary));
13851        }
13852        // Scope the TABLESAMPLE lowering channel to this SELECT:
13853        // stash whatever an enclosing select accumulated, collect
13854        // our own FROM's predicates, restore after the combine.
13855        let enclosing_sample_preds = core::mem::take(&mut self.pending_sample_preds);
13856        let mut from = if matches!(self.peek(), Token::From) {
13857            self.advance();
13858            Some(self.parse_from_clause()?)
13859        } else {
13860            None
13861        };
13862        // v7.37 D.22 — a set-returning function in the projection with no FROM
13863        // (`SELECT unnest(arr)`, `SELECT 'x', generate_series(a,b)`) expands to
13864        // rows. Move the first SRF projection item to a FROM-position derived
13865        // table and replace it in the projection with a reference to its output
13866        // column; sibling scalar columns repeat per SRF row. PG names the output
13867        // column after the function (or its AS alias). Reuses the FROM-SRF
13868        // machinery. Only fires with no FROM — mixed SRF over a real FROM already
13869        // works via the targetlist-SRF path.
13870        // v7.39 (read01 round 69) — lower `(f(args)).*`. With no FROM it IS
13871        // `SELECT * FROM f(args)` — the record's fields become the columns, which
13872        // is exactly what the function's own row shape already is. Anywhere else
13873        // (per outer row, or beside other items) it would need a real record-typed
13874        // projection, so it says so rather than answering something else.
13875        if let [
13876            SelectItem::Expr {
13877                expr: Expr::FunctionCall { name, args },
13878                ..
13879            },
13880        ] = items.as_slice()
13881            && name == "__record_expand"
13882        {
13883            let Some(Expr::FunctionCall {
13884                name: inner_name,
13885                args: inner_args,
13886            }) = args.first()
13887            else {
13888                return Err(self.err(
13889                    "(<expr>).* expands a function's record — it needs a function call".into(),
13890                ));
13891            };
13892            if from.is_some() {
13893                return Err(self.err(
13894                    "(<fn>).* over a FROM clause is not supported — call the function in FROM"
13895                        .into(),
13896                ));
13897            }
13898            let fn_ref = TableRef {
13899                name: inner_name.clone(),
13900                alias: None,
13901                only: false,
13902                as_of_segment: None,
13903                unnest_expr: None,
13904                unnest_column_aliases: Vec::new(),
13905                with_ordinality: false,
13906                generate_series_args: None,
13907                lateral_subquery: None,
13908                jsonb_each_text_arg: None,
13909                table_fn_call: Some(Box::new((
13910                    inner_name.to_ascii_lowercase(),
13911                    inner_args.clone(),
13912                ))),
13913                rows_from: None,
13914                json_table: None,
13915                scalar_fn_item: false,
13916            };
13917            items = alloc::vec![SelectItem::Wildcard];
13918            from = Some(FromClause {
13919                primary: fn_ref,
13920                joins: Vec::new(),
13921            });
13922        }
13923        // v7.39 (read01 round 74) — `(f(args)).*` beside other items, or over a
13924        // FROM, keeps its marker: the ENGINE lowers it, because naming the
13925        // record's fields takes the catalog. It becomes a LATERAL of the same
13926        // function plus one item per declared column — the machinery rounds 65
13927        // and 69 already built.
13928        // v7.39 (read01 round 67) — the lift moves ONE SRF into FROM. With two
13929        // (`SELECT generate_series(1,3), generate_series(10,11)`) PG runs them in
13930        // LOCKSTEP, padding the shorter with NULLs — a shape the lift cannot
13931        // express, since the lifted one becomes a scan and the other would
13932        // expand per its rows (a cross product, not a zip). So when the
13933        // projection holds more than one top-level function call, the lift steps
13934        // aside and the engine's target-list expansion takes the whole list.
13935        let fn_call_items = items
13936            .iter()
13937            .filter(|it| {
13938                matches!(
13939                    it,
13940                    SelectItem::Expr {
13941                        expr: Expr::FunctionCall { .. },
13942                        ..
13943                    }
13944                )
13945            })
13946            .count();
13947        if from.is_none() && fn_call_items <= 1 {
13948            let mut found: Option<(usize, TableRef, String)> = None;
13949            for (i, item) in items.iter().enumerate() {
13950                if let SelectItem::Expr {
13951                    expr: Expr::FunctionCall { name, args },
13952                    alias,
13953                } = item
13954                {
13955                    let lname = name.to_ascii_lowercase();
13956                    let colname = alias.clone().unwrap_or_else(|| lname.clone());
13957                    let (unnest, gs) = match lname.as_str() {
13958                        "unnest" if args.len() == 1 => (Some(Box::new(args[0].clone())), None),
13959                        "generate_series" if (2..=3).contains(&args.len()) => {
13960                            (None, Some(args.clone()))
13961                        }
13962                        // v7.38 (read01) — generate_subscripts(arr, dim) in a
13963                        // no-FROM projection yields the 1-based subscripts, i.e.
13964                        // generate_series(1, array_length(arr, dim)); an invalid
13965                        // dimension makes array_length NULL → 0 rows, as in PG.
13966                        "generate_subscripts" if args.len() == 2 => (
13967                            None,
13968                            Some(alloc::vec![
13969                                Expr::Literal(Literal::Integer(1)),
13970                                Expr::FunctionCall {
13971                                    name: "array_length".to_string(),
13972                                    args: args.clone(),
13973                                },
13974                            ]),
13975                        ),
13976                        // v7.38 (read01, T-srf) — string_to_table / regexp_split_to_table
13977                        // in a no-FROM projection unnest their *_to_array form.
13978                        "string_to_table" | "regexp_split_to_table" => {
13979                            let array_fn = if lname == "string_to_table" {
13980                                "string_to_array"
13981                            } else {
13982                                "regexp_split_to_array"
13983                            };
13984                            (
13985                                Some(Box::new(Expr::FunctionCall {
13986                                    name: array_fn.to_string(),
13987                                    args: args.clone(),
13988                                })),
13989                                None,
13990                            )
13991                        }
13992                        // v7.38 (read01, T15) — jsonb/json_array_elements[_text] in
13993                        // a no-FROM projection expand per element. The scalar form
13994                        // returns the elements as a TEXT array, so unnest over the
13995                        // same call materialises one row each (same rewrite the
13996                        // FROM-clause form uses).
13997                        "jsonb_array_elements"
13998                        | "json_array_elements"
13999                        | "jsonb_array_elements_text"
14000                        | "json_array_elements_text"
14001                            if args.len() == 1 =>
14002                        {
14003                            (
14004                                Some(Box::new(Expr::FunctionCall {
14005                                    name: lname.clone(),
14006                                    args: args.clone(),
14007                                })),
14008                                None,
14009                            )
14010                        }
14011                        // v7.38 (read01, T15) — jsonb/json_path_query(doc, path)
14012                        // in a no-FROM projection expands per match (scalar form
14013                        // returns the matches as a TEXT array → unnest).
14014                        "jsonb_path_query" | "json_path_query" if args.len() == 2 => (
14015                            Some(Box::new(Expr::FunctionCall {
14016                                name: lname.clone(),
14017                                args: args.clone(),
14018                            })),
14019                            None,
14020                        ),
14021                        _ => continue,
14022                    };
14023                    found = Some((
14024                        i,
14025                        TableRef {
14026                            name: colname.clone(),
14027                            alias: Some(colname.clone()),
14028                            only: false,
14029                            as_of_segment: None,
14030                            unnest_expr: unnest,
14031                            unnest_column_aliases: alloc::vec![colname.clone()],
14032                            with_ordinality: false,
14033                            generate_series_args: gs,
14034                            lateral_subquery: None,
14035                            jsonb_each_text_arg: None,
14036                            table_fn_call: None,
14037                            rows_from: None,
14038                            json_table: None,
14039                            scalar_fn_item: false,
14040                        },
14041                        colname,
14042                    ));
14043                    break;
14044                }
14045            }
14046            if let Some((idx, tref, colname)) = found {
14047                from = Some(FromClause {
14048                    primary: tref,
14049                    joins: Vec::new(),
14050                });
14051                items[idx] = SelectItem::Expr {
14052                    expr: Expr::Column(ColumnName {
14053                        qualifier: None,
14054                        name: colname.clone(),
14055                    }),
14056                    alias: Some(colname),
14057                };
14058            }
14059        }
14060        let sample_preds = core::mem::take(&mut self.pending_sample_preds);
14061        let where_ = if matches!(self.peek(), Token::Where) {
14062            self.advance();
14063            Some(self.parse_expr(0)?)
14064        } else {
14065            None
14066        };
14067        let where_ = sample_preds.into_iter().fold(where_, |acc, pred| {
14068            Some(match acc {
14069                Some(w) => Expr::Binary {
14070                    lhs: Box::new(pred),
14071                    op: crate::ast::BinOp::And,
14072                    rhs: Box::new(w),
14073                },
14074                None => pred,
14075            })
14076        });
14077        self.pending_sample_preds = enclosing_sample_preds;
14078        let mut group_by_all = false;
14079        // v7.37.17 (17.6 siblings) — ROLLUP / CUBE / GROUPING SETS
14080        // share one expansion: `grouping_sets` lists the key subsets
14081        // (first = primary, assigned to stmt.group_by; the rest
14082        // become UNION ALL peers), `grouping_universe` is the full
14083        // key list used to compute each peer's dropped keys.
14084        let mut grouping_sets: Vec<Vec<Expr>> = Vec::new();
14085        let mut grouping_universe: Vec<Expr> = Vec::new();
14086        // v7.39 (round 472) — did the GROUP BY end in MySQL's `WITH ROLLUP`?
14087        // A BOOL, not the key list: this frame is the statement parser's, and
14088        // round 430 measured that a `Vec` local here is enough on its own to
14089        // tip the 512 KiB nesting guard. The keys are recoverable from
14090        // `grouping_universe`, which a rollup fills with exactly them.
14091        let mut mysql_rollup = false;
14092        let group_by = if matches!(self.peek(), Token::Group) {
14093            self.advance();
14094            if !self.peek_is_by() {
14095                return Err(self.err(format!("expected BY after GROUP, got {:?}", self.peek())));
14096            }
14097            self.advance();
14098            // v6.4.1 — `GROUP BY ALL` shortcut. Planner expands to
14099            // every non-aggregate SELECT-list item later.
14100            if matches!(self.peek(), Token::All) {
14101                self.advance();
14102                group_by_all = true;
14103                None
14104            } else {
14105                // v7.39 (round 242) — PG's general grouping-element grammar:
14106                // GROUP BY [DISTINCT] element [, element]*, where an element
14107                // is a bare expression, ROLLUP (…), CUBE (…) or GROUPING
14108                // SETS (…) — mixed freely. Each element yields a list of
14109                // key sets; the query's grouping sets are the CARTESIAN
14110                // PRODUCT of the elements' lists (so `a, ROLLUP (b)` is
14111                // {(a,b),(a)}), and DISTINCT drops duplicate sets by
14112                // content. ROLLUP/CUBE members may be composite
14113                // (`ROLLUP ((a, b))` moves a and b as one unit), and a
14114                // GROUPING SETS item may itself be a ROLLUP/CUBE. The old
14115                // parser handled only a lone ROLLUP/CUBE/GS as the whole
14116                // clause.
14117                let distinct_sets = if matches!(self.peek(), Token::Distinct) {
14118                    self.advance();
14119                    true
14120                } else {
14121                    false
14122                };
14123                let mut element_sets: Vec<Vec<Vec<Expr>>> = Vec::new();
14124                loop {
14125                    element_sets.push(self.parse_grouping_element()?);
14126                    if matches!(self.peek(), Token::Comma) {
14127                        self.advance();
14128                    } else {
14129                        break;
14130                    }
14131                }
14132                let mut total: Vec<Vec<Expr>> = alloc::vec![Vec::new()];
14133                for el in &element_sets {
14134                    let mut next: Vec<Vec<Expr>> = Vec::new();
14135                    for base in &total {
14136                        for set in el {
14137                            let mut merged = base.clone();
14138                            for k in set {
14139                                if !merged.iter().any(|m| m == k) {
14140                                    merged.push(k.clone());
14141                                }
14142                            }
14143                            next.push(merged);
14144                        }
14145                    }
14146                    total = next;
14147                }
14148                // v7.39 (round 472) — MySQL spells a rollup as a SUFFIX:
14149                // `GROUP BY a, b WITH ROLLUP` is PG's `GROUP BY ROLLUP(a, b)`.
14150                // The keys and the aggregates come out identical; the ROW
14151                // ORDER does not, and that is the part a report depends on.
14152                // MySQL interleaves each group's subtotal right after its
14153                // own rows (east/a, east/b, east/NULL, west/a, …, NULL/NULL)
14154                // where the union-of-grouping-sets expansion emits every
14155                // leaf first and then every subtotal. MariaDB REFUSES an
14156                // ORDER BY next to ROLLUP (1221), so a client cannot fix the
14157                // order itself — measured on MariaDB 11 and MySQL 9.7, which
14158                // agree on the order and disagree only on whether ORDER BY
14159                // is allowed (MySQL allows it; SPG allows it too, since
14160                // refusing would break the clients that can write it).
14161                if self.mysql_dialect
14162                    && matches!(self.peek(), Token::Ident(w) if w.eq_ignore_ascii_case("with"))
14163                    && matches!(
14164                        self.tokens.get(self.pos + 1),
14165                        Some(Token::Ident(r)) if r.eq_ignore_ascii_case("rollup")
14166                    )
14167                {
14168                    self.advance(); // WITH
14169                    self.advance(); // ROLLUP
14170                    let keys = total.into_iter().next().unwrap_or_default();
14171                    mysql_rollup = true;
14172                    // n+1 prefixes, largest first — the same expansion
14173                    // `ROLLUP (…)` produces.
14174                    total = (0..=keys.len()).rev().map(|n| keys[..n].to_vec()).collect();
14175                }
14176                if distinct_sets {
14177                    let mut seen: Vec<Vec<String>> = Vec::new();
14178                    total.retain(|set| {
14179                        let mut key: Vec<String> =
14180                            set.iter().map(|e| alloc::format!("{e}")).collect();
14181                        key.sort();
14182                        if seen.contains(&key) {
14183                            false
14184                        } else {
14185                            seen.push(key);
14186                            true
14187                        }
14188                    });
14189                }
14190                if total.len() > 1 {
14191                    let mut universe: Vec<Expr> = Vec::new();
14192                    for set in &total {
14193                        for k in set {
14194                            if !universe.iter().any(|u| u == k) {
14195                                universe.push(k.clone());
14196                            }
14197                        }
14198                    }
14199                    grouping_universe = universe;
14200                    let primary = total[0].clone();
14201                    grouping_sets = total;
14202                    Some(primary)
14203                } else {
14204                    // One set (a plain GROUP BY list, or a single-set
14205                    // spelling like GROUPING SETS ((a, b))). An EMPTY
14206                    // single set — GROUPING SETS (()) — stays
14207                    // `Some(vec![])`: the grand-total group, which must
14208                    // run the aggregate path.
14209                    Some(total.into_iter().next().unwrap_or_default())
14210                }
14211            }
14212        } else {
14213            None
14214        };
14215        let having = if matches!(self.peek(), Token::Having) {
14216            self.advance();
14217            Some(self.parse_expr(0)?)
14218        } else {
14219            None
14220        };
14221        // `WINDOW w AS ( <window-def> ) [, ...]` — named windows.
14222        // OVER w parsed to a marker above; inline each definition
14223        // into the referencing WindowFunction nodes.
14224        let mut window_defs: Vec<(String, WindowDef)> = Vec::new();
14225        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("window")) {
14226            self.advance();
14227            loop {
14228                let wname = self.expect_ident_like()?;
14229                if !matches!(self.peek(), Token::As) {
14230                    return Err(self.err(format!(
14231                        "expected AS after WINDOW {wname}, got {:?}",
14232                        self.peek()
14233                    )));
14234                }
14235                self.advance();
14236                // v7.39 (round 229) — PG rejects a redefinition outright.
14237                if window_defs
14238                    .iter()
14239                    .any(|(n, _)| n.eq_ignore_ascii_case(&wname))
14240                {
14241                    return Err(self.err(alloc::format!("window \"{wname}\" is already defined")));
14242                }
14243                let def = self.parse_over_clause()?;
14244                // A definition may itself copy an earlier one
14245                // (`WINDOW w1 AS (PARTITION BY g), w2 AS (w1 ORDER BY v)`),
14246                // so resolve it against the defs already in scope. Same
14247                // copy rules as an `OVER (w1 …)` in the select list.
14248                let mut probe = Expr::WindowFunction {
14249                    name: String::new(),
14250                    args: Vec::new(),
14251                    partition_by: def.0,
14252                    order_by: def.1,
14253                    frame: def.2,
14254                    null_treatment: crate::ast::NullTreatment::Respect,
14255                    filter: None,
14256                };
14257                Self::substitute_named_windows(&mut probe, &window_defs)
14258                    .map_err(|m| self.err(m))?;
14259                let Expr::WindowFunction {
14260                    partition_by,
14261                    order_by,
14262                    frame,
14263                    ..
14264                } = probe
14265                else {
14266                    unreachable!("probe is a WindowFunction")
14267                };
14268                window_defs.push((wname, (partition_by, order_by, frame)));
14269                if matches!(self.peek(), Token::Comma) {
14270                    self.advance();
14271                    continue;
14272                }
14273                break;
14274            }
14275        }
14276        // v7.39 (round 705) — which definitions did anything reference?
14277        // The ones nothing did used to be dropped here, unexamined, so
14278        // `WINDOW w AS (ORDER BY nosuch)` succeeded — PG analyses every
14279        // definition whether referenced or not. Their key expressions ride
14280        // out on the statement for the engine to resolve.
14281        let mut window_refs: Vec<String> = Vec::new();
14282        if !window_defs.is_empty() {
14283            for it in &items {
14284                if let SelectItem::Expr { expr, .. } = it {
14285                    Self::collect_named_window_refs(expr, &mut window_refs);
14286                }
14287            }
14288        }
14289        let window_check_exprs: Vec<Expr> = window_defs
14290            .iter()
14291            .filter(|(n, _)| !window_refs.iter().any(|r| r.eq_ignore_ascii_case(n)))
14292            .flat_map(|(_, (partition, order, _))| {
14293                partition
14294                    .iter()
14295                    .cloned()
14296                    .chain(order.iter().map(|(e, _, _)| e.clone()))
14297            })
14298            .collect();
14299        if !window_defs.is_empty()
14300            || items
14301                .iter()
14302                .any(|it| matches!(it, SelectItem::Expr { expr, .. } if Self::expr_has_named_window(expr)))
14303        {
14304            for it in &mut items {
14305                if let SelectItem::Expr { expr, .. } = it {
14306                    Self::substitute_named_windows(expr, &window_defs)
14307                        .map_err(|m| self.err(m))?;
14308                }
14309            }
14310        }
14311        // `GROUP BY 1` — positional keys substitute with the Nth
14312        // select item's expression (same contract ORDER BY has had
14313        // since v6.x). Out-of-range positions error.
14314        let group_by = match group_by {
14315            Some(mut keys) => {
14316                for k in &mut keys {
14317                    if let Expr::Literal(Literal::Integer(n)) = k {
14318                        let idx = *n;
14319                        if idx < 1 || idx as usize > items.len() {
14320                            return Err(self.err(alloc::format!(
14321                                "GROUP BY position {idx} is not in select list"
14322                            )));
14323                        }
14324                        match &items[(idx - 1) as usize] {
14325                            SelectItem::Expr { expr, .. } => *k = expr.clone(),
14326                            SelectItem::Wildcard | SelectItem::QualifiedWildcard(_) => {
14327                                return Err(self.err(alloc::format!(
14328                                    "GROUP BY position {idx} references a wildcard item"
14329                                )));
14330                            }
14331                        }
14332                    }
14333                }
14334                Some(keys)
14335            }
14336            None => None,
14337        };
14338        let mut stmt = SelectStatement {
14339            locking: None,
14340            ctes: Vec::new(),
14341            distinct,
14342            distinct_on,
14343            items,
14344            from,
14345            where_,
14346            group_by,
14347            group_by_all,
14348            having,
14349            unions: Vec::new(),
14350            order_by: Vec::new(),
14351            limit: None,
14352            offset: None,
14353            limit_with_ties: false,
14354            window_check_exprs,
14355        };
14356        // Grouping expansion (ROLLUP / CUBE / GROUPING SETS): the
14357        // first set is the primary (already on stmt.group_by); each
14358        // further set becomes a UNION ALL peer with its dropped
14359        // keys (universe minus the set) replaced by NULL literals
14360        // in the peer's items and group_by. PG-legal: non-grouped
14361        // select items must be group keys or aggregates, so a
14362        // dropped key's occurrences in the projection are exactly
14363        // the ones to nullify.
14364        // v7.39 (round 242) — grouping() OUTSIDE an expansion: PG allows it
14365        // over a plain GROUP BY (every argument must be a group key; the
14366        // mask is then 0) and rejects anything else with 42803. SPG's
14367        // rewrite only ran during the ROLLUP/CUBE expansion, so a plain
14368        // `SELECT grouping(a) … GROUP BY a` died at eval with "unknown
14369        // function `grouping`".
14370        if grouping_sets.len() <= 1 {
14371            let keys: Vec<Expr> = stmt.group_by.clone().unwrap_or_default();
14372            let mut calls: Vec<Expr> = Vec::new();
14373            for item in &stmt.items {
14374                if let SelectItem::Expr { expr, .. } = item {
14375                    Self::collect_grouping_calls(expr, &mut calls);
14376                }
14377            }
14378            if let Some(h) = &stmt.having {
14379                Self::collect_grouping_calls(h, &mut calls);
14380            }
14381            for call in &calls {
14382                let Expr::FunctionCall { args, .. } = call else {
14383                    continue;
14384                };
14385                for a in args {
14386                    if !keys.iter().any(|k| k == a) {
14387                        return Err(self.err(
14388                            "arguments to GROUPING must be grouping expressions of the associated query level"
14389                                .to_string(),
14390                        ));
14391                    }
14392                }
14393            }
14394            if !calls.is_empty() {
14395                for item in &mut stmt.items {
14396                    if let SelectItem::Expr { expr, .. } = item {
14397                        Self::substitute_grouping_calls(expr, &[]);
14398                    }
14399                }
14400                if let Some(h) = &mut stmt.having {
14401                    Self::substitute_grouping_calls(h, &[]);
14402                }
14403            }
14404        }
14405        if grouping_sets.len() > 1 {
14406            // The primary set's own dropped keys nullify in the
14407            // HEAD's projection too (GROUPING SETS's first set may
14408            // omit keys other sets use).
14409            let primary = grouping_sets[0].clone();
14410            let head_dropped: Vec<Expr> = grouping_universe
14411                .iter()
14412                .filter(|u| !primary.iter().any(|k| k == *u))
14413                .cloned()
14414                .collect();
14415            for set in grouping_sets.iter().skip(1) {
14416                let mut peer = stmt.clone();
14417                peer.unions = Vec::new();
14418                let dropped: Vec<&Expr> = grouping_universe
14419                    .iter()
14420                    .filter(|u| !set.iter().any(|k| k == *u))
14421                    .collect();
14422                // Empty set = grand-total group: `Some(vec![])` forces
14423                // the aggregate path (one collapsed row) instead of a
14424                // per-row passthrough. See the primary-set note above.
14425                peer.group_by = Some(set.clone());
14426                let dropped_owned: Vec<Expr> = dropped.iter().map(|d| (*d).clone()).collect();
14427                for item in &mut peer.items {
14428                    if let SelectItem::Expr { expr, alias } = item {
14429                        if dropped.iter().any(|d| *d == expr) {
14430                            // v7.39 — keep the dropped key's name on the
14431                            // NULL literal so the UNION output column
14432                            // (and any top-level ORDER BY on it) still
14433                            // resolves.
14434                            if alias.is_none()
14435                                && let Expr::Column(c) = &expr
14436                            {
14437                                *alias = Some(c.name.clone());
14438                            }
14439                            *expr = Expr::Literal(Literal::Null);
14440                        } else {
14441                            Self::substitute_grouping_calls(expr, &dropped_owned);
14442                        }
14443                    }
14444                }
14445                if let Some(h) = &mut peer.having {
14446                    Self::substitute_grouping_calls(h, &dropped_owned);
14447                }
14448                stmt.unions.push((UnionKind::All, peer));
14449            }
14450            for item in &mut stmt.items {
14451                if let SelectItem::Expr { expr, alias } = item {
14452                    if head_dropped.iter().any(|d| d == expr) {
14453                        if alias.is_none()
14454                            && let Expr::Column(c) = &expr
14455                        {
14456                            *alias = Some(c.name.clone());
14457                        }
14458                        *expr = Expr::Literal(Literal::Null);
14459                    } else {
14460                        Self::substitute_grouping_calls(expr, &head_dropped);
14461                    }
14462                }
14463            }
14464            if let Some(h) = &mut stmt.having {
14465                Self::substitute_grouping_calls(h, &head_dropped);
14466            }
14467            // v7.39 (round 135) — GROUPING() in ORDER BY. Parse the ORDER BY now
14468            // (while `grouping_universe` / the per-branch sets are in scope). For
14469            // each grouping() call in it, inject a per-branch hidden column
14470            // `__grp_ord_K` carrying that branch's mask into the head + every
14471            // peer, and rewrite the ORDER BY to reference it. `parse_select_tail_into`
14472            // preserves this pre-set order_by; the engine strips `__grp_ord_*`
14473            // from the final output. A standalone grouping-set query has ORDER BY
14474            // (not an explicit set-op) next, so consuming it here is safe.
14475            // v7.39 (round 472) — absent the client's own ORDER BY, a MySQL
14476            // rollup carries the hierarchical order: sort by the grouping
14477            // keys with the rolled-up NULLs last, which is exactly the
14478            // interleaving both oracles emit. A client's own ORDER BY wins,
14479            // which is what MySQL does (MariaDB refuses to let one be
14480            // written at all).
14481            // The synthesised keys have to travel the SAME path a written
14482            // ORDER BY does: the block below is what turns a `grouping()`
14483            // call into the per-branch `__grp_ord_K` column the engine can
14484            // actually sort on. Bypassing it left a bare `grouping(text)`
14485            // for the evaluator to reject.
14486            let synthesised_or_parsed: Vec<OrderBy> = if matches!(self.peek(), Token::Order) {
14487                self.parse_order_by_keys()?
14488            } else if mysql_rollup {
14489                Self::mysql_rollup_order(&grouping_universe)
14490            } else {
14491                Vec::new()
14492            };
14493            if !synthesised_or_parsed.is_empty() {
14494                let mut order_keys = synthesised_or_parsed;
14495                let mut grp_exprs: Vec<Expr> = Vec::new();
14496                for ob in &order_keys {
14497                    Self::collect_grouping_calls(&ob.expr, &mut grp_exprs);
14498                }
14499                for (k, gexpr) in grp_exprs.iter().enumerate() {
14500                    let colname = alloc::format!("__grp_ord_{k}");
14501                    // Head branch (primary set) uses `head_dropped`.
14502                    let mut he = gexpr.clone();
14503                    Self::substitute_grouping_calls(&mut he, &head_dropped);
14504                    stmt.items.push(SelectItem::Expr {
14505                        expr: he,
14506                        alias: Some(colname.clone()),
14507                    });
14508                    // Each peer `stmt.unions[i]` corresponds to `grouping_sets[i+1]`.
14509                    for (i, (_, peer)) in stmt.unions.iter_mut().enumerate() {
14510                        let set = &grouping_sets[i + 1];
14511                        let dropped: Vec<Expr> = grouping_universe
14512                            .iter()
14513                            .filter(|u| !set.iter().any(|k| k == *u))
14514                            .cloned()
14515                            .collect();
14516                        let mut pe = gexpr.clone();
14517                        Self::substitute_grouping_calls(&mut pe, &dropped);
14518                        peer.items.push(SelectItem::Expr {
14519                            expr: pe,
14520                            alias: Some(colname.clone()),
14521                        });
14522                    }
14523                }
14524                for ob in &mut order_keys {
14525                    Self::rewrite_grouping_to_col(&mut ob.expr, &grp_exprs);
14526                }
14527                stmt.order_by = order_keys;
14528            }
14529        }
14530        Ok(stmt)
14531    }
14532
14533    /// v7.39 (round 472) — the row order MySQL's `WITH ROLLUP` promises,
14534    /// as ORDER BY keys.
14535    ///
14536    /// Per key: the rollup marker, then the key. Sorting on the key alone
14537    /// is not enough, and a table with a NULL in it says why — MariaDB puts
14538    /// the DATA-NULL group where a plain GROUP BY puts it (first) and only
14539    /// the ROLLUP-introduced NULL last, and both print as NULL.
14540    /// `GROUPING(k)` is the one thing that tells them apart: 0 for every
14541    /// real group including the data-NULL one, 1 only for the row the
14542    /// rollup added. Measured on MariaDB 11 — `('a',1),(NULL,2),('b',3)`
14543    /// rolls up to NULL|2, a|1, b|3, NULL|6.
14544    ///
14545    /// `#[inline(never)]`: its locals must not join the statement parser's
14546    /// frame, which round 430 measured sitting against the nesting guard.
14547    #[inline(never)]
14548    fn mysql_rollup_order(keys: &[Expr]) -> Vec<OrderBy> {
14549        let mut out: Vec<OrderBy> = Vec::with_capacity(keys.len() * 2);
14550        for e in keys {
14551            out.push(OrderBy {
14552                expr: Expr::FunctionCall {
14553                    name: "grouping".into(),
14554                    args: alloc::vec![e.clone()],
14555                },
14556                desc: false,
14557                nulls_first: None,
14558                collation: None,
14559            });
14560            out.push(OrderBy {
14561                expr: e.clone(),
14562                desc: false,
14563                // MySQL orders NULL first on an ascending key.
14564                nulls_first: Some(true),
14565                collation: None,
14566            });
14567        }
14568        out
14569    }
14570
14571    /// v7.39 (round 535) — `REINDEX [(opts)] { INDEX | TABLE | SCHEMA |
14572    /// DATABASE | SYSTEM } [CONCURRENTLY] [<name>]`.
14573    #[inline(never)]
14574    fn parse_reindex_tail(&mut self) -> Result<Statement, ParseError> {
14575        use crate::ast::MaintainKind;
14576        self.skip_paren_option_list();
14577        let kind = match self.peek() {
14578            // `TABLE` and `INDEX` lex as keywords, not identifiers.
14579            Token::Table | Token::Index => {
14580                self.advance();
14581                MaintainKind::ReindexRelation
14582            }
14583            Token::Ident(s) | Token::QuotedIdent(s) => match s.to_ascii_lowercase().as_str() {
14584                "index" | "table" => {
14585                    self.advance();
14586                    MaintainKind::ReindexRelation
14587                }
14588                "schema" => {
14589                    self.advance();
14590                    MaintainKind::ReindexSchema
14591                }
14592                "system" | "database" => {
14593                    self.advance();
14594                    MaintainKind::Whole
14595                }
14596                // PG requires the object type; anything else is the
14597                // caller's problem, not something to swallow.
14598                _ => MaintainKind::ReindexRelation,
14599            },
14600            _ => MaintainKind::Whole,
14601        };
14602        // PG bars `REINDEX … CONCURRENTLY` inside a transaction block and
14603        // allows the plain form, so the modifier is recorded rather than
14604        // skipped. It still has no effect on how the reindex runs.
14605        let mut concurrently = false;
14606        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("concurrently")) {
14607            self.advance();
14608            concurrently = true;
14609        }
14610        let target = self.take_optional_maintain_name();
14611        self.consume_until_statement_boundary();
14612        Ok(Statement::Maintain {
14613            kind,
14614            concurrently,
14615            target,
14616        })
14617    }
14618
14619    /// v7.39 (round 535) — `CLUSTER [VERBOSE] [<table> [USING <index>]]`
14620    /// and `CLUSTER [VERBOSE] <index> ON <table>`.
14621    #[inline(never)]
14622    fn parse_cluster_tail(&mut self) -> Result<Statement, ParseError> {
14623        use crate::ast::MaintainKind;
14624        self.skip_paren_option_list();
14625        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("verbose")) {
14626            self.advance();
14627        }
14628        let target = self.take_optional_maintain_name();
14629        self.consume_until_statement_boundary();
14630        Ok(Statement::Maintain {
14631            kind: if target.is_some() {
14632                MaintainKind::ClusterRelation
14633            } else {
14634                MaintainKind::Whole
14635            },
14636            // CLUSTER has no CONCURRENTLY form, and PG runs it inside a
14637            // transaction block quite happily (measured).
14638            concurrently: false,
14639            target,
14640        })
14641    }
14642
14643    /// The next token as a relation / schema name, when there is one.
14644    fn take_optional_maintain_name(&mut self) -> Option<alloc::string::String> {
14645        match self.peek() {
14646            Token::Ident(_) | Token::QuotedIdent(_) => match self.advance() {
14647                Token::Ident(n) | Token::QuotedIdent(n) => Some(n),
14648                _ => None,
14649            },
14650            _ => None,
14651        }
14652    }
14653
14654    /// A parenthesised option list, absorbed.
14655    fn skip_paren_option_list(&mut self) {
14656        if !matches!(self.peek(), Token::LParen) {
14657            return;
14658        }
14659        let mut depth = 0usize;
14660        loop {
14661            match self.advance() {
14662                Token::LParen => depth += 1,
14663                Token::RParen => {
14664                    depth -= 1;
14665                    if depth == 0 {
14666                        return;
14667                    }
14668                }
14669                Token::Eof => return,
14670                _ => {}
14671            }
14672        }
14673    }
14674
14675    /// v7.39 (round 531) — the `LIKE` clause inside a CREATE TABLE
14676    /// column list.
14677    ///
14678    /// PG's option names are COMMENTS / COMPRESSION / CONSTRAINTS /
14679    /// DEFAULTS / GENERATED / IDENTITY / INDEXES / STATISTICS / STORAGE
14680    /// / ALL. The three that describe physical storage have no meaning
14681    /// here, so they parse and change nothing rather than making a
14682    /// dump that mentions them fail to load.
14683    ///
14684    /// `#[inline(never)]` because the CREATE TABLE frame sits on the
14685    /// parse chain the nesting sentinel is tuned against.
14686    #[inline(never)]
14687    fn parse_create_table_like(&mut self, at: usize) -> Result<crate::ast::LikeSpec, ParseError> {
14688        self.advance(); // LIKE
14689        let source = self.expect_ident_like()?;
14690        let mut options = crate::ast::LikeOptions::default();
14691        loop {
14692            let including = match self.peek() {
14693                Token::Ident(s) if s.eq_ignore_ascii_case("including") => true,
14694                Token::Ident(s) if s.eq_ignore_ascii_case("excluding") => false,
14695                _ => break,
14696            };
14697            self.advance();
14698            // `ALL` lexes as its own keyword, not an identifier.
14699            let opt = if matches!(self.peek(), Token::All) {
14700                self.advance();
14701                alloc::string::String::from("all")
14702            } else {
14703                self.expect_ident_like()?
14704            };
14705            let set = |o: &mut crate::ast::LikeOptions, on: bool| {
14706                o.defaults = on;
14707                o.constraints = on;
14708                o.identity = on;
14709                o.generated = on;
14710                o.indexes = on;
14711                o.comments = on;
14712            };
14713            match opt.to_ascii_lowercase().as_str() {
14714                "all" => set(&mut options, including),
14715                "defaults" => options.defaults = including,
14716                "constraints" => options.constraints = including,
14717                "identity" => options.identity = including,
14718                "generated" => options.generated = including,
14719                "indexes" => options.indexes = including,
14720                "comments" => options.comments = including,
14721                // No storage model to copy into.
14722                "storage" | "statistics" | "compression" => {}
14723                other => {
14724                    return Err(self.err(alloc::format!("unrecognized LIKE option {other:?}")));
14725                }
14726            }
14727        }
14728        Ok(crate::ast::LikeSpec {
14729            source,
14730            at,
14731            options,
14732        })
14733    }
14734
14735    fn parse_create_table_stmt_after_create(&mut self) -> Result<Statement, ParseError> {
14736        // Caller already consumed CREATE; we're sitting on TABLE.
14737        debug_assert!(matches!(self.peek(), Token::Table));
14738        self.advance();
14739        let if_not_exists = self.consume_if_not_exists();
14740        let name = self.expect_ident_like()?;
14741        // v7.37.6-B — `CREATE TABLE c PARTITION OF parent <bounds>`
14742        // child shape has no column list; the child inherits its
14743        // columns from the parent at engine-DDL time. Detect it
14744        // before the `(` requirement below.
14745        if matches!(self.peek(), Token::Partition)
14746            && Self::tokens_match_ident_ci(self.tokens.get(self.pos + 1), "of")
14747        {
14748            self.advance(); // PARTITION
14749            self.advance(); // of
14750            let partition_of = self.parse_partition_of_tail()?;
14751            return Ok(Statement::CreateTable(CreateTableStatement {
14752                temporary: false,
14753                name,
14754                engine: None,
14755                columns: Vec::new(),
14756                like_specs: Vec::new(),
14757                inherits: Vec::new(),
14758                if_not_exists,
14759                foreign_keys: Vec::new(),
14760                table_constraints: Vec::new(),
14761                partition_by: None,
14762                partition_of: Some(partition_of),
14763            }));
14764        }
14765        // v7.38 (read01 P6.49) — CTAS: `CREATE TABLE name AS <select>`. Reuses
14766        // the materialized-view materialisation path (run the SELECT, infer the
14767        // column types, create + populate the table) but marks the node so the
14768        // executor creates a plain table without a mat-view registry entry.
14769        if matches!(self.peek(), Token::As) {
14770            self.advance();
14771            let body_stmt = self.parse_select_stmt()?;
14772            let Statement::Select(body) = body_stmt else {
14773                return Err(self.err(format!(
14774                    "CREATE TABLE {name:?} AS body must be a SELECT, got {body_stmt:?}"
14775                )));
14776            };
14777            let with_data = self.parse_optional_with_data(true)?;
14778            return Ok(Statement::CreateMaterializedView(
14779                crate::ast::CreateMaterializedViewStatement {
14780                    temporary: false,
14781                    name,
14782                    if_not_exists,
14783                    columns: Vec::new(),
14784                    body,
14785                    with_data,
14786                    as_plain_table: true,
14787                },
14788            ));
14789        }
14790        if !matches!(self.peek(), Token::LParen) {
14791            return Err(self.err(format!(
14792                "expected '(' after table name, got {:?}",
14793                self.peek()
14794            )));
14795        }
14796        self.advance();
14797        let mut columns = Vec::new();
14798        let mut foreign_keys: Vec<ForeignKeyConstraint> = Vec::new();
14799        let mut table_constraints: Vec<crate::ast::TableConstraint> = Vec::new();
14800        let mut like_specs: Vec<crate::ast::LikeSpec> = Vec::new();
14801        loop {
14802            // v7.39 (round 621) — `CREATE TABLE c () INHERITS (p)`, the empty
14803            // column list. It is how a child that adds nothing of its own is
14804            // written, and this loop demanded at least one entry: `syntax
14805            // error at or near ")"`. The child takes the parent's columns,
14806            // which the INHERITS clause already arranges.
14807            if columns.is_empty() && matches!(self.peek(), Token::RParen) {
14808                self.advance();
14809                break;
14810            }
14811            // v7.6.0 / v7.9.18 — distinguish table-level constraint
14812            // clauses from column definitions. Constraints start
14813            // with `CONSTRAINT <name> …`, `FOREIGN KEY (…)`,
14814            // `PRIMARY KEY (…)`, or `UNIQUE (…)`. Anything else is
14815            // a column.
14816            if self.peek_table_level_pk_start() {
14817                table_constraints.push(self.parse_table_level_primary_key()?);
14818            } else if matches!(self.peek(), Token::Like) {
14819                // v7.39 (round 531) — `LIKE <table> [ {INCLUDING|EXCLUDING}
14820                // <opt> ]*`. The source table's shape lives in the catalog,
14821                // so this records the clause and the engine expands it.
14822                like_specs.push(self.parse_create_table_like(columns.len())?);
14823            } else if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("exclude")) {
14824                // v7.39 (round 210) — bare `EXCLUDE [USING m] (col WITH op, …)`.
14825                table_constraints.push(self.parse_table_level_exclude()?);
14826            } else if self.peek_table_level_unique_start() {
14827                table_constraints.push(self.parse_table_level_unique()?);
14828            } else if self.peek_table_level_check_start() {
14829                // v7.13.0 — table-level CHECK (mailrs round-5 G3).
14830                table_constraints.push(self.parse_table_level_check()?);
14831            } else if self.peek_mysql_inline_key_start() {
14832                // v7.14.0 — mysqldump emits inline `KEY name (cols)`,
14833                // `INDEX name (cols)`, `UNIQUE KEY name (cols)`,
14834                // `FULLTEXT KEY name (cols)`, `SPATIAL KEY name (cols)`
14835                // inside the column list. Skip name + paren list;
14836                // for UNIQUE KEY, register as a UC.
14837                if let Some(uc) = self.parse_mysql_inline_key()? {
14838                    table_constraints.push(uc);
14839                }
14840            } else if let Some(kind) = self.peek_named_table_constraint_kind() {
14841                // v7.22 (mailrs round-13 gap 5) — `CONSTRAINT <name>
14842                // { CHECK | UNIQUE | PRIMARY KEY }`: every pg_dump'd
14843                // CHECK is named, and the named-CONSTRAINT arm used
14844                // to accept FOREIGN KEY only. The name is accepted
14845                // and discarded — same handling as every other SPG
14846                // constraint name.
14847                self.advance(); // CONSTRAINT
14848                // v7.39 (read01 round 48) — the name is kept now: the schema
14849                // stores it, so DROP / RENAME CONSTRAINT can find it.
14850                let con_name = self.expect_ident_like()?;
14851                let mut tc = match kind {
14852                    NamedTableConstraintKind::Check => self.parse_table_level_check()?,
14853                    NamedTableConstraintKind::Unique => self.parse_table_level_unique()?,
14854                    NamedTableConstraintKind::PrimaryKey => self.parse_table_level_primary_key()?,
14855                    NamedTableConstraintKind::Exclude => self.parse_table_level_exclude()?,
14856                };
14857                match &mut tc {
14858                    crate::ast::TableConstraint::Check { name, .. }
14859                    | crate::ast::TableConstraint::Unique { name, .. }
14860                    | crate::ast::TableConstraint::PrimaryKey { name, .. }
14861                    | crate::ast::TableConstraint::Exclude { name, .. } => {
14862                        *name = Some(con_name);
14863                    }
14864                    _ => {}
14865                }
14866                table_constraints.push(tc);
14867            } else if self.peek_constraint_or_fk_start() {
14868                foreign_keys.push(self.parse_table_level_fk()?);
14869            } else {
14870                let (col, col_level_fk) = self.parse_column_def_with_fk()?;
14871                // v7.13.0 — fold inline UNIQUE / CHECK column
14872                // constraints into table-level entries so the
14873                // engine path stays uniform.
14874                if col.is_unique {
14875                    table_constraints.push(crate::ast::TableConstraint::Unique {
14876                        name: None,
14877                        columns: alloc::vec![col.name.clone()],
14878                        nulls_not_distinct: col.unique_nulls_not_distinct,
14879                        deferrable: col.constraint_deferrable,
14880                        initially_deferred: col.constraint_initially_deferred,
14881                    });
14882                }
14883                if let Some(check_expr) = col.check.clone() {
14884                    table_constraints.push(crate::ast::TableConstraint::Check {
14885                        name: None,
14886                        expr: check_expr,
14887                        not_valid: false,
14888                    });
14889                }
14890                columns.push(col);
14891                if let Some(fk) = col_level_fk {
14892                    foreign_keys.push(fk);
14893                }
14894            }
14895            match self.peek() {
14896                Token::Comma => {
14897                    self.advance();
14898                }
14899                Token::RParen => {
14900                    self.advance();
14901                    break;
14902                }
14903                other => {
14904                    return Err(
14905                        self.err(format!("expected ',' or ')' in column list, got {other:?}"))
14906                    );
14907                }
14908            }
14909        }
14910        // v7.39 (round 531) — a `LIKE` clause brings its own columns, so
14911        // `CREATE TABLE k (LIKE t)` is a complete definition even though
14912        // nothing is written between the parentheses.
14913        // v7.39 (round 621) — a table with NO columns is legal: PG creates it
14914        // and `INSERT … DEFAULT VALUES` puts a row in it. This refused, so the
14915        // empty parentheses were a parse error in their own right — quite apart
14916        // from `CREATE TABLE c () INHERITS (p)`, which needs table inheritance
14917        // SPG does not have (filed separately).
14918        let _ = &like_specs;
14919        // v7.39 (round 645) — `INHERITS (p1, p2)`, PG table inheritance.
14920        // It sits between the column list and the MySQL table options,
14921        // and it was a syntax error until this round.
14922        let mut inherits: Vec<String> = Vec::new();
14923        if matches!(self.peek(), Token::Ident(k) | Token::QuotedIdent(k)
14924            if k.eq_ignore_ascii_case("inherits"))
14925        {
14926            self.advance();
14927            if !matches!(self.peek(), Token::LParen) {
14928                return Err(self.err(alloc::format!(
14929                    "expected ( after INHERITS, got {:?}",
14930                    self.peek()
14931                )));
14932            }
14933            self.advance();
14934            loop {
14935                inherits.push(self.expect_ident_like()?);
14936                if matches!(self.peek(), Token::Comma) {
14937                    self.advance();
14938                    continue;
14939                }
14940                break;
14941            }
14942            if !matches!(self.peek(), Token::RParen) {
14943                return Err(self.err(alloc::format!(
14944                    "expected ) closing INHERITS, got {:?}",
14945                    self.peek()
14946                )));
14947            }
14948            self.advance();
14949        }
14950        // v7.14.0 — consume MySQL/MariaDB table options after the
14951        // closing `)`. mysqldump emits things like
14952        // `ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
14953        // AUTO_INCREMENT=42 ROW_FORMAT=DYNAMIC COMMENT='blog posts'`.
14954        // SPG accepts all forms as no-ops (each option is
14955        // `<ident> [=] <ident-or-string>` separated by whitespace).
14956        let engine = self.consume_mysql_table_options();
14957        // v7.38 (read01 P6.55) — PG storage parameters `WITH (opt=val, …)`.
14958        // SPG has no per-table reloptions, so accept and ignore them so a
14959        // pg_dump `CREATE TABLE … WITH (fillfactor=70, …)` restores cleanly.
14960        self.consume_with_reloptions();
14961        // v7.37.6-B — declarative-partition-parent suffix
14962        // (`PARTITION BY RANGE (key_col)`) sits after the column
14963        // list + MySQL table-options. v7.37.6-B only accepts RANGE
14964        // and locks the key column at one ident; the engine then
14965        // verifies the column type is TIMESTAMPTZ.
14966        let partition_by = if matches!(self.peek(), Token::Partition) {
14967            self.advance(); // PARTITION
14968            if !self.peek_is_by() {
14969                return Err(self.err(format!(
14970                    "expected BY after PARTITION, got {:?}",
14971                    self.peek()
14972                )));
14973            }
14974            self.advance();
14975            Some(self.parse_partition_by_tail()?)
14976        } else {
14977            None
14978        };
14979        Ok(Statement::CreateTable(CreateTableStatement {
14980            temporary: false,
14981            name,
14982            engine,
14983            columns,
14984            like_specs,
14985            inherits,
14986            if_not_exists,
14987            foreign_keys,
14988            table_constraints,
14989            partition_by,
14990            partition_of: None,
14991        }))
14992    }
14993
14994    /// v7.37.6-B — case-insensitive ident match helper for the
14995    /// `PARTITION OF` / `MINVALUE` / `MAXVALUE` keywords. They lex
14996    /// as `Token::Ident("of"/"minvalue"/"maxvalue")` because we
14997    /// didn't burn a global keyword slot for each (see the
14998    /// `Token::Partition` doc-comment in `lexer.rs`).
14999    fn tokens_match_ident_ci(t: Option<&Token>, want: &str) -> bool {
15000        matches!(t, Some(Token::Ident(s) | Token::QuotedIdent(s)) if s.eq_ignore_ascii_case(want))
15001    }
15002
15003    /// v7.37.6-B — after `PARTITION BY`, expect `RANGE (key_col [, ...])`.
15004    /// v7.37.16 (16.1/16.2) — extended to LIST + HASH.
15005    fn parse_partition_by_tail(&mut self) -> Result<crate::ast::PartitionBySpec, ParseError> {
15006        use crate::ast::{PartitionBySpec, PartitionKindAst};
15007        let kind = match self.peek() {
15008            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("range") => {
15009                self.advance();
15010                PartitionKindAst::Range
15011            }
15012            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("list") => {
15013                self.advance();
15014                PartitionKindAst::List
15015            }
15016            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("hash") => {
15017                self.advance();
15018                PartitionKindAst::Hash
15019            }
15020            other => {
15021                return Err(self.err(format!(
15022                    "PARTITION BY: expected RANGE / LIST / HASH, got {other:?}"
15023                )));
15024            }
15025        };
15026        if !matches!(self.peek(), Token::LParen) {
15027            return Err(self.err(format!(
15028                "expected '(' after PARTITION BY <strategy>, got {:?}",
15029                self.peek()
15030            )));
15031        }
15032        self.advance();
15033        let mut key_columns = Vec::new();
15034        loop {
15035            key_columns.push(self.expect_ident_like()?);
15036            match self.peek() {
15037                Token::Comma => {
15038                    self.advance();
15039                }
15040                Token::RParen => {
15041                    self.advance();
15042                    break;
15043                }
15044                other => {
15045                    return Err(self.err(format!(
15046                        "expected ',' or ')' in PARTITION BY key list, got {other:?}"
15047                    )));
15048                }
15049            }
15050        }
15051        if key_columns.is_empty() {
15052            return Err(self.err("PARTITION BY requires at least one key column".to_string()));
15053        }
15054        Ok(PartitionBySpec { kind, key_columns })
15055    }
15056
15057    /// v7.37.6-B — after `PARTITION OF`, expect
15058    ///   <parent> FOR VALUES FROM ( <expr> ) TO ( <expr> )
15059    /// or
15060    ///   <parent> DEFAULT
15061    fn parse_partition_of_tail(&mut self) -> Result<crate::ast::PartitionOfSpec, ParseError> {
15062        use crate::ast::{PartitionOfBoundsAst, PartitionOfSpec};
15063        let parent_name = self.expect_ident_like()?;
15064        // v7.37.6-B rejects an explicit column list — the child
15065        // inherits from the parent. mailrs round-7 taught us that
15066        // CREATE TABLE-side schema reconciliation hides drift, so
15067        // we surface this as a parse error rather than silently
15068        // ignoring user columns.
15069        if matches!(self.peek(), Token::LParen) {
15070            return Err(self.err(
15071                "CREATE TABLE … PARTITION OF parent: explicit column list not supported \
15072                 at v7.37.6-B; the child inherits its columns from the parent"
15073                    .to_string(),
15074            ));
15075        }
15076        let bounds = match self.peek() {
15077            Token::Default => {
15078                self.advance();
15079                PartitionOfBoundsAst::Default
15080            }
15081            Token::For => {
15082                self.advance();
15083                if !matches!(self.peek(), Token::Values) {
15084                    return Err(
15085                        self.err(format!("expected VALUES after FOR, got {:?}", self.peek()))
15086                    );
15087                }
15088                self.advance();
15089                // WITH is not a reserved Token in the lexer — it lexes
15090                // as Token::Ident("with"). Disambiguate manually.
15091                let want_with = matches!(
15092                    self.peek(),
15093                    Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("with")
15094                );
15095                if want_with {
15096                    self.advance();
15097                    if !matches!(self.peek(), Token::LParen) {
15098                        return Err(self.err(format!(
15099                            "expected '(' after FOR VALUES WITH, got {:?}",
15100                            self.peek()
15101                        )));
15102                    }
15103                    self.advance();
15104                    let (mut modulus, mut remainder): (Option<u32>, Option<u32>) = (None, None);
15105                    loop {
15106                        let key = self.expect_ident_like()?;
15107                        let n = match self.peek().clone() {
15108                            Token::Integer(v) if u32::try_from(v).is_ok() => {
15109                                self.advance();
15110                                v as u32
15111                            }
15112                            other => {
15113                                return Err(self.err(format!(
15114                                    "FOR VALUES WITH: expected unsigned integer literal, got {other:?}"
15115                                )));
15116                            }
15117                        };
15118                        match key.to_ascii_uppercase().as_str() {
15119                            "MODULUS" => modulus = Some(n),
15120                            "REMAINDER" => remainder = Some(n),
15121                            other => {
15122                                return Err(self.err(format!(
15123                                    "FOR VALUES WITH: unknown key {other:?}; \
15124                                     expected MODULUS or REMAINDER"
15125                                )));
15126                            }
15127                        }
15128                        match self.peek() {
15129                            Token::Comma => {
15130                                self.advance();
15131                            }
15132                            Token::RParen => {
15133                                self.advance();
15134                                break;
15135                            }
15136                            other => {
15137                                return Err(self.err(format!(
15138                                    "expected ',' or ')' in FOR VALUES WITH list, got {other:?}"
15139                                )));
15140                            }
15141                        }
15142                    }
15143                    let modulus = modulus
15144                        .ok_or_else(|| self.err("FOR VALUES WITH: missing MODULUS".to_string()))?;
15145                    let remainder = remainder.ok_or_else(|| {
15146                        self.err("FOR VALUES WITH: missing REMAINDER".to_string())
15147                    })?;
15148                    if modulus == 0 {
15149                        return Err(self.err("FOR VALUES WITH: MODULUS must be > 0".to_string()));
15150                    }
15151                    if remainder >= modulus {
15152                        return Err(self.err(format!(
15153                            "FOR VALUES WITH: REMAINDER ({remainder}) \
15154                             must be < MODULUS ({modulus})"
15155                        )));
15156                    }
15157                    PartitionOfBoundsAst::Hash { modulus, remainder }
15158                } else {
15159                    match self.peek() {
15160                        Token::From => {
15161                            self.advance();
15162                            let lower = Box::new(self.parse_partition_bound_expr()?);
15163                            if !matches!(self.peek(), Token::To) {
15164                                return Err(self.err(format!(
15165                                    "expected TO after FROM (...), got {:?}",
15166                                    self.peek()
15167                                )));
15168                            }
15169                            self.advance();
15170                            let upper = Box::new(self.parse_partition_bound_expr()?);
15171                            PartitionOfBoundsAst::Range { lower, upper }
15172                        }
15173                        // v7.37.16 (16.1) — FOR VALUES IN (lit [, lit, …])
15174                        Token::In => {
15175                            self.advance();
15176                            if !matches!(self.peek(), Token::LParen) {
15177                                return Err(self.err(format!(
15178                                    "expected '(' after FOR VALUES IN, got {:?}",
15179                                    self.peek()
15180                                )));
15181                            }
15182                            self.advance();
15183                            let mut values = Vec::new();
15184                            loop {
15185                                values.push(self.parse_expr(0)?);
15186                                match self.peek() {
15187                                    Token::Comma => {
15188                                        self.advance();
15189                                    }
15190                                    Token::RParen => {
15191                                        self.advance();
15192                                        break;
15193                                    }
15194                                    other => {
15195                                        return Err(self.err(format!(
15196                                        "expected ',' or ')' in FOR VALUES IN list, got {other:?}"
15197                                    )));
15198                                    }
15199                                }
15200                            }
15201                            if values.is_empty() {
15202                                return Err(self.err(
15203                                    "FOR VALUES IN requires at least one literal".to_string(),
15204                                ));
15205                            }
15206                            PartitionOfBoundsAst::List { values }
15207                        }
15208                        other => {
15209                            return Err(self.err(format!(
15210                                "expected FROM / IN / WITH after FOR VALUES, got {other:?}"
15211                            )));
15212                        }
15213                    }
15214                }
15215            }
15216            other => {
15217                return Err(self.err(format!(
15218                    "expected FOR VALUES or DEFAULT after PARTITION OF parent, got {other:?}"
15219                )));
15220            }
15221        };
15222        Ok(PartitionOfSpec {
15223            parent_name,
15224            bounds,
15225        })
15226    }
15227
15228    /// v7.37.6-B — a single `( <expr> )` bound. `MINVALUE` /
15229    /// `MAXVALUE` lex as Ident; rewrite them into FunctionCall
15230    /// markers (no-arg builtins) so the engine resolves them
15231    /// against [`spg_storage::PartitionBound::{MinValue, MaxValue}`].
15232    fn parse_partition_bound_expr(&mut self) -> Result<crate::ast::Expr, ParseError> {
15233        if !matches!(self.peek(), Token::LParen) {
15234            return Err(self.err(format!(
15235                "expected '(' before partition bound, got {:?}",
15236                self.peek()
15237            )));
15238        }
15239        self.advance();
15240        let expr = match self.peek() {
15241            Token::Ident(s) | Token::QuotedIdent(s)
15242                if s.eq_ignore_ascii_case("minvalue") || s.eq_ignore_ascii_case("maxvalue") =>
15243            {
15244                let name = s.to_ascii_uppercase();
15245                self.advance();
15246                crate::ast::Expr::FunctionCall {
15247                    name,
15248                    args: Vec::new(),
15249                }
15250            }
15251            _ => self.parse_expr(0)?,
15252        };
15253        if !matches!(self.peek(), Token::RParen) {
15254            return Err(self.err(format!(
15255                "expected ')' after partition bound, got {:?}",
15256                self.peek()
15257            )));
15258        }
15259        self.advance();
15260        Ok(expr)
15261    }
15262
15263    /// v7.14.0 — true when the next tokens look like an inline
15264    /// MySQL index declaration: KEY / INDEX / UNIQUE KEY /
15265    /// UNIQUE INDEX / FULLTEXT [KEY|INDEX] / SPATIAL [KEY|INDEX]
15266    /// — each followed by an optional name + `(...)`. Critical:
15267    /// a column NAMED `key` / `index` (PG accepts as ident) must
15268    /// NOT be mistaken for the KEY constraint shape. We disambig
15269    /// by requiring the keyword to be followed by either `(` or
15270    /// `<ident> (`.
15271    fn peek_mysql_inline_key_start(&self) -> bool {
15272        let cur = self.peek();
15273        // Shapes:
15274        //   KEY (cols)
15275        //   KEY name (cols)
15276        //   INDEX (cols)
15277        //   INDEX name (cols)
15278        //   UNIQUE KEY [name] (cols)
15279        //   UNIQUE INDEX [name] (cols)
15280        //   FULLTEXT [KEY|INDEX] [name] (cols)
15281        //   SPATIAL [KEY|INDEX] [name] (cols)
15282        let after_keyword_followed_by_paren_or_ident_paren = |skip: usize| -> bool {
15283            // tokens at skip = the position AFTER the index-form
15284            // keywords (KEY/INDEX) have been consumed.
15285            match self.tokens.get(skip) {
15286                Some(Token::LParen) => true,
15287                Some(Token::Ident(_) | Token::QuotedIdent(_)) => {
15288                    matches!(self.tokens.get(skip + 1), Some(Token::LParen))
15289                }
15290                _ => false,
15291            }
15292        };
15293        // `INDEX` lexes as Token::Index (reserved), not as
15294        // Token::Ident("index"). Both shapes count as a KEY/INDEX
15295        // start; the peek helper below handles either.
15296        let is_key_or_index_tok = |t: &Token| -> bool {
15297            matches!(t, Token::Index)
15298                || matches!(t, Token::Ident(s) if s.eq_ignore_ascii_case("key") || s.eq_ignore_ascii_case("index"))
15299        };
15300        match cur {
15301            Token::Index => after_keyword_followed_by_paren_or_ident_paren(self.pos + 1),
15302            Token::Ident(s) if s.eq_ignore_ascii_case("key") || s.eq_ignore_ascii_case("index") => {
15303                after_keyword_followed_by_paren_or_ident_paren(self.pos + 1)
15304            }
15305            Token::Ident(s)
15306                if s.eq_ignore_ascii_case("fulltext") || s.eq_ignore_ascii_case("spatial") =>
15307            {
15308                let nxt = self.tokens.get(self.pos + 1);
15309                let after_after = if nxt.is_some_and(is_key_or_index_tok) {
15310                    self.pos + 2
15311                } else {
15312                    self.pos + 1
15313                };
15314                after_keyword_followed_by_paren_or_ident_paren(after_after)
15315            }
15316            Token::Ident(s) if s.eq_ignore_ascii_case("unique") => {
15317                let nxt = self.tokens.get(self.pos + 1);
15318                if !nxt.is_some_and(is_key_or_index_tok) {
15319                    return false;
15320                }
15321                after_keyword_followed_by_paren_or_ident_paren(self.pos + 2)
15322            }
15323            _ => false,
15324        }
15325    }
15326
15327    /// v7.14.0 — parse the MySQL inline KEY/INDEX form. Returns
15328    /// Some(TableConstraint::Unique) for UNIQUE KEY (so SPG
15329    /// enforces uniqueness on INSERT). v7.15.0: plain KEY/INDEX
15330    /// returns Some(TableConstraint::Index) so the engine builds
15331    /// a real BTree index on the leading column (mysqldump
15332    /// `KEY idx_posts_author (author_id)` shape).
15333    /// FULLTEXT / SPATIAL still return None — accepted-as-no-op
15334    /// (the storage layer has no matching AM).
15335    fn parse_mysql_inline_key(
15336        &mut self,
15337    ) -> Result<Option<crate::ast::TableConstraint>, ParseError> {
15338        // Detect UNIQUE prefix.
15339        let is_unique = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("unique"))
15340        {
15341            self.advance();
15342            true
15343        } else {
15344            false
15345        };
15346        // Consume FULLTEXT / SPATIAL prefix and record which one
15347        // it was. v7.17.0 Phase 2.2 — FULLTEXT routes through a
15348        // dedicated TableConstraint variant so the engine can
15349        // build a tsvector-GIN; SPATIAL still has no matching
15350        // AM, so it falls back to accept-as-no-op.
15351        let mut is_fulltext = false;
15352        let mut is_spatial = false;
15353        if let Token::Ident(s) = self.peek().clone() {
15354            if s.eq_ignore_ascii_case("fulltext") {
15355                self.advance();
15356                is_fulltext = true;
15357            } else if s.eq_ignore_ascii_case("spatial") {
15358                self.advance();
15359                is_spatial = true;
15360            }
15361        }
15362        // KEY / INDEX keyword. `INDEX` lexes as Token::Index
15363        // (reserved); accept either token shape.
15364        match self.peek() {
15365            Token::Index => {
15366                self.advance();
15367            }
15368            Token::Ident(s) if s.eq_ignore_ascii_case("key") || s.eq_ignore_ascii_case("index") => {
15369                self.advance();
15370            }
15371            other => {
15372                return Err(self.err(alloc::format!(
15373                    "expected KEY/INDEX in inline index declaration, got {other:?}"
15374                )));
15375            }
15376        }
15377        // Optional index name (an ident before the `(`).
15378        // v7.15.0 — capture the name when present so the engine
15379        // builds the secondary index under the user's chosen
15380        // name (matches mysqldump's `KEY idx_x (col)` shape).
15381        let mut idx_name: Option<String> = None;
15382        if matches!(self.peek(), Token::Ident(_) | Token::QuotedIdent(_))
15383            && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
15384        {
15385            if let Token::Ident(s) | Token::QuotedIdent(s) = self.advance() {
15386                idx_name = Some(s);
15387            }
15388        }
15389        // Optional `USING BTREE` / `USING HASH` (MySQL).
15390        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("using")) {
15391            self.advance();
15392            if matches!(self.peek(), Token::Ident(_) | Token::QuotedIdent(_)) {
15393                self.advance();
15394            }
15395        }
15396        // Required column list `(col [, col]*)`.
15397        if !matches!(self.peek(), Token::LParen) {
15398            return Err(self.err(alloc::format!(
15399                "expected '(' in inline KEY/INDEX, got {:?}",
15400                self.peek()
15401            )));
15402        }
15403        self.advance();
15404        let mut cols: Vec<String> = Vec::new();
15405        while let Token::Ident(s) | Token::QuotedIdent(s) = self.peek().clone() {
15406            self.advance();
15407            cols.push(s);
15408            // Skip optional `(length)` per-column prefix.
15409            if matches!(self.peek(), Token::LParen) {
15410                let mut depth = 1usize;
15411                self.advance();
15412                while depth > 0 {
15413                    match self.peek() {
15414                        Token::LParen => depth += 1,
15415                        Token::RParen => depth -= 1,
15416                        Token::Eof => break,
15417                        _ => {}
15418                    }
15419                    self.advance();
15420                }
15421            }
15422            // Skip optional ASC / DESC.
15423            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("asc") || s.eq_ignore_ascii_case("desc"))
15424                || matches!(self.peek(), Token::Asc | Token::Desc)
15425            {
15426                self.advance();
15427            }
15428            if matches!(self.peek(), Token::Comma) {
15429                self.advance();
15430                continue;
15431            }
15432            break;
15433        }
15434        if matches!(self.peek(), Token::RParen) {
15435            self.advance();
15436        }
15437        // Trailing options on the inline index — comment / etc.
15438        // Skip until comma or `)`.
15439        while !matches!(self.peek(), Token::Comma | Token::RParen | Token::Eof) {
15440            self.advance();
15441        }
15442        if cols.is_empty() {
15443            return Ok(None);
15444        }
15445        if is_unique {
15446            // Carry the captured idx_name on UNIQUE too so future
15447            // engine work can name the underlying BTree
15448            // accordingly; today the unique-constraint installer
15449            // synthesises the name itself, but Display round-trip
15450            // benefits from preserving it.
15451            Ok(Some(crate::ast::TableConstraint::Unique {
15452                name: idx_name,
15453                columns: cols,
15454                nulls_not_distinct: false,
15455                // MySQL inline UNIQUE KEY has no deferral vocabulary.
15456                deferrable: false,
15457                initially_deferred: false,
15458            }))
15459        } else if is_fulltext {
15460            // v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY` now
15461            // routes through `TableConstraint::FulltextIndex`;
15462            // the engine builds a tsvector-GIN over each named
15463            // column so MATCH AGAINST gets a real inverted
15464            // index instead of a silently-dropped declaration.
15465            Ok(Some(crate::ast::TableConstraint::FulltextIndex {
15466                name: idx_name,
15467                columns: cols,
15468            }))
15469        } else if is_spatial {
15470            // SPG has no native SPATIAL AM. Accept-as-no-op
15471            // (declaration is parsed, but no index is built).
15472            Ok(None)
15473        } else {
15474            // v7.15.0 — plain KEY / INDEX builds a real BTree
15475            // secondary index.
15476            Ok(Some(crate::ast::TableConstraint::Index {
15477                name: idx_name,
15478                columns: cols,
15479            }))
15480        }
15481    }
15482
15483    /// v7.14.0 — consume MySQL/MariaDB table-options tail after
15484    /// the closing `)`: ENGINE=..., DEFAULT CHARSET=...,
15485    /// COLLATE=..., AUTO_INCREMENT=N, ROW_FORMAT=..., COMMENT='...'
15486    /// (in any order, separated by whitespace).
15487    /// v7.38 (read01 P6.55) — consume and discard a PG `WITH (opt=val, …)`
15488    /// storage-parameter clause on CREATE TABLE. SPG has no per-table
15489    /// reloptions; accepting them keeps pg_dump restores working. `WITH` is a
15490    /// bare ident here, and only the parenthesised form is reloptions (so this
15491    /// never eats a `WITH DATA` / `WITH CHECK OPTION` trailer).
15492    fn consume_with_reloptions(&mut self) {
15493        let is_with = matches!(
15494            self.peek(),
15495            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("with")
15496        );
15497        if !is_with || !matches!(self.tokens.get(self.pos + 1), Some(Token::LParen)) {
15498            return;
15499        }
15500        self.advance(); // WITH
15501        self.advance(); // (
15502        let mut depth = 1u32;
15503        while depth > 0 && !matches!(self.peek(), Token::Eof) {
15504            match self.peek() {
15505                Token::LParen => depth += 1,
15506                Token::RParen => depth -= 1,
15507                _ => {}
15508            }
15509            self.advance();
15510        }
15511    }
15512
15513    /// v7.39 — returns the `ENGINE=` name, which used to be consumed and
15514    /// dropped with everything else here. The rest of the MySQL table
15515    /// options genuinely have no meaning for SPG's storage; the engine
15516    /// name does, because MySQL REFUSES one it does not know and a dump
15517    /// with a typo in it should not quietly become a table.
15518    fn consume_mysql_table_options(&mut self) -> Option<alloc::string::String> {
15519        let mut engine: Option<alloc::string::String> = None;
15520        loop {
15521            // Heuristic: a table option is an ident (or `DEFAULT`
15522            // reserved keyword) followed by `=` and an
15523            // ident / string / integer.
15524            let name_lc = match self.peek().clone() {
15525                Token::Ident(s) | Token::QuotedIdent(s) => s.to_ascii_lowercase(),
15526                Token::Default => alloc::string::String::from("default"),
15527                _ => break,
15528            };
15529            let known = matches!(
15530                name_lc.as_str(),
15531                "engine"
15532                    | "default"
15533                    | "charset"
15534                    | "collate"
15535                    | "auto_increment"
15536                    | "row_format"
15537                    | "comment"
15538                    | "pack_keys"
15539                    | "stats_persistent"
15540                    | "stats_auto_recalc"
15541                    | "stats_sample_pages"
15542                    | "key_block_size"
15543                    | "tablespace"
15544                    | "min_rows"
15545                    | "max_rows"
15546                    | "checksum"
15547                    | "delay_key_write"
15548                    | "insert_method"
15549                    | "data"
15550                    | "index"
15551                    | "encryption"
15552                    | "compression"
15553            );
15554            if !known {
15555                break;
15556            }
15557            self.advance(); // option name
15558            // `DEFAULT` optional prefix is followed by `CHARSET` /
15559            // `COLLATE`; consume the next ident too.
15560            if name_lc == "default" {
15561                if matches!(self.peek(), Token::Ident(_) | Token::QuotedIdent(_)) {
15562                    self.advance();
15563                }
15564            }
15565            if matches!(self.peek(), Token::Eq) {
15566                self.advance();
15567            }
15568            match self.peek().clone() {
15569                Token::Ident(v) | Token::QuotedIdent(v) | Token::String(v) => {
15570                    if name_lc == "engine" {
15571                        // v7.39.3 — as WRITTEN. MySQL 9.7.2 refuses an
15572                        // engine it does not know and names it back
15573                        // exactly: `Unknown storage engine 'NoSuchEng'`,
15574                        // measured. The lexer folds a bare identifier, so
15575                        // the message quoted a name the dump did not
15576                        // contain, which is the one thing that message is
15577                        // for. Guarded the same way the column spelling
15578                        // is: the span runs to the next token, so what
15579                        // comes back has to be the same word.
15580                        let written = self
15581                            .source_span(self.pos, self.pos)
15582                            .map(|raw| raw.trim().trim_matches('`').trim_matches('\''))
15583                            .filter(|raw| raw.eq_ignore_ascii_case(&v))
15584                            .map(alloc::string::String::from);
15585                        engine = Some(written.unwrap_or(v));
15586                    }
15587                    self.advance();
15588                }
15589                Token::Integer(_) => {
15590                    self.advance();
15591                }
15592                _ => {}
15593            }
15594        }
15595        engine
15596    }
15597
15598    /// v7.9.18 — true when the next tokens are `PRIMARY KEY (…)`.
15599    /// PRIMARY and KEY are bare idents; we look-ahead 2 to be
15600    /// sure (otherwise a column literally named `primary` would
15601    /// be mistaken).
15602    fn peek_table_level_pk_start(&self) -> bool {
15603        let cur = self.peek();
15604        let nxt = self.tokens.get(self.pos + 1);
15605        let nxt2 = self.tokens.get(self.pos + 2);
15606        let is_primary = matches!(cur, Token::Ident(s) if s.eq_ignore_ascii_case("primary"));
15607        let is_key = matches!(nxt, Some(Token::Ident(s)) if s.eq_ignore_ascii_case("key"));
15608        let is_lparen = matches!(nxt2, Some(Token::LParen));
15609        is_primary && is_key && is_lparen
15610    }
15611
15612    /// v7.9.18 — true when the next tokens are `UNIQUE (…)`.
15613    /// v7.13.0 — also matches `UNIQUE NULLS [NOT] DISTINCT (…)`
15614    /// (mailrs round-5 G10).
15615    fn peek_table_level_unique_start(&self) -> bool {
15616        let cur = self.peek();
15617        let is_unique = matches!(cur, Token::Ident(s) if s.eq_ignore_ascii_case("unique"));
15618        if !is_unique {
15619            return false;
15620        }
15621        let n1 = self.tokens.get(self.pos + 1);
15622        // Plain `UNIQUE (…)`.
15623        if matches!(n1, Some(Token::LParen)) {
15624            return true;
15625        }
15626        // `UNIQUE NULLS [NOT] DISTINCT (…)`.
15627        let is_nulls = matches!(n1, Some(Token::Ident(s)) if s.eq_ignore_ascii_case("nulls"));
15628        if !is_nulls {
15629            return false;
15630        }
15631        let n2 = self.tokens.get(self.pos + 2);
15632        let n3 = self.tokens.get(self.pos + 3);
15633        let n4 = self.tokens.get(self.pos + 4);
15634        // `UNIQUE NULLS DISTINCT (…)` — 4 tokens before `(`.
15635        if matches!(n2, Some(Token::Distinct)) && matches!(n3, Some(Token::LParen)) {
15636            return true;
15637        }
15638        // `UNIQUE NULLS NOT DISTINCT (…)` — 5 tokens before `(`.
15639        if matches!(n2, Some(Token::Not))
15640            && matches!(n3, Some(Token::Distinct))
15641            && matches!(n4, Some(Token::LParen))
15642        {
15643            return true;
15644        }
15645        false
15646    }
15647
15648    fn parse_table_level_primary_key(&mut self) -> Result<crate::ast::TableConstraint, ParseError> {
15649        self.advance(); // PRIMARY
15650        self.advance(); // KEY
15651        let columns = self.parse_paren_ident_list("PRIMARY KEY")?;
15652        // v7.39 (round 711) — the trailer's values are CARRIED now; round
15653        // 621 consumed and dropped them (the storing half of F08).
15654        let (deferrable, initially_deferred) = self.consume_deferrable_clauses_timed()?;
15655        Ok(crate::ast::TableConstraint::PrimaryKey {
15656            name: None,
15657            columns,
15658            deferrable,
15659            initially_deferred,
15660        })
15661    }
15662
15663    fn parse_table_level_unique(&mut self) -> Result<crate::ast::TableConstraint, ParseError> {
15664        self.advance(); // UNIQUE
15665        // v7.13.0 — optional `NULLS NOT DISTINCT` modifier
15666        // (mailrs round-5 G10, PG 15+ surface). Default behaviour
15667        // is `NULLS DISTINCT` per the SQL standard.
15668        let mut nulls_not_distinct = false;
15669        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("nulls")) {
15670            let n1 = self.tokens.get(self.pos + 1);
15671            let n2 = self.tokens.get(self.pos + 2);
15672            let is_not = matches!(n1, Some(Token::Not));
15673            let is_distinct = matches!(n2, Some(Token::Distinct));
15674            if is_not && is_distinct {
15675                self.advance(); // NULLS
15676                self.advance(); // NOT
15677                self.advance(); // DISTINCT
15678                nulls_not_distinct = true;
15679            } else if matches!(n1, Some(Token::Distinct)) {
15680                self.advance(); // NULLS
15681                self.advance(); // DISTINCT
15682            }
15683        }
15684        let columns = self.parse_paren_ident_list("UNIQUE")?;
15685        let (deferrable, initially_deferred) = self.consume_deferrable_clauses_timed()?;
15686        Ok(crate::ast::TableConstraint::Unique {
15687            name: None,
15688            columns,
15689            nulls_not_distinct,
15690            deferrable,
15691            initially_deferred,
15692        })
15693    }
15694
15695    /// v7.13.0 — table-level `CHECK (<expr>)` constraint
15696    /// (mailrs round-5 G3). Consumes `CHECK` then a parenthesised
15697    /// expression.
15698    /// v7.39 (round 210) — `EXCLUDE [USING <method>] ( <col> WITH <op>
15699    /// [, <col> WITH <op>]* ) [WHERE (...)]`. The operator is read as a
15700    /// standalone token spelling (`&&`, `=`, `@>`, `<@`, `&<`, `&>`).
15701    /// v7.39 (round 652) — the optional `NOT VALID` suffix on a
15702    /// constraint added by ALTER TABLE. `NOT` alone is not enough to
15703    /// commit: `NOT` starts no other suffix here, but reading both
15704    /// tokens before advancing keeps the caller's error message intact
15705    /// if someone writes `NOT NULL` by mistake.
15706    fn parse_not_valid_suffix(&mut self) -> bool {
15707        if !matches!(self.peek(), Token::Not) {
15708            return false;
15709        }
15710        if !matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("valid"))
15711        {
15712            return false;
15713        }
15714        self.advance();
15715        self.advance();
15716        true
15717    }
15718
15719    fn parse_table_level_exclude(&mut self) -> Result<crate::ast::TableConstraint, ParseError> {
15720        self.advance(); // EXCLUDE
15721        // Optional `USING <method>`.
15722        let mut method = None;
15723        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("using")) {
15724            self.advance();
15725            method = Some(match self.advance() {
15726                Token::Ident(s) | Token::QuotedIdent(s) => s.to_ascii_lowercase(),
15727                other => {
15728                    return Err(self.err(alloc::format!(
15729                        "expected index method after USING, got {other:?}"
15730                    )));
15731                }
15732            });
15733        }
15734        if !matches!(self.peek(), Token::LParen) {
15735            return Err(self.err(alloc::format!(
15736                "expected '(' after EXCLUDE, got {:?}",
15737                self.peek()
15738            )));
15739        }
15740        self.advance();
15741        let mut elements: Vec<(String, String)> = Vec::new();
15742        loop {
15743            let col = match self.advance() {
15744                Token::Ident(s) | Token::QuotedIdent(s) => s,
15745                other => {
15746                    return Err(self.err(alloc::format!(
15747                        "expected column name in EXCLUDE, got {other:?}"
15748                    )));
15749                }
15750            };
15751            if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("with")) {
15752                return Err(self.err(alloc::format!(
15753                    "expected WITH after EXCLUDE column, got {:?}",
15754                    self.peek()
15755                )));
15756            }
15757            self.advance();
15758            let op = match self.advance() {
15759                Token::InetOverlap => String::from("&&"),
15760                Token::Intersects => String::from("?#"),
15761                Token::IsBelow => String::from("<^"),
15762                Token::IsAbove => String::from(">^"),
15763                Token::PatternLt => String::from("~<~"),
15764                Token::PatternLtEq => String::from("~<=~"),
15765                Token::PatternGt => String::from("~>~"),
15766                Token::PatternGtEq => String::from("~>=~"),
15767                Token::TsMatchOld => String::from("@@@"),
15768                Token::Eq => String::from("="),
15769                Token::JsonContains => String::from("@>"),
15770                Token::JsonContainedBy => String::from("<@"),
15771                Token::OverLeft => String::from("&<"),
15772                Token::OverRight => String::from("&>"),
15773                other => {
15774                    return Err(self.err(alloc::format!(
15775                        "unsupported EXCLUDE operator {other:?} (SPG supports &&, =, @>, <@, &<, &>)"
15776                    )));
15777                }
15778            };
15779            elements.push((col, op));
15780            if matches!(self.peek(), Token::Comma) {
15781                self.advance();
15782                continue;
15783            }
15784            break;
15785        }
15786        if !matches!(self.peek(), Token::RParen) {
15787            return Err(self.err(alloc::format!(
15788                "expected ')' to close EXCLUDE, got {:?}",
15789                self.peek()
15790            )));
15791        }
15792        self.advance();
15793        Ok(crate::ast::TableConstraint::Exclude {
15794            name: None,
15795            method,
15796            elements,
15797        })
15798    }
15799
15800    fn parse_table_level_check(&mut self) -> Result<crate::ast::TableConstraint, ParseError> {
15801        self.advance(); // CHECK
15802        if !matches!(self.peek(), Token::LParen) {
15803            return Err(self.err(alloc::format!(
15804                "expected '(' after CHECK, got {:?}",
15805                self.peek()
15806            )));
15807        }
15808        self.advance();
15809        let expr = self.parse_expr(0)?;
15810        if !matches!(self.peek(), Token::RParen) {
15811            return Err(self.err(alloc::format!(
15812                "expected ')' to close CHECK predicate, got {:?}",
15813                self.peek()
15814            )));
15815        }
15816        self.advance();
15817        // A CHECK written inside CREATE TABLE cannot be NOT VALID: there
15818        // are no existing rows for PG to skip, so it rejects the suffix.
15819        Ok(crate::ast::TableConstraint::Check {
15820            name: None,
15821            expr,
15822            not_valid: false,
15823        })
15824    }
15825
15826    /// v7.13.0 — `true` when the next token is `CHECK` (a bare ident).
15827    fn peek_table_level_check_start(&self) -> bool {
15828        matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("check"))
15829    }
15830
15831    /// v7.22 (round-13 gap 5) — `Some(kind)` when the next tokens are
15832    /// `CONSTRAINT <name> { CHECK | UNIQUE | PRIMARY }`. FOREIGN stays
15833    /// on the dedicated FK path (`parse_table_level_fk` consumes its
15834    /// own CONSTRAINT prefix).
15835    fn peek_named_table_constraint_kind(&self) -> Option<NamedTableConstraintKind> {
15836        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("constraint")) {
15837            return None;
15838        }
15839        // tokens[pos+1] is the constraint name (any ident-like);
15840        // tokens[pos+2] is the kind keyword.
15841        match self.tokens.get(self.pos + 2) {
15842            Some(Token::Ident(s)) if s.eq_ignore_ascii_case("check") => {
15843                Some(NamedTableConstraintKind::Check)
15844            }
15845            Some(Token::Ident(s)) if s.eq_ignore_ascii_case("unique") => {
15846                Some(NamedTableConstraintKind::Unique)
15847            }
15848            Some(Token::Ident(s)) if s.eq_ignore_ascii_case("primary") => {
15849                Some(NamedTableConstraintKind::PrimaryKey)
15850            }
15851            Some(Token::Ident(s)) if s.eq_ignore_ascii_case("exclude") => {
15852                Some(NamedTableConstraintKind::Exclude)
15853            }
15854            _ => None,
15855        }
15856    }
15857
15858    fn parse_paren_ident_list(&mut self, ctx: &str) -> Result<Vec<String>, ParseError> {
15859        if !matches!(self.peek(), Token::LParen) {
15860            return Err(self.err(alloc::format!(
15861                "expected '(' after {ctx}, got {:?}",
15862                self.peek()
15863            )));
15864        }
15865        self.advance();
15866        let mut out = Vec::new();
15867        loop {
15868            out.push(self.expect_ident_like()?);
15869            match self.peek() {
15870                Token::Comma => {
15871                    self.advance();
15872                }
15873                Token::RParen => {
15874                    self.advance();
15875                    break;
15876                }
15877                other => {
15878                    return Err(self.err(alloc::format!(
15879                        "expected ',' or ')' in {ctx} list, got {other:?}"
15880                    )));
15881                }
15882            }
15883        }
15884        if out.is_empty() {
15885            return Err(self.err(alloc::format!("{ctx} requires at least one column")));
15886        }
15887        Ok(out)
15888    }
15889
15890    /// v7.6.0 — true when the next tokens are `CONSTRAINT <name>
15891    /// FOREIGN KEY` or bare `FOREIGN KEY`. Both introduce a
15892    /// table-level FK; a column def never starts with either keyword
15893    /// (column names are not in this reserved set).
15894    fn peek_constraint_or_fk_start(&self) -> bool {
15895        let is_constraint_kw = matches!(
15896            self.peek(),
15897            Token::Ident(s) if s.eq_ignore_ascii_case("constraint")
15898        );
15899        let is_foreign_kw = matches!(
15900            self.peek(),
15901            Token::Ident(s) if s.eq_ignore_ascii_case("foreign")
15902        );
15903        is_constraint_kw || is_foreign_kw
15904    }
15905
15906    /// v7.6.0 — parse a table-level FK clause:
15907    /// `[CONSTRAINT <name>] FOREIGN KEY (<col>[,<col>]*) REFERENCES
15908    /// <tbl> [(<pcol>[,<pcol>]*)] [ON DELETE <action>] [ON UPDATE <action>]`.
15909    fn parse_table_level_fk(&mut self) -> Result<ForeignKeyConstraint, ParseError> {
15910        let mut name: Option<String> = None;
15911        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("constraint")) {
15912            self.advance();
15913            name = Some(self.expect_ident_like()?);
15914        }
15915        // `FOREIGN`
15916        match self.advance() {
15917            Token::Ident(s) if s.eq_ignore_ascii_case("foreign") => {}
15918            other => return Err(self.err(format!("expected FOREIGN, got {other:?}"))),
15919        }
15920        // `KEY`
15921        match self.advance() {
15922            Token::Ident(s) if s.eq_ignore_ascii_case("key") => {}
15923            other => return Err(self.err(format!("expected KEY after FOREIGN, got {other:?}"))),
15924        }
15925        // `(col, col, ...)`
15926        if !matches!(self.peek(), Token::LParen) {
15927            return Err(self.err(format!(
15928                "expected '(' after FOREIGN KEY, got {:?}",
15929                self.peek()
15930            )));
15931        }
15932        self.advance();
15933        let mut columns = Vec::new();
15934        loop {
15935            columns.push(self.expect_ident_like()?);
15936            match self.peek() {
15937                Token::Comma => {
15938                    self.advance();
15939                }
15940                Token::RParen => {
15941                    self.advance();
15942                    break;
15943                }
15944                other => {
15945                    return Err(self.err(format!(
15946                        "expected ',' or ')' in FK column list, got {other:?}"
15947                    )));
15948                }
15949            }
15950        }
15951        if columns.is_empty() {
15952            return Err(self.err("FOREIGN KEY requires at least one column".into()));
15953        }
15954        let (
15955            parent_table,
15956            parent_columns,
15957            on_delete,
15958            on_update,
15959            match_type,
15960            deferrable,
15961            initially_deferred,
15962        ) = self.parse_references_tail(columns.len())?;
15963        Ok(ForeignKeyConstraint {
15964            name,
15965            columns,
15966            parent_table,
15967            parent_columns,
15968            on_delete,
15969            on_update,
15970            match_type,
15971            deferrable,
15972            initially_deferred,
15973        })
15974    }
15975
15976    /// v7.6.0 — parse the tail `REFERENCES <tbl> [(<pcol>...)] [ON
15977    /// DELETE <action>] [ON UPDATE <action>]`. `expected_arity` is
15978    /// the local column count, used to default the parent column
15979    /// list when omitted (SQL spec: parent's PK is implied).
15980    fn parse_references_tail(
15981        &mut self,
15982        expected_arity: usize,
15983    ) -> Result<
15984        (
15985            String,
15986            Vec<String>,
15987            FkAction,
15988            FkAction,
15989            crate::ast::MatchType,
15990            // v7.39 (round 288) — deferrable, initially_deferred.
15991            bool,
15992            bool,
15993        ),
15994        ParseError,
15995    > {
15996        match self.advance() {
15997            Token::Ident(s) if s.eq_ignore_ascii_case("references") => {}
15998            other => return Err(self.err(format!("expected REFERENCES, got {other:?}"))),
15999        }
16000        let parent_table = self.expect_ident_like()?;
16001        let mut parent_columns: Vec<String> = Vec::new();
16002        if matches!(self.peek(), Token::LParen) {
16003            self.advance();
16004            loop {
16005                parent_columns.push(self.expect_ident_like()?);
16006                match self.peek() {
16007                    Token::Comma => {
16008                        self.advance();
16009                    }
16010                    Token::RParen => {
16011                        self.advance();
16012                        break;
16013                    }
16014                    other => {
16015                        return Err(self.err(format!(
16016                            "expected ',' or ')' in REFERENCES column list, got {other:?}"
16017                        )));
16018                    }
16019                }
16020            }
16021        }
16022        if !parent_columns.is_empty() && parent_columns.len() != expected_arity {
16023            return Err(self.err(format!(
16024                "FK arity mismatch: {} local column(s) vs {} parent column(s)",
16025                expected_arity,
16026                parent_columns.len()
16027            )));
16028        }
16029        // Optional `MATCH {SIMPLE | FULL | PARTIAL}`. PG's grammar puts
16030        // it between the referenced column list and the ON / DEFERRABLE
16031        // trailers. SPG implements MATCH SIMPLE semantics (the FK check
16032        // is skipped when any referencing column is NULL), so SIMPLE —
16033        // the default, and the only spelling pg_dump emits — is accepted
16034        // as a no-op. MATCH FULL / MATCH PARTIAL need the per-FK
16035        // mixed-NULL rule, which is not wired yet; reject them honestly
16036        // rather than silently applying SIMPLE (PG itself errors on
16037        // MATCH PARTIAL as "not yet implemented").
16038        let mut match_type = crate::ast::MatchType::Simple;
16039        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("match")) {
16040            self.advance();
16041            // `FULL` is a reserved keyword token (FULL OUTER JOIN);
16042            // SIMPLE / PARTIAL arrive as bare identifiers.
16043            let kind = match self.advance() {
16044                Token::Full => "FULL".to_string(),
16045                Token::Ident(s) => s.to_uppercase(),
16046                other => {
16047                    return Err(self.err(format!(
16048                        "expected FULL, PARTIAL or SIMPLE after MATCH, got {other:?}"
16049                    )));
16050                }
16051            };
16052            match kind.as_str() {
16053                "SIMPLE" => {} // Default — match_type stays Simple.
16054                // v7.38 (read01, T29) — MATCH FULL: the check is skipped only
16055                // when ALL referencing columns are NULL; a mixed-NULL key errors.
16056                "FULL" => match_type = crate::ast::MatchType::Full,
16057                "PARTIAL" => {
16058                    return Err(self.err("MATCH PARTIAL not yet implemented".to_string()));
16059                }
16060                _ => {
16061                    return Err(self.err(format!(
16062                        "expected FULL, PARTIAL or SIMPLE after MATCH, got {kind}"
16063                    )));
16064                }
16065            }
16066        }
16067        // v7.6.7 / v7.17.0 Phase 3.1 — interleave `[NOT] DEFERRABLE
16068        // [INITIALLY {DEFERRED | IMMEDIATE}]` and `ON DELETE
16069        // <action>` / `ON UPDATE <action>` in either order. PG /
16070        // pg_dump emits the timing clause AFTER the ON clauses
16071        // (`ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED`),
16072        // but the SQL spec allows either order. We loop over
16073        // every possible trailer and dispatch on the next token,
16074        // stopping when nothing matches. Phase 3.1 changes the
16075        // bare DEFERRABLE form from hard-error to accept-as-
16076        // immediate; SPG is single-writer with no deferred-
16077        // constraint window so the runtime semantics are always
16078        // immediate even when INITIALLY DEFERRED is requested.
16079        // PG's default referential action (no ON DELETE / ON UPDATE
16080        // clause) is NO ACTION, not RESTRICT — the two enforce
16081        // identically in SPG (single-writer, no deferred window; see the
16082        // shared match arm in constraints.rs) but information_schema.
16083        // referential_constraints must report NO ACTION to match PG.
16084        let mut on_delete = FkAction::NoAction;
16085        let mut on_update = FkAction::NoAction;
16086        let mut seen_on_delete = false;
16087        let mut seen_on_update = false;
16088        let mut deferrable = false;
16089        let mut initially_deferred = false;
16090        loop {
16091            // DEFERRABLE / NOT DEFERRABLE / INITIALLY shapes.
16092            let before = self.pos;
16093            let (d, idef) = self.consume_deferrable_clauses_timed()?;
16094            if self.pos != before {
16095                deferrable = d;
16096                initially_deferred = idef;
16097                continue;
16098            }
16099            // ON DELETE / ON UPDATE.
16100            if !matches!(self.peek(), Token::On) {
16101                break;
16102            }
16103            self.advance();
16104            let which = self.advance();
16105            let action = self.parse_fk_action()?;
16106            match which {
16107                Token::Ident(ref s) if s.eq_ignore_ascii_case("delete") => {
16108                    if seen_on_delete {
16109                        return Err(self.err("ON DELETE specified twice".into()));
16110                    }
16111                    seen_on_delete = true;
16112                    on_delete = action;
16113                }
16114                Token::Ident(ref s) if s.eq_ignore_ascii_case("update") => {
16115                    if seen_on_update {
16116                        return Err(self.err("ON UPDATE specified twice".into()));
16117                    }
16118                    seen_on_update = true;
16119                    on_update = action;
16120                }
16121                other => {
16122                    return Err(
16123                        self.err(format!("expected DELETE or UPDATE after ON, got {other:?}"))
16124                    );
16125                }
16126            }
16127        }
16128        Ok((
16129            parent_table,
16130            parent_columns,
16131            on_delete,
16132            on_update,
16133            match_type,
16134            deferrable,
16135            initially_deferred,
16136        ))
16137    }
16138
16139    /// v7.6.0 — parse `CASCADE | RESTRICT | SET NULL | SET DEFAULT |
16140    /// NO ACTION`.
16141    fn parse_fk_action(&mut self) -> Result<FkAction, ParseError> {
16142        match self.advance() {
16143            Token::Ident(s) if s.eq_ignore_ascii_case("cascade") => Ok(FkAction::Cascade),
16144            Token::Ident(s) if s.eq_ignore_ascii_case("restrict") => Ok(FkAction::Restrict),
16145            Token::Ident(s) if s.eq_ignore_ascii_case("set") => match self.advance() {
16146                Token::Null => Ok(FkAction::SetNull),
16147                Token::Default => Ok(FkAction::SetDefault),
16148                other => Err(self.err(format!(
16149                    "expected NULL or DEFAULT after SET in FK action, got {other:?}"
16150                ))),
16151            },
16152            Token::Ident(s) if s.eq_ignore_ascii_case("no") => match self.advance() {
16153                Token::Ident(s) if s.eq_ignore_ascii_case("action") => Ok(FkAction::NoAction),
16154                other => Err(self.err(format!(
16155                    "expected ACTION after NO in FK action, got {other:?}"
16156                ))),
16157            },
16158            other => Err(self.err(format!(
16159                "expected CASCADE | RESTRICT | SET NULL | SET DEFAULT | NO ACTION, got {other:?}"
16160            ))),
16161        }
16162    }
16163
16164    /// Recognise the optional `IF NOT EXISTS` prefix shared by `CREATE
16165    /// TABLE` and `CREATE INDEX`. Returns `true` if consumed.
16166    fn consume_if_not_exists(&mut self) -> bool {
16167        // `IF` arrives as a bare Ident (we don't reserve it because it
16168        // also appears mid-expression in PG, though we don't support
16169        // those forms yet).
16170        let looks_like_if = matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("if"));
16171        if !looks_like_if {
16172            return false;
16173        }
16174        // Peek one ahead before committing: only consume IF when it's
16175        // actually `IF NOT EXISTS`.
16176        if !matches!(self.tokens.get(self.pos + 1), Some(Token::Not)) {
16177            return false;
16178        }
16179        if !matches!(
16180            self.tokens.get(self.pos + 2),
16181            Some(Token::Ident(s)) if s.eq_ignore_ascii_case("exists")
16182        ) {
16183            return false;
16184        }
16185        self.advance(); // IF
16186        self.advance(); // NOT
16187        self.advance(); // EXISTS
16188        true
16189    }
16190
16191    /// v7.12.4 — `IF EXISTS` modifier for DROP statements.
16192    /// Consumes IF EXISTS as a pair; returns false otherwise
16193    /// without consuming any tokens.
16194    /// v7.39 (RLS) — consume the `ROW LEVEL SECURITY` keyword triple after
16195    /// ENABLE/DISABLE/FORCE/NO FORCE.
16196    fn expect_row_level_security(&mut self) -> Result<(), ParseError> {
16197        for kw in ["row", "level", "security"] {
16198            if !matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case(kw))
16199            {
16200                return Err(self.err(alloc::format!(
16201                    "expected {} in ROW LEVEL SECURITY, got {:?}",
16202                    kw.to_ascii_uppercase(),
16203                    self.peek()
16204                )));
16205            }
16206            self.advance();
16207        }
16208        Ok(())
16209    }
16210
16211    fn consume_if_exists(&mut self) -> bool {
16212        let looks_like_if = matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("if"));
16213        if !looks_like_if {
16214            return false;
16215        }
16216        if !matches!(
16217            self.tokens.get(self.pos + 1),
16218            Some(Token::Ident(s)) if s.eq_ignore_ascii_case("exists")
16219        ) {
16220            return false;
16221        }
16222        self.advance(); // IF
16223        self.advance(); // EXISTS
16224        true
16225    }
16226
16227    /// v7.9.14 — consume `ASC | DESC | NULLS FIRST | NULLS LAST`
16228    /// qualifiers after an index column ref. ASC / DESC are
16229    /// reserved tokens; NULLS / FIRST / LAST are bare idents.
16230    /// We accept and discard them since single-column BTree
16231    /// stores rows in natural key order today.
16232    /// v7.24 (round-16 A) — `NULLS FIRST` / `NULLS LAST` after an
16233    /// ORDER BY key. Returns None when absent.
16234    fn parse_optional_nulls_placement(&mut self) -> Result<Option<bool>, ParseError> {
16235        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("nulls")) {
16236            return Ok(None);
16237        }
16238        self.advance();
16239        match self.advance() {
16240            Token::Ident(s) if s.eq_ignore_ascii_case("first") => Ok(Some(true)),
16241            Token::Ident(s) if s.eq_ignore_ascii_case("last") => Ok(Some(false)),
16242            other => Err(self.err(alloc::format!(
16243                "expected FIRST or LAST after NULLS, got {other:?}"
16244            ))),
16245        }
16246    }
16247
16248    /// v7.39 (round 537) — the per-column ordering clause, REPORTED now
16249    /// rather than discarded.
16250    ///
16251    /// SPG's index does not scan in a direction — column ordering is
16252    /// intrinsic to the storage — but `pg_indexes.indexdef` is a
16253    /// reproduction of the DDL, and dropping the clause meant
16254    /// `CREATE INDEX i ON t (a DESC NULLS LAST)` read back as `(a)`. A
16255    /// dump lost it, and a schema diff saw drift on every run.
16256    fn consume_optional_index_column_qualifiers(&mut self) -> crate::ast::IndexColumnOrder {
16257        let mut order = crate::ast::IndexColumnOrder::default();
16258        loop {
16259            match self.peek() {
16260                Token::Asc => {
16261                    self.advance();
16262                }
16263                Token::Desc => {
16264                    order.descending = true;
16265                    self.advance();
16266                }
16267                Token::Ident(s) if s.eq_ignore_ascii_case("nulls") => {
16268                    let look = self.tokens.get(self.pos + 1);
16269                    if matches!(
16270                        look,
16271                        Some(Token::Ident(k)) if k.eq_ignore_ascii_case("first")
16272                            || k.eq_ignore_ascii_case("last")
16273                    ) {
16274                        self.advance();
16275                        order.nulls_first = Some(matches!(
16276                            self.advance(),
16277                            Token::Ident(k) if k.eq_ignore_ascii_case("first")
16278                        ));
16279                    } else {
16280                        break;
16281                    }
16282                }
16283                _ => break,
16284            }
16285        }
16286        order
16287    }
16288
16289    fn parse_create_index_stmt_after_create(
16290        &mut self,
16291        is_unique: bool,
16292    ) -> Result<Statement, ParseError> {
16293        // Caller consumed CREATE (and the optional UNIQUE); we're on INDEX.
16294        debug_assert!(matches!(self.peek(), Token::Index));
16295        self.advance();
16296        // v7.37.17 (17.6 partial) — CONCURRENTLY noise word (PG 8.2+).
16297        // SPG's CREATE INDEX is synchronous end-to-end today (real
16298        // CONCURRENTLY variant with restartable scans queues with
16299        // v7.39 indexes epic), so the modifier has no runtime effect
16300        // — same accept-and-no-op shape as v7.37.16.5 DETACH
16301        // PARTITION CONCURRENTLY and v7.37.19.8 REFRESH MATERIALIZED
16302        // VIEW CONCURRENTLY.
16303        let mut concurrently = false;
16304        if matches!(
16305            self.peek(),
16306            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("concurrently")
16307        ) {
16308            self.advance();
16309            concurrently = true;
16310        }
16311        let if_not_exists = self.consume_if_not_exists();
16312        // v7.39 (read01 round 93) — the index name is optional (PG since
16313        // forever): `CREATE INDEX ON t (a)` lets the server pick a name.
16314        // When the token after `[IF NOT EXISTS]` is already `ON`, no name
16315        // was given; leave it empty and the engine derives a PG-style
16316        // `<table>_<cols>_idx` name at CREATE time (with collision counter).
16317        let name = if matches!(self.peek(), Token::On) {
16318            String::new()
16319        } else {
16320            self.expect_ident_like()?
16321        };
16322        if !matches!(self.peek(), Token::On) {
16323            return Err(self.err(format!(
16324                "expected ON after CREATE INDEX <name>, got {:?}",
16325                self.peek()
16326            )));
16327        }
16328        self.advance();
16329        let table = self.expect_ident_like()?;
16330        // Optional `USING <method>` — only recognised method in v2.0 is
16331        // `hnsw` (a single-layer NSW graph for kNN). `USING` is the bare
16332        // ident `using` (we don't promote it to a reserved keyword
16333        // because it isn't reserved anywhere else in our SQL surface).
16334        let mut method_name: Option<String> = None;
16335        let method = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("using")) {
16336            self.advance();
16337            let m = self.expect_ident_like()?;
16338            method_name = Some(m.to_ascii_lowercase());
16339            match m.to_ascii_lowercase().as_str() {
16340                "hnsw" => IndexMethod::Hnsw,
16341                "btree" => IndexMethod::BTree,
16342                "brin" => IndexMethod::Brin,
16343                // v7.12.3 — real GIN inverted index over `tsvector`.
16344                // v7.9.26b's `USING gin` → BTree silent fallback is
16345                // gone; the engine validates that the indexed column
16346                // is `tsvector` at CREATE INDEX time.
16347                "gin" => IndexMethod::Gin,
16348                // v7.9.26b — PG `pg_dump` emits `USING gist` /
16349                // `USING spgist` / `USING hash` for their built-in
16350                // AMs that SPG doesn't have a matching
16351                // implementation for; degrade to BTree on the
16352                // leading column so the schema loads + the index
16353                // catalogue stays consistent. Operator pays the
16354                // planner cost only for the queries that would have
16355                // used the specialised AM.
16356                "gist" | "spgist" | "hash" => IndexMethod::BTree,
16357                // v7.11.3 — pgvector ships both `ivfflat` and
16358                // `hnsw`. Customers shouldn't have to choose
16359                // their on-disk index method based on what SPG
16360                // implements; accept `ivfflat` as a synonym for
16361                // `hnsw` so PG schemas using either method drop
16362                // in. The vector distance op (`<->` / `<#>` /
16363                // `<=>`) at query time still picks the metric.
16364                "ivfflat" => IndexMethod::Hnsw,
16365                other => {
16366                    return Err(self.err(alloc::format!(
16367                        "unknown index method {other:?}; supported: hnsw, btree, brin, gin (gist/spgist/hash accepted as BTree fallback)"
16368                    )));
16369                }
16370            }
16371        } else {
16372            IndexMethod::BTree
16373        };
16374        if !matches!(self.peek(), Token::LParen) {
16375            return Err(self.err(format!(
16376                "expected '(' before indexed column, got {:?}",
16377                self.peek()
16378            )));
16379        }
16380        self.advance();
16381        // v6.8.2 — accept either a bare column ident (legacy) or
16382        // an expression `fn(col, …)` for expression indexes.
16383        // Distinguish by peeking the token *after* the current
16384        // ident: `ident )` is the legacy column-only path;
16385        // anything else triggers the Pratt expression parser.
16386        // (`advance()` uses `mem::replace` to nil out the current
16387        // slot, so we can't save+rewind cleanly — peek-ahead via
16388        // direct index avoids the mutation.)
16389        let mut opclass: Option<String> = None;
16390        let mut key_collation: Option<String> = None;
16391        let (column, expression): (String, Option<Expr>) = match self.peek().clone() {
16392            // Single column with `)` immediately after — fast path.
16393            // v7.9.29 — also: bare column followed by `,` (the
16394            // multi-column form `(a, b, c)`). Without this branch
16395            // the leading ident gets pulled into `parse_expr`
16396            // which then sets `expression = Some(Column(a))` and
16397            // breaks Display round-trip on the multi-column shape.
16398            Token::Ident(s) | Token::QuotedIdent(s)
16399                if matches!(
16400                    self.tokens.get(self.pos + 1),
16401                    Some(Token::RParen | Token::Comma)
16402                ) =>
16403            {
16404                self.advance();
16405                (s, None)
16406            }
16407            // v7.9.22 — single column followed by a pgvector
16408            // opclass ident: `(col vector_cosine_ops)`. mailrs G5.
16409            // v7.15.0 — capture the opclass instead of discarding
16410            // it so the engine can dispatch (e.g. `gin_trgm_ops`
16411            // → real trigram-shingle GIN over a TEXT column).
16412            // Vector/HNSW opclasses still take their distance
16413            // metric from the query operator (`<->` / `<#>` /
16414            // `<=>`), so for those callers the opclass stays
16415            // informational.
16416            // v7.22 (mailrs round-13 gap 7) — pg_dump qualifies the
16417            // opclass: `(embedding public.vector_cosine_ops)`. Strip
16418            // the schema and dispatch on the bare opclass, the same
16419            // treatment table/type names get.
16420            Token::Ident(s) | Token::QuotedIdent(s)
16421                if matches!(
16422                    self.tokens.get(self.pos + 1),
16423                    Some(Token::Ident(_) | Token::QuotedIdent(_))
16424                ) && matches!(self.tokens.get(self.pos + 2), Some(Token::Dot))
16425                    && matches!(
16426                        self.tokens.get(self.pos + 3),
16427                        Some(Token::Ident(op) | Token::QuotedIdent(op))
16428                            if is_vector_opclass_name(op)
16429                    ) =>
16430            {
16431                self.advance(); // column name
16432                self.advance(); // schema qualifier
16433                self.advance(); // dot
16434                let op_tok = self.advance();
16435                if let Token::Ident(op) | Token::QuotedIdent(op) = op_tok {
16436                    opclass = Some(op.to_ascii_lowercase());
16437                }
16438                (s, None)
16439            }
16440            // r1038 — an operator class is recognised by its POSITION, not
16441            // by a list of names. It used to be `is_vector_opclass_name`,
16442            // so `USING gin (doc jsonb_path_ops)` — ordinary PG, and what
16443            // sentori's migration wrote — was a syntax error while
16444            // `USING gin (doc)` parsed. Anything sitting between a column
16445            // name and a `,` `)` ASC DESC NULLS COLLATE is an opclass;
16446            // two bare identifiers in a row are not valid there otherwise.
16447            Token::Ident(s) | Token::QuotedIdent(s)
16448                if matches!(
16449                    self.tokens.get(self.pos + 1),
16450                    Some(Token::Ident(op) | Token::QuotedIdent(op))
16451                        if is_vector_opclass_name(op) || Self::opclass_position_follows(
16452                            self.tokens.get(self.pos + 2)
16453                        )
16454                ) =>
16455            {
16456                self.advance(); // column name
16457                // Capture the opclass token, lower-cased for
16458                // case-insensitive engine dispatch.
16459                let op_tok = self.advance();
16460                if let Token::Ident(op) | Token::QuotedIdent(op) = op_tok {
16461                    opclass = Some(op.to_ascii_lowercase());
16462                }
16463                (s, None)
16464            }
16465            Token::Ident(_) | Token::QuotedIdent(_) => {
16466                // v7.39 (round 538) — an explicit COLLATE on the key,
16467                // read by LOOKAHEAD because `parse_expr` absorbs the
16468                // clause as a no-op (SPG orders text by bytes, which is
16469                // the C collation, so it changes nothing to honour). PG
16470                // still PRINTS it: an explicitly written `"C"` and the
16471                // collation a column inherits are different collation
16472                // OBJECTS even where they sort identically, which is why
16473                // `(a COLLATE "C")` shows on a C-collation database too.
16474                if matches!(
16475                    self.tokens.get(self.pos + 1),
16476                    Some(Token::Ident(w)) if w.eq_ignore_ascii_case("collate")
16477                ) {
16478                    key_collation = match self.tokens.get(self.pos + 2) {
16479                        Some(Token::Ident(n) | Token::QuotedIdent(n) | Token::String(n)) => {
16480                            Some(n.clone())
16481                        }
16482                        _ => None,
16483                    };
16484                }
16485                // v7.39.2 — the clause is read by the LOOKAHEAD above and
16486                // belongs to the KEY, not to the expression. Since
16487                // `COLLATE` became a node, letting `parse_expr` build one
16488                // here put the collation in twice and the key deparsed as
16489                // `(c COLLATE "C" COLLATE "C")`. The ORDER-BY-key channel
16490                // is the same idea and already exists, so this borrows it:
16491                // absorb into the side channel, and the key's own
16492                // lookahead is what carries it.
16493                // v7.39.2 — and the key can only CARRY the byte-order
16494                // spellings. Absorbing into the side channel accepts any
16495                // name, so suppressing the node here without this check
16496                // silently accepted `(name COLLATE "en_US")`, which SPG's
16497                // index cannot honour — a refusal that was doing real
16498                // work, removed by the suppression and put back here.
16499                if let Some(name) = &key_collation {
16500                    let lc = name.to_ascii_lowercase();
16501                    let byte_order = matches!(
16502                        lc.as_str(),
16503                        "c" | "posix" | "default" | "ucs_basic" | "pg_c_utf8"
16504                    );
16505                    let mysql_ok = self.mysql_dialect
16506                        && (lc.ends_with("_ci")
16507                            || lc.ends_with("_bin")
16508                            || lc == "binary"
16509                            || matches!(lc.as_str(), "case_insensitive" | "nocase"));
16510                    if !byte_order && !mysql_ok {
16511                        return Err(self.err(alloc::format!(
16512                            "COLLATE {name:?} is not supported in this position: an index \
16513                             key carries the byte-order spellings only. Declare it on the \
16514                             column (`x text COLLATE {name:?}`) instead"
16515                        )));
16516                    }
16517                }
16518                let saved_key_ctx = self.in_order_by_key;
16519                self.in_order_by_key = true;
16520                let key_expr = self.parse_expr(0);
16521                self.in_order_by_key = saved_key_ctx;
16522                let key_expr = key_expr?;
16523                let primary = extract_first_column(&key_expr).ok_or_else(|| {
16524                    self.err("expression index key must reference at least one column".into())
16525                })?;
16526                (primary, Some(key_expr))
16527            }
16528            // v7.37.43-T4 — parenthesised expression index key
16529            // `CREATE INDEX … ON t ((payload->'bundle'->>'id'))`.
16530            // PG's CREATE INDEX requires the expression to be in
16531            // its own parens to disambiguate function calls from
16532            // column lists, so this `LParen` is the inner open-paren
16533            // of an expression key. parse_expr handles the recursive
16534            // descent and consumes the matching `RParen`.
16535            Token::LParen => {
16536                let key_expr = self.parse_expr(0)?;
16537                let primary = extract_first_column(&key_expr).ok_or_else(|| {
16538                    self.err("expression index key must reference at least one column".into())
16539                })?;
16540                (primary, Some(key_expr))
16541            }
16542            other => {
16543                return Err(self.err(format!(
16544                    "expected column ident or expression, got {other:?}"
16545                )));
16546            }
16547        };
16548        // v7.9.14 — accept extra comma-separated columns inside
16549        // the index key parens (`CREATE INDEX … (a, b, c)`).
16550        // mailrs F2. Each extra column may carry an optional
16551        // `ASC` / `DESC` / `NULLS FIRST` / `NULLS LAST` clause
16552        // — parsed and discarded; SPG doesn't honour direction
16553        // on a BTree index today (column ordering is intrinsic
16554        // to the storage). v7.10 will widen to genuine composite
16555        // index keys.
16556        let mut extra_columns: Vec<String> = Vec::new();
16557        // The leading column may also have ASC/DESC after it — and that
16558        // one is the column SPG indexes, so its clause is kept.
16559        let key_order = self.consume_optional_index_column_qualifiers();
16560        while matches!(self.peek(), Token::Comma) {
16561            self.advance();
16562            let extra = self.expect_ident_like()?;
16563            let _ = self.consume_optional_index_column_qualifiers();
16564            extra_columns.push(extra);
16565        }
16566        if !matches!(self.peek(), Token::RParen) {
16567            return Err(self.err(format!(
16568                "expected ')' after indexed column / expression, got {:?}",
16569                self.peek()
16570            )));
16571        }
16572        self.advance();
16573        // v6.8.0 — optional `INCLUDE (col1, col2, …)` clause for
16574        // index-only-scan annotation. Bare ident (not a reserved
16575        // keyword) so we test by case-insensitive string match.
16576        let included_columns = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("include"))
16577        {
16578            self.advance();
16579            if !matches!(self.peek(), Token::LParen) {
16580                return Err(self.err(format!("expected '(' after INCLUDE, got {:?}", self.peek())));
16581            }
16582            self.advance();
16583            let mut cols = Vec::new();
16584            loop {
16585                cols.push(self.expect_ident_like()?);
16586                match self.peek() {
16587                    Token::Comma => {
16588                        self.advance();
16589                    }
16590                    Token::RParen => {
16591                        self.advance();
16592                        break;
16593                    }
16594                    other => {
16595                        return Err(self.err(format!(
16596                            "expected ',' or ')' in INCLUDE list, got {other:?}"
16597                        )));
16598                    }
16599                }
16600            }
16601            cols
16602        } else {
16603            Vec::new()
16604        };
16605        // v7.11.3 — accept and discard PG `WITH (k = v, ...)` index
16606        // storage parameters. pgvector emits `WITH (lists = N)` for
16607        // ivfflat and `WITH (m = N, ef_construction = M)` for hnsw;
16608        // SPG's HNSW picks its own parameters today (tunable via
16609        // env vars), so the WITH clause is informational and dropped.
16610        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("with")) {
16611            self.advance();
16612            if !matches!(self.peek(), Token::LParen) {
16613                return Err(self.err(format!(
16614                    "expected '(' after WITH in CREATE INDEX, got {:?}",
16615                    self.peek()
16616                )));
16617            }
16618            self.advance();
16619            loop {
16620                if matches!(self.peek(), Token::RParen) {
16621                    self.advance();
16622                    break;
16623                }
16624                // Drain `key = value` or bare `key` tokens.
16625                let _ = self.advance(); // key
16626                if matches!(self.peek(), Token::Eq) {
16627                    self.advance();
16628                    let _ = self.advance(); // value (int / string / ident)
16629                }
16630                match self.peek() {
16631                    Token::Comma => {
16632                        self.advance();
16633                    }
16634                    Token::RParen => {
16635                        self.advance();
16636                        break;
16637                    }
16638                    other => {
16639                        return Err(self.err(format!(
16640                            "expected ',' or ')' in WITH (…) clause, got {other:?}"
16641                        )));
16642                    }
16643                }
16644            }
16645        }
16646        // v7.39 (read01 round 52) — optional `NULLS [NOT] DISTINCT` (PG 15+),
16647        // which sits between the key list and the WHERE clause.
16648        let mut nulls_not_distinct = false;
16649        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("nulls")) {
16650            let n1 = self.tokens.get(self.pos + 1);
16651            let n2 = self.tokens.get(self.pos + 2);
16652            if matches!(n1, Some(Token::Not)) && matches!(n2, Some(Token::Distinct)) {
16653                self.advance(); // NULLS
16654                self.advance(); // NOT
16655                self.advance(); // DISTINCT
16656                nulls_not_distinct = true;
16657            } else if matches!(n1, Some(Token::Distinct)) {
16658                self.advance(); // NULLS
16659                self.advance(); // DISTINCT
16660            }
16661        }
16662        // v6.8.1 — optional `WHERE <expr>` partial-index predicate.
16663        let partial_predicate = if matches!(self.peek(), Token::Where) {
16664            self.advance();
16665            Some(self.parse_expr(0)?)
16666        } else {
16667            None
16668        };
16669        // v7.9.29 — UNIQUE on a vector index (HNSW) makes no
16670        // sense: uniqueness over an ANN structure has no clean
16671        // semantics. Reject early. (BRIN UNIQUE is similarly
16672        // meaningless — block both.)
16673        if is_unique && !matches!(method, IndexMethod::BTree) {
16674            return Err(self.err(alloc::format!(
16675                "UNIQUE is only supported on BTree indexes, got USING {:?}",
16676                method
16677            )));
16678        }
16679        Ok(Statement::CreateIndex(CreateIndexStatement {
16680            concurrently,
16681            name,
16682            key_order,
16683            key_collation,
16684            table,
16685            column,
16686            nulls_not_distinct,
16687            method,
16688            if_not_exists,
16689            included_columns,
16690            partial_predicate,
16691            extra_columns: extra_columns.clone(),
16692            expression,
16693            is_unique,
16694            opclass,
16695            method_name,
16696        }))
16697    }
16698
16699    /// v7.6.0 — wraps `parse_column_def` and consumes an optional
16700    /// column-level `REFERENCES ...` clause. The trailing FK is
16701    /// normalised into table-level shape (single-element columns +
16702    /// parent_columns) so the engine sees one uniform constraint list.
16703    fn parse_column_def_with_fk(
16704        &mut self,
16705    ) -> Result<(ColumnDef, Option<ForeignKeyConstraint>), ParseError> {
16706        let col = self.parse_column_def()?;
16707        // v7.39 (round 308, V29) — an explicitly named inline FK:
16708        // `col INT CONSTRAINT fk_a REFERENCES tbl(pcol)`. The column-def
16709        // loop leaves this spelling intact precisely so the name can be
16710        // kept here; PG reports it in violation messages and matches it
16711        // in `SET CONSTRAINTS`.
16712        let declared_name = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("constraint"))
16713        {
16714            self.advance();
16715            Some(self.expect_ident_like()?)
16716        } else {
16717            None
16718        };
16719        // Inline form: `col INT REFERENCES tbl(pcol) [ON DELETE ...] [ON UPDATE ...]`.
16720        let inline_references = matches!(
16721            self.peek(),
16722            Token::Ident(s) if s.eq_ignore_ascii_case("references")
16723        );
16724        if !inline_references {
16725            return Ok((col, None));
16726        }
16727        let (
16728            parent_table,
16729            parent_columns,
16730            on_delete,
16731            on_update,
16732            match_type,
16733            deferrable,
16734            initially_deferred,
16735        ) = self.parse_references_tail(1)?;
16736        let fk = ForeignKeyConstraint {
16737            name: declared_name,
16738            columns: vec![col.name.clone()],
16739            parent_table,
16740            parent_columns,
16741            on_delete,
16742            on_update,
16743            match_type,
16744            deferrable,
16745            initially_deferred,
16746        };
16747        Ok((col, Some(fk)))
16748    }
16749
16750    /// v7.13.0 — parse a column type (consuming the type ident and
16751    /// any trailing parameters / `[]`), without surrounding column
16752    /// constraints. Used by ALTER COLUMN TYPE (mailrs round-5 G8).
16753    /// Returns the resolved `ColumnTypeName` plus implied
16754    /// `(auto_increment, not_null)` flags from PG SERIAL family
16755    /// shorthands — callers that don't expect those (ALTER COLUMN
16756    /// TYPE) can discard them.
16757    fn parse_column_type_name(&mut self) -> Result<ColumnTypeName, ParseError> {
16758        let (ty, _, _, _, _, _, _, _, _, _, _, _, _, _) = self.parse_type_with_implied_flags()?;
16759        Ok(ty)
16760    }
16761
16762    #[allow(clippy::type_complexity)]
16763    fn parse_type_with_implied_flags(
16764        &mut self,
16765    ) -> Result<
16766        (
16767            ColumnTypeName,
16768            bool,
16769            bool,
16770            Option<String>,
16771            Collation,
16772            // v7.39 (round 370, M4 P4a) — was `COLLATE` written explicitly?
16773            bool,
16774            // v7.39 (round 676) — the collation NAME as written, which the
16775            // `Collation` enum above cannot carry.
16776            Option<String>,
16777            bool,
16778            // v7.17.0 Phase 3.P0-36 — MySQL inline ENUM variant
16779            // list captured at type-parse time. None for all
16780            // non-ENUM types.
16781            Option<Vec<String>>,
16782            // v7.17.0 Phase 3.P0-37 — MySQL inline SET variant
16783            // list. Distinct from ENUM (subset semantics).
16784            Option<Vec<String>>,
16785            // v7.39 (round 386, epic P1) — declared TINYINT / MEDIUMINT
16786            // width, lost when the type collapses to SmallInt / Int.
16787            Option<MysqlIntWidth>,
16788            // v7.39 (round 424) — declared fractional-seconds precision of a
16789            // MySQL temporal column (bare spelling = 0). None under PG.
16790            Option<u8>,
16791            // v7.39.2 — written `TIMESTAMP` rather than `DATETIME`. The
16792            // two are different types on MySQL and SPG stores both as
16793            // `Timestamp`, so the spelling has to travel separately or
16794            // a dump silently rewrites the column.
16795            bool,
16796            // v7.39.3 — a MySQL `FLOAT(m,d)` / `DOUBLE(m,d)` pair. Not a
16797            // display hint: it rounds on write.
16798            Option<(u8, u8)>,
16799        ),
16800        ParseError,
16801    > {
16802        let mut ty_ident = match self.advance() {
16803            Token::Ident(s) => s,
16804            // v7.37.5 β-P2 — `INTERVAL` lexes as a reserved keyword
16805            // (Token::Interval) since v7.9.25 to drive the `INTERVAL
16806            // '<span>'` literal grammar. As a column type it lands
16807            // here directly; downstream resolution still uses the
16808            // canonical lowercase string.
16809            Token::Interval => "interval".to_string(),
16810            other => {
16811                return Err(ParseError {
16812                    message: format!("expected column type, got {other:?}"),
16813                    token_pos: self.consumed_pos(),
16814                });
16815            }
16816        };
16817        // v7.22 (mailrs round-13 gap 4) — schema-qualified type names:
16818        // pg_dump qualifies extension types (`public.vector(1024)`).
16819        // SPG is single-namespace; drop the schema and resolve the
16820        // bare type — same treatment table names already get.
16821        while matches!(self.peek(), Token::Dot) {
16822            self.advance();
16823            ty_ident = self.expect_ident_like()?;
16824        }
16825        let mut implied_auto_increment = false;
16826        let mut implied_not_null = false;
16827        let mut user_type_ref: Option<String> = None;
16828        // v7.17.0 Phase 3.P0-36 — MySQL inline ENUM('a','b','c')
16829        // value list, captured here and bubbled up through the
16830        // ColumnDef so the engine can attach it to the column
16831        // schema (and validate INSERT cells against it).
16832        let mut inline_enum_variants: Option<Vec<String>> = None;
16833        // v7.17.0 Phase 3.P0-37 — MySQL inline SET variant list.
16834        let mut inline_set_variants: Option<Vec<String>> = None;
16835        // v7.39 (round 386, type-fidelity epic P1) — the declared MySQL
16836        // narrow-int width (TINYINT / MEDIUMINT), captured before the type
16837        // collapses to SmallInt / Int. Only under the MySQL dialect.
16838        let mut mysql_int_width: Option<MysqlIntWidth> = None;
16839        // v7.39 (round 424) — the declared fractional-seconds precision of a
16840        // MySQL temporal column. Set by the temporal arms below; stays None
16841        // for PG (whose temporal columns keep full microseconds).
16842        let mut mysql_fsp: Option<u8> = None;
16843        let mut mysql_declared_timestamp = false;
16844        let mut mysql_float_md: Option<(u8, u8)> = None;
16845        let mut ty = match ty_ident.as_str() {
16846            // PG SERIAL family. Implies NOT NULL + AUTO_INCREMENT.
16847            "smallserial" | "serial2" => {
16848                implied_auto_increment = true;
16849                implied_not_null = true;
16850                ColumnTypeName::SmallInt
16851            }
16852            "serial" | "serial4" => {
16853                implied_auto_increment = true;
16854                implied_not_null = true;
16855                ColumnTypeName::Int
16856            }
16857            "bigserial" | "serial8" => {
16858                implied_auto_increment = true;
16859                implied_not_null = true;
16860                ColumnTypeName::BigInt
16861            }
16862            // MySQL flavours we accept by aliasing to the closest SPG
16863            // type. TINYINT covers MySQL's i8 — held inside SMALLINT
16864            // since SPG doesn't have a dedicated i8. MEDIUMINT (MySQL
16865            // 24-bit) → INT. UNSIGNED modifiers are consumed below
16866            // without semantic effect.
16867            // v7.38 (read01 P4.19-sibling) — `int2` / `int4` / `int8` are
16868            // PG's internal type names; pg_dump and hand-written PG schemas
16869            // use them interchangeably with smallint / int / bigint (the cast
16870            // path already accepted them, only the column grammar didn't).
16871            "smallint" | "int2" => {
16872                // v7.14.0 — MySQL display-width on integers
16873                // (`SMALLINT(5)`, `INT(11)`, `BIGINT(20)`). The
16874                // parenthesised number is purely cosmetic — it
16875                // doesn't change storage. Accept + discard.
16876                self.consume_optional_paren_size();
16877                ColumnTypeName::SmallInt
16878            }
16879            // v7.17.0 Phase 4.3 — MySQL `TINYINT(1)` is the
16880            // canonical encoding for BOOLEAN. Every MySQL driver
16881            // (JDBC `tinyInt1isBit=true`, PHP `mysql_field_type`,
16882            // .NET `MySqlConnection`, sqlx) maps it to bit. Pre-
16883            // 4.3 SPG classified TINYINT(1) as SmallInt, which
16884            // gave the customer i16-shaped values where the app
16885            // expected bool — a Tier-A silent type drift on
16886            // mysqldump restores. Now: `TINYINT(1)` → Bool;
16887            // `TINYINT` (no width) and `TINYINT(N)` for N ≠ 1
16888            // stay SmallInt (the legacy width-agnostic path).
16889            "tinyint" => {
16890                let width = self.peek_optional_paren_size_value();
16891                self.consume_optional_paren_size();
16892                if width == Some(1) {
16893                    ColumnTypeName::Bool
16894                } else {
16895                    // v7.39 (round 386, epic P1) — TINYINT is i8; record the
16896                    // lost width so the write path can enforce -128..127.
16897                    if self.mysql_dialect {
16898                        mysql_int_width = Some(MysqlIntWidth::Tiny);
16899                    }
16900                    ColumnTypeName::SmallInt
16901                }
16902            }
16903            "mediumint" => {
16904                self.consume_optional_paren_size();
16905                // v7.39 (round 386, epic P1) — MEDIUMINT is 24-bit; record it.
16906                if self.mysql_dialect {
16907                    mysql_int_width = Some(MysqlIntWidth::Medium);
16908                }
16909                ColumnTypeName::Int
16910            }
16911            "int" | "integer" | "int4" => {
16912                self.consume_optional_paren_size();
16913                ColumnTypeName::Int
16914            }
16915            "bigint" | "int8" => {
16916                self.consume_optional_paren_size();
16917                ColumnTypeName::BigInt
16918            }
16919            // v7.13.0 — `DOUBLE PRECISION` (PG canonical spelling)
16920            // (mailrs round-5 G6). Consume the optional `PRECISION`
16921            // tail when the type keyword was `double` / `DOUBLE`.
16922            //
16923            // v7.39 (round 269) — REAL is 32-bit, not "the same as our
16924            // FLOAT". `FLOAT(p)` picks the width the way PG does:
16925            // p in 1..=24 is real, 25..=53 is double precision, and
16926            // anything else is an error.
16927            "float" | "double" | "real" => {
16928                if ty_ident.eq_ignore_ascii_case("double")
16929                    && matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("precision"))
16930                {
16931                    self.advance();
16932                }
16933                if ty_ident.eq_ignore_ascii_case("real") {
16934                    // v7.39 (round 274) — the two dialects genuinely
16935                    // disagree: PG's REAL is 4-byte, MySQL's REAL is a
16936                    // synonym for DOUBLE (8-byte). Round 269 made REAL
16937                    // 32-bit globally and thereby narrowed the stored
16938                    // precision of every MySQL REAL column.
16939                    if self.mysql_dialect {
16940                        ColumnTypeName::Float
16941                    } else {
16942                        ColumnTypeName::Real
16943                    }
16944                } else if self.mysql_dialect
16945                    && matches!(self.peek(), Token::LParen)
16946                    && self.peek_paren_has_comma()
16947                {
16948                    // v7.39 (round 360) — MySQL's `FLOAT(m,d)` / `DOUBLE(m,d)`
16949                    // display form (`FLOAT(10,2)`), which PG has no
16950                    // equivalent of. It was `syntax error at or near ","`,
16951                    // so the whole CREATE failed.
16952                    //
16953                    // v7.39.2 — the guard said `float` while the comment
16954                    // said both, so `DOUBLE(10,2)` — which every legacy
16955                    // MySQL schema uses for money — still failed the
16956                    // whole CREATE with `syntax error at or near "("`.
16957                    // Measured on 9.7.2: both forms are accepted, and the
16958                    // digits are NOT a display hint, they round on write
16959                    // (3.14159265358979 into either stores 3.14). The
16960                    // rounding is recorded as a residual; accepting the
16961                    // syntax and keeping the width is the half this
16962                    // change makes.
16963                    // v7.39.3 — keep the pair. The digits are not a
16964                    // display hint: MySQL 9.7.2 ROUNDS on write and
16965                    // refuses a value wider than `m` (errno 1264), so a
16966                    // column declared for money held more precision here
16967                    // than its schema said.
16968                    let (m, d) = self.parse_optional_numeric_params()?;
16969                    mysql_float_md = Some((
16970                        u8::try_from(m).unwrap_or(u8::MAX),
16971                        u8::try_from(d.max(0)).unwrap_or(u8::MAX),
16972                    ));
16973                    if ty_ident.eq_ignore_ascii_case("float") {
16974                        ColumnTypeName::Real
16975                    } else {
16976                        ColumnTypeName::Float
16977                    }
16978                } else if ty_ident.eq_ignore_ascii_case("float")
16979                    && matches!(self.peek(), Token::LParen)
16980                {
16981                    // PG words the two bounds differently, and
16982                    // parse_paren_size already rejects a zero.
16983                    let p = self.parse_paren_size("FLOAT")?;
16984                    if p > 53 {
16985                        return Err(self.err(String::from(
16986                            "precision for type float must be less than 54 bits",
16987                        )));
16988                    }
16989                    if p <= 24 {
16990                        ColumnTypeName::Real
16991                    } else {
16992                        ColumnTypeName::Float
16993                    }
16994                } else if ty_ident.eq_ignore_ascii_case("float") && self.mysql_dialect {
16995                    // v7.39.2 — MySQL's bare FLOAT is FOUR bytes; PG's is
16996                    // eight (it is `float8`'s spelling there). SPG used
16997                    // PG's for both, so a MySQL FLOAT column silently
16998                    // kept more precision than MySQL does — measured,
16999                    // 3.14159265358979 comes back as 3.14159 there and
17000                    // came back whole here — and reported itself as
17001                    // `double` to every reflection.
17002                    //
17003                    // This is the mirror of the REAL split above: the
17004                    // two dialects disagree about which spelling means
17005                    // which width, and one of them was already honoured.
17006                    ColumnTypeName::Real
17007                } else {
17008                    ColumnTypeName::Float
17009                }
17010            }
17011            // v7.13.0 — `FLOAT8` (PG short form) maps the same as FLOAT.
17012            "float4" => ColumnTypeName::Real,
17013            "float8" => ColumnTypeName::Float,
17014            "text" => ColumnTypeName::Text,
17015            // v7.39 (round 360) — MySQL's sized TEXT and BLOB families.
17016            // `LONGTEXT`, `BLOB` and `VARBINARY` appear in nearly every
17017            // real MySQL schema and NONE of them existed: the CREATE
17018            // failed outright with `type "blob" does not exist`, so the
17019            // table was never made. The sizes differ only in MySQL's
17020            // maximum length, which SPG does not cap, so they collapse
17021            // onto TEXT and BYTEA the way the unsized spellings do.
17022            "tinytext" | "mediumtext" | "longtext" => ColumnTypeName::Text,
17023            "blob" | "tinyblob" | "mediumblob" | "longblob" => ColumnTypeName::Bytes,
17024            // `VARBINARY(n)` / `BINARY(n)` — a length that SPG does not
17025            // enforce, consumed so the declaration parses.
17026            "varbinary" | "binary" => {
17027                self.consume_optional_paren_size();
17028                ColumnTypeName::Bytes
17029            }
17030            "name" => ColumnTypeName::Name,
17031            "xid" => ColumnTypeName::Xid,
17032            "oid" => ColumnTypeName::Oid,
17033            "xid8" => ColumnTypeName::Xid8,
17034            "bool" | "boolean" => ColumnTypeName::Bool,
17035            // v7.39 (round 620) — an UNBOUNDED `varchar` is the same type as
17036            // an unbounded `character varying`, which the arm below has always
17037            // read as text. Only the short spelling demanded a length, so
17038            // `CREATE TABLE t (x VARCHAR)` — as ordinary a line of DDL as
17039            // there is — failed on `VARCHAR type requires (N)` while the long
17040            // spelling of the same thing was accepted. The same asymmetry
17041            // round 613 closed on the CAST side, here on the DDL side.
17042            "varchar" => {
17043                if matches!(self.peek(), Token::LParen) {
17044                    ColumnTypeName::Varchar(self.parse_paren_size("VARCHAR")?)
17045                } else {
17046                    ColumnTypeName::Text
17047                }
17048            }
17049            // v7.39 (bpchar epic) — bare `char` = char(1), same as bare
17050            // `character` below (SQL standard).
17051            "char" => {
17052                if matches!(self.peek(), Token::LParen) {
17053                    ColumnTypeName::Char(self.parse_paren_size("CHAR")?)
17054                } else {
17055                    ColumnTypeName::Char(1)
17056                }
17057            }
17058            // pg_dump's canonical spellings: `character varying(n)` = varchar,
17059            // `character(n)` = char, bare `character` = char(1). Unbounded
17060            // `character varying` maps to text.
17061            "character" => {
17062                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("varying")) {
17063                    self.advance();
17064                    if matches!(self.peek(), Token::LParen) {
17065                        ColumnTypeName::Varchar(self.parse_paren_size("VARCHAR")?)
17066                    } else {
17067                        ColumnTypeName::Text
17068                    }
17069                } else if matches!(self.peek(), Token::LParen) {
17070                    ColumnTypeName::Char(self.parse_paren_size("CHAR")?)
17071                } else {
17072                    ColumnTypeName::Char(1)
17073                }
17074            }
17075            "vector" => {
17076                let dim = self.parse_paren_size("VECTOR")?;
17077                let encoding = self.parse_optional_vector_encoding()?;
17078                ColumnTypeName::Vector { dim, encoding }
17079            }
17080            // v7.39 (round 345, M5) — `DECIMAL` and `DEC` are the SQL
17081            // standard's own spellings of NUMERIC, and PG 18.4 accepts both
17082            // (measured: `DECIMAL(10,2)` and `DEC(5,1)` both report as
17083            // `numeric`). Only `NUMERIC` parsed, so `CREATE TABLE t (a
17084            // DECIMAL(10,2))` — how nearly every money column is written,
17085            // in either dialect — was a syntax error and the table was
17086            // never created. `FIXED` is MySQL's alias alone, so it is
17087            // taken only in that dialect.
17088            "numeric" | "decimal" | "dec" => {
17089                let (precision, scale) = self.parse_optional_numeric_params()?;
17090                ColumnTypeName::Numeric(precision, scale)
17091            }
17092            "fixed" if self.mysql_dialect => {
17093                let (precision, scale) = self.parse_optional_numeric_params()?;
17094                ColumnTypeName::Numeric(precision, scale)
17095            }
17096            "date" => ColumnTypeName::Date,
17097            // MySQL's `DATETIME` is the same domain as standard
17098            // `TIMESTAMP` — accept both spellings.
17099            "timestamp" | "datetime" => {
17100                // pg_dump emits `TIMESTAMP(6) WITH TIME ZONE` — the optional
17101                // fractional-seconds precision comes BEFORE the `WITH/WITHOUT
17102                // TIME ZONE` clause, so consume it first.
17103                // v7.39 (round 424) — under MySQL the precision is SEMANTIC
17104                // (it truncates on write and pads on render), so capture it;
17105                // a bare spelling means precision 0 there. PG stores µs always
17106                // and keeps `None`.
17107                let n = self.take_optional_paren_size();
17108                if self.mysql_dialect {
17109                    mysql_fsp = Some(n.unwrap_or(0).min(6));
17110                    // v7.39.2 — remember WHICH spelling was written.
17111                    // MySQL and MariaDB keep `timestamp` and `datetime`
17112                    // apart everywhere a client can read the type back,
17113                    // and SPG reported `datetime` for both — so a dump
17114                    // and reload silently changed the column's declared
17115                    // type, and MySQL's TIMESTAMP is not DATETIME (a
17116                    // different range, and UTC conversion on the way in
17117                    // and out).
17118                    mysql_declared_timestamp = ty_ident.eq_ignore_ascii_case("timestamp");
17119                }
17120                // v7.14.0 — PG canonical `TIMESTAMP WITH TIME ZONE`
17121                // / `TIMESTAMP WITHOUT TIME ZONE`. pg_dump emits
17122                // the full form. SPG canonicalises:
17123                //   - WITH TIME ZONE    → Timestamptz
17124                //   - WITHOUT TIME ZONE → Timestamp
17125                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("with"))
17126                    && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("time"))
17127                    && matches!(self.tokens.get(self.pos + 2), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("zone"))
17128                {
17129                    self.advance(); // WITH
17130                    self.advance(); // TIME
17131                    self.advance(); // ZONE
17132                    ColumnTypeName::Timestamptz
17133                } else if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("without"))
17134                    && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("time"))
17135                    && matches!(self.tokens.get(self.pos + 2), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("zone"))
17136                {
17137                    self.advance(); // WITHOUT
17138                    self.advance(); // TIME
17139                    self.advance(); // ZONE
17140                    ColumnTypeName::Timestamp
17141                } else {
17142                    // A second `(precision)` cannot legally follow, but the
17143                    // old grammar tolerated it; keep that tolerance.
17144                    self.consume_optional_paren_size();
17145                    ColumnTypeName::Timestamp
17146                }
17147            }
17148            // v7.9.2 — `TIMESTAMPTZ` and full PG spelling
17149            // `TIMESTAMP WITH TIME ZONE`. Same storage as TIMESTAMP;
17150            // only PG-wire OID differs.
17151            "timestamptz" => {
17152                self.consume_optional_paren_size();
17153                ColumnTypeName::Timestamptz
17154            }
17155            // v4.9: JSON / JSONB. Stored as raw text — no parse-time
17156            // validation. We accept the JSONB spelling too because
17157            // most PG clients default to it; SPG doesn't distinguish
17158            // the two (no path-operator perf advantage to model).
17159            "json" => ColumnTypeName::Json,
17160            "jsonb" => ColumnTypeName::Jsonb,
17161            // v7.10.4 — PG `BYTEA` and the SPG `BYTES` alias both
17162            // surface here. Same storage shape; mapping happens at
17163            // the engine side via the ColumnTypeName → DataType
17164            // resolver. Literal forms are handled at coerce_value
17165            // time so the lexer stays untouched.
17166            "bytea" | "bytes" => ColumnTypeName::Bytes,
17167            // v7.17.0 Phase 7 — PG network address types
17168            // v7.17.0 had a Text-backed fallback here for
17169            // `inet` / `cidr` / `macaddr`. v7.37.5 ζ-A promoted
17170            // each to a first-class type; the keywords are
17171            // bound below in the ζ-A block.
17172            // v7.12.0 — PG full-text search types. mailrs G-CRIT-3.
17173            // The actual `to_tsvector` / `@@` / `ts_rank` surface
17174            // arrives in v7.12.1+; the type itself loads here so
17175            // mailrs's `scripts/init-schema.sql` runs unmodified.
17176            "tsvector" => ColumnTypeName::TsVector,
17177            "tsquery" => ColumnTypeName::TsQuery,
17178            // v7.17.0 — PG `UUID`. Wire OID 2950. The drop-in PG
17179            // surface for Django / Rails / Hibernate's default
17180            // PK pattern.
17181            "uuid" => ColumnTypeName::Uuid,
17182            // v7.37.5 β-P2 — PG `INTERVAL` as a column type.
17183            // Storage = three-field {months, days, micros}, catalog
17184            // tag 34, FILE_VERSION 48+, wire OID 1186. Prior to this
17185            // line `INTERVAL` was parser-rejected at CREATE TABLE.
17186            "interval" => {
17187                // pg_dump emits field-qualified forms like `INTERVAL DAY TO
17188                // SECOND` and an optional `(p)` precision. SPG stores the full
17189                // {months,days,micros}; consume + ignore the qualifier/precision.
17190                while matches!(self.peek(), Token::To)
17191                    || matches!(self.peek(), Token::Ident(s) if matches!(
17192                        s.to_ascii_lowercase().as_str(),
17193                        "year" | "month" | "day" | "hour" | "minute" | "second"
17194                    ))
17195                {
17196                    self.advance();
17197                }
17198                self.consume_optional_paren_size();
17199                ColumnTypeName::Interval
17200            }
17201            // v7.17.0 Phase 3.P0-32 — PG `TIME` (without time zone).
17202            // i64 microseconds since 00:00:00. Wire OID 1083.
17203            // pg_dump emits `TIME(6)` and `TIME(6) WITH TIME ZONE`.
17204            "time" => {
17205                // v7.39 (round 424) — MySQL TIME carries a semantic
17206                // fractional-seconds precision, bare meaning 0.
17207                let n = self.take_optional_paren_size();
17208                if self.mysql_dialect {
17209                    mysql_fsp = Some(n.unwrap_or(0).min(6));
17210                }
17211                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("with"))
17212                    && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("time"))
17213                    && matches!(self.tokens.get(self.pos + 2), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("zone"))
17214                {
17215                    self.advance();
17216                    self.advance();
17217                    self.advance();
17218                    ColumnTypeName::TimeTz
17219                } else if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("without"))
17220                    && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("time"))
17221                    && matches!(self.tokens.get(self.pos + 2), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("zone"))
17222                {
17223                    self.advance();
17224                    self.advance();
17225                    self.advance();
17226                    ColumnTypeName::Time
17227                } else {
17228                    ColumnTypeName::Time
17229                }
17230            }
17231            // v7.17.0 Phase 3.P0-33 — MySQL `YEAR`. u16 in
17232            // 1901..=2155 + zero-year sentinel 0. Wire = INT4.
17233            "year" => ColumnTypeName::Year,
17234            // v7.17.0 Phase 3.P0-34 — PG `TIMETZ` / `TIME WITH
17235            // TIME ZONE`. i64 us + i32 offset_secs. Wire OID 1266.
17236            "timetz" => ColumnTypeName::TimeTz,
17237            // v7.17.0 Phase 3.P0-35 — PG `MONEY` — i64 cents.
17238            // Wire OID 790.
17239            "money" => ColumnTypeName::Money,
17240            // v7.17.0 Phase 3.P0-38 — PG range types.
17241            "int4range" => ColumnTypeName::Range(RangeKindAst::Int4),
17242            "int8range" => ColumnTypeName::Range(RangeKindAst::Int8),
17243            "numrange" => ColumnTypeName::Range(RangeKindAst::Num),
17244            "tsrange" => ColumnTypeName::Range(RangeKindAst::Ts),
17245            "tstzrange" => ColumnTypeName::Range(RangeKindAst::TsTz),
17246            "daterange" => ColumnTypeName::Range(RangeKindAst::Date),
17247            // v7.37.5 δ — PG 14+ multirange keywords.
17248            "int4multirange" => ColumnTypeName::Multirange(RangeKindAst::Int4),
17249            "int8multirange" => ColumnTypeName::Multirange(RangeKindAst::Int8),
17250            "nummultirange" => ColumnTypeName::Multirange(RangeKindAst::Num),
17251            "tsmultirange" => ColumnTypeName::Multirange(RangeKindAst::Ts),
17252            "tstzmultirange" => ColumnTypeName::Multirange(RangeKindAst::TsTz),
17253            "datemultirange" => ColumnTypeName::Multirange(RangeKindAst::Date),
17254            // v7.37.5 ε — PG geometry scalar keywords.
17255            "point" => ColumnTypeName::Point,
17256            "lseg" => ColumnTypeName::Lseg,
17257            "path" => ColumnTypeName::Path,
17258            "box" => ColumnTypeName::PgBox,
17259            "polygon" => ColumnTypeName::Polygon,
17260            "line" => ColumnTypeName::Line,
17261            "circle" => ColumnTypeName::Circle,
17262            // v7.37.5 ζ-A — network / bit / xml / "char" keywords.
17263            "inet" => ColumnTypeName::Inet,
17264            "cidr" => ColumnTypeName::Cidr,
17265            "macaddr" => ColumnTypeName::Macaddr,
17266            "macaddr8" => ColumnTypeName::Macaddr8,
17267            // `bit`, `bit(N)`, `bit varying`, `bit varying(N)`. SPG carries the
17268            // width in the value, so the optional `(N)` typmod is accepted and
17269            // ignored (the column stores whatever width it's given).
17270            "bit" => {
17271                let varying = matches!(
17272                    self.peek(),
17273                    Token::Ident(k) if k.eq_ignore_ascii_case("varying")
17274                );
17275                if varying {
17276                    self.advance();
17277                }
17278                // v7.39 (round 281) — the length used to be parsed and
17279                // dropped, so `bit(3)` accepted a five-bit string.
17280                let n = if matches!(self.peek(), Token::LParen) {
17281                    self.parse_paren_size("BIT")?
17282                } else {
17283                    0
17284                };
17285                if varying {
17286                    ColumnTypeName::BitVarying(n)
17287                } else {
17288                    ColumnTypeName::Bit(n)
17289                }
17290            }
17291            "varbit" => {
17292                let n = if matches!(self.peek(), Token::LParen) {
17293                    self.parse_paren_size("VARBIT")?
17294                } else {
17295                    0
17296                };
17297                ColumnTypeName::BitVarying(n)
17298            }
17299            "xml" => ColumnTypeName::Xml,
17300            // v7.17.0 Phase 3.P0-39 — PG hstore extension type.
17301            "hstore" => ColumnTypeName::Hstore,
17302            // v7.17.0 Phase 3.P0-36 — MySQL inline ENUM
17303            // `ENUM('a','b','c')`. Storage is TEXT; the value
17304            // list lands on `inline_enum_variants` for the
17305            // engine to validate INSERT cells against. Empty
17306            // value list is a parse error (matches MySQL).
17307            "enum" => {
17308                // Expect the opening `(`.
17309                if !matches!(self.peek(), Token::LParen) {
17310                    return Err(self.err(alloc::format!(
17311                        "expected '(' after ENUM, got {:?}",
17312                        self.peek()
17313                    )));
17314                }
17315                self.advance();
17316                let mut variants: Vec<String> = Vec::new();
17317                loop {
17318                    match self.advance() {
17319                        Token::String(s) => variants.push(s),
17320                        other => {
17321                            return Err(self.err(alloc::format!(
17322                                "ENUM(...) expects string literal variants, got {other:?}"
17323                            )));
17324                        }
17325                    }
17326                    match self.peek() {
17327                        Token::Comma => {
17328                            self.advance();
17329                            continue;
17330                        }
17331                        Token::RParen => {
17332                            self.advance();
17333                            break;
17334                        }
17335                        other => {
17336                            return Err(self.err(alloc::format!(
17337                                "expected ',' or ')' in ENUM(...), got {other:?}"
17338                            )));
17339                        }
17340                    }
17341                }
17342                if variants.is_empty() {
17343                    return Err(self.err("ENUM(...) must declare at least one variant".into()));
17344                }
17345                inline_enum_variants = Some(variants);
17346                // Storage is plain TEXT; the variant list lives on
17347                // the ColumnSchema side.
17348                ColumnTypeName::Text
17349            }
17350            // v7.17.0 Phase 3.P0-37 — MySQL inline SET
17351            // `SET('a','b','c')`. Same parse shape as ENUM;
17352            // semantics differ (subset rather than pick-one).
17353            "set" => {
17354                if !matches!(self.peek(), Token::LParen) {
17355                    return Err(self.err(alloc::format!(
17356                        "expected '(' after SET, got {:?}",
17357                        self.peek()
17358                    )));
17359                }
17360                self.advance();
17361                let mut variants: Vec<String> = Vec::new();
17362                loop {
17363                    match self.advance() {
17364                        Token::String(s) => variants.push(s),
17365                        other => {
17366                            return Err(self.err(alloc::format!(
17367                                "SET(...) expects string literal variants, got {other:?}"
17368                            )));
17369                        }
17370                    }
17371                    match self.peek() {
17372                        Token::Comma => {
17373                            self.advance();
17374                            continue;
17375                        }
17376                        Token::RParen => {
17377                            self.advance();
17378                            break;
17379                        }
17380                        other => {
17381                            return Err(self.err(alloc::format!(
17382                                "expected ',' or ')' in SET(...), got {other:?}"
17383                            )));
17384                        }
17385                    }
17386                }
17387                if variants.is_empty() {
17388                    return Err(self.err("SET(...) must declare at least one variant".into()));
17389                }
17390                inline_set_variants = Some(variants);
17391                ColumnTypeName::Text
17392            }
17393            _other => {
17394                // v7.17.0 Phase 1.4 — unknown ident → defer
17395                // resolution to the engine. Stored as Text in
17396                // ColumnTypeName + the original name carried as
17397                // `user_type_ref` so CREATE TABLE can look up
17398                // user-defined enum / domain types.
17399                user_type_ref = Some(ty_ident.clone());
17400                ColumnTypeName::Text
17401            }
17402        };
17403        // v7.17.0 Phase 4.4 — MySQL's `UNSIGNED` modifier sits
17404        // right after the type keyword. Pre-4.4 SPG consumed +
17405        // discarded the keyword, leaving a customer column
17406        // declared `id INT UNSIGNED NOT NULL` silently accepting
17407        // negative values — a Tier-A correctness drift where
17408        // application invariants (auto-increment-IDs never
17409        // negative) silently broke on cutover. Now: capture as
17410        // a column flag, persist on the schema, enforce at
17411        // INSERT / UPDATE time.
17412        let is_unsigned = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("unsigned"))
17413        {
17414            self.advance();
17415            true
17416        } else {
17417            false
17418        };
17419        // v7.14.0 — mysqldump emits `<type> CHARACTER SET <name>` and
17420        // `<type> COLLATE <name>` post-fixes on text columns. SPG
17421        // stores text as UTF-8 always so CHARACTER SET is still a
17422        // no-op. v7.17.0 Phase 2.5 — COLLATE no longer drops the
17423        // name: it gets classified into a `Collation` variant the
17424        // engine consults at WHERE-eval time. PG `default` /
17425        // `pg_catalog.default` / `C` / `POSIX` collations all
17426        // resolve to `Binary` (the prior behaviour); `_ci` /
17427        // `case_insensitive` / `nocase` shift to CaseInsensitive.
17428        // The schema-qualifier form (`pg_catalog.default`) lexes
17429        // as `Ident '.' Ident` — peek for the `.` and consume both
17430        // halves so it's treated as one collation name. PG's
17431        // `IDENT.IDENT` collation form (which can appear here) is
17432        // resolved by Collation::from_collation_name on the bare
17433        // identifier after the dot.
17434        let mut collation = Collation::Binary;
17435        // v7.39 (round 370, M4 P4a) — whether an explicit `COLLATE <name>`
17436        // clause was written. The engine needs this to tell an explicit
17437        // `COLLATE utf8mb4_bin` (byte-wise) apart from a column with no
17438        // clause at all: both resolve to `Collation::Binary`, but under the
17439        // MySQL dialect the latter takes the folding default collation.
17440        let mut collation_explicit = false;
17441        let mut collation_name: Option<alloc::string::String> = None;
17442        loop {
17443            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("character"))
17444                && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("set"))
17445            {
17446                self.advance(); // CHARACTER
17447                self.advance(); // SET
17448                if matches!(
17449                    self.peek(),
17450                    Token::Ident(_) | Token::QuotedIdent(_) | Token::String(_)
17451                ) {
17452                    self.advance();
17453                }
17454                continue;
17455            }
17456            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("collate")) {
17457                self.advance(); // COLLATE
17458                // Accept Ident / QuotedIdent / String AND the
17459                // keyword-tokenised `Default` (PG `pg_catalog.default`
17460                // and bare `DEFAULT` collation names — `default` is a
17461                // reserved word so the lexer hands back Token::Default
17462                // not Token::Ident).
17463                let read_collation_atom = |this: &mut Self| -> Option<alloc::string::String> {
17464                    match this.peek().clone() {
17465                        Token::Ident(s) | Token::QuotedIdent(s) | Token::String(s) => {
17466                            this.advance();
17467                            Some(s)
17468                        }
17469                        Token::Default => {
17470                            this.advance();
17471                            Some(alloc::string::String::from("default"))
17472                        }
17473                        _ => None,
17474                    }
17475                };
17476                let raw = if let Some(head) = read_collation_atom(self) {
17477                    // Schema-qualified PG form: `pg_catalog.default`.
17478                    if matches!(self.peek(), Token::Dot) {
17479                        self.advance();
17480                        let tail = read_collation_atom(self).unwrap_or_default();
17481                        alloc::format!("{head}.{tail}")
17482                    } else {
17483                        head
17484                    }
17485                } else {
17486                    alloc::string::String::new()
17487                };
17488                if !raw.is_empty() {
17489                    collation_explicit = true;
17490                    // v7.39 (round 676) — keep the name too. The enum below
17491                    // folds C / POSIX / en_US / default into one value, and
17492                    // `pg_attribute.attcollation` has to tell them apart.
17493                    // The schema qualifier goes: PG's `pg_catalog.default`
17494                    // and a bare `default` name the same collation.
17495                    // v7.39 (round 679) — strip a SCHEMA qualifier, not an
17496                    // encoding suffix. Round 676 used `rsplit('.')` for
17497                    // both, and `COLLATE "en_US.utf8"` came out as `utf8`:
17498                    // PG writes `pg_catalog.default` (qualifier) and
17499                    // `en_US.utf8` (locale + encoding) with the same
17500                    // separator. Only `pg_catalog.` is a qualifier, and it
17501                    // is the only one PG's own dumps emit.
17502                    let bare = raw.trim_matches(|c: char| c == '"' || c == '\'');
17503                    let bare = bare.strip_prefix("pg_catalog.").unwrap_or(bare);
17504                    collation_name = Some(alloc::string::String::from(bare));
17505                    let parsed = Collation::from_collation_name(&raw);
17506                    // Last COLLATE clause wins, but `Binary` from a
17507                    // bare keyword like `default` should not
17508                    // silently downgrade a stronger one set earlier
17509                    // on the same column. v7.17 only ships one
17510                    // non-Binary variant so a simple OR is enough.
17511                    if parsed != Collation::Binary {
17512                        collation = parsed;
17513                    }
17514                }
17515                continue;
17516            }
17517            break;
17518        }
17519        // v7.10.10 — postfix `[]` widens the base type to its array
17520        // type. PG accepts `TYPE[]` after any base type and so does
17521        // SPG now (round-753 probe: INT[] / NUMERIC[] / TIMESTAMP[]
17522        // all through; the old "only TEXT[]" note was stale).
17523        if matches!(self.peek(), Token::LBracket) {
17524            self.advance();
17525            if !matches!(self.peek(), Token::RBracket) {
17526                return Err(self.err(alloc::format!(
17527                    "TEXT[] takes no dimension; got {:?}",
17528                    self.peek()
17529                )));
17530            }
17531            self.advance();
17532            // v7.11.13 — widened to INT[] and BIGINT[] in addition
17533            // to TEXT[]. Other base types (BOOL[], NUMERIC[], etc.)
17534            // still error here.
17535            ty = match ty {
17536                ColumnTypeName::Text => ColumnTypeName::TextArray,
17537                ColumnTypeName::Int => ColumnTypeName::IntArray,
17538                ColumnTypeName::BigInt => ColumnTypeName::BigIntArray,
17539                // v7.37.5 β-P4 — INTERVAL[] via the same postfix
17540                // `[]` grammar. Wire OID 1187.
17541                ColumnTypeName::Interval => ColumnTypeName::IntervalArray,
17542                // v7.37.5 γ — full PG array-of-scalar family.
17543                ColumnTypeName::Bool => ColumnTypeName::BoolArray,
17544                ColumnTypeName::SmallInt => ColumnTypeName::SmallIntArray,
17545                ColumnTypeName::Float => ColumnTypeName::FloatArray,
17546                // NUMERIC(p, s) loses its precision params at the
17547                // array level (matches PG: `NUMERIC[]` is untyped,
17548                // per-element precision flows through values).
17549                ColumnTypeName::Numeric(_, _) => ColumnTypeName::NumericArray,
17550                ColumnTypeName::Date => ColumnTypeName::DateArray,
17551                ColumnTypeName::Timestamp => ColumnTypeName::TimestampArray,
17552                ColumnTypeName::Timestamptz => ColumnTypeName::TimestamptzArray,
17553                ColumnTypeName::Uuid => ColumnTypeName::UuidArray,
17554                ColumnTypeName::Json => ColumnTypeName::JsonArray,
17555                ColumnTypeName::Jsonb => ColumnTypeName::JsonbArray,
17556                ColumnTypeName::Bytes => ColumnTypeName::BytesArray,
17557                // VARCHAR(n)[] / CHAR(n)[] drop the length cap at
17558                // the array level (matches PG semantics where the
17559                // element precision is per-row, not column-wide).
17560                ColumnTypeName::Varchar(_) => ColumnTypeName::VarcharArray,
17561                ColumnTypeName::Char(_) => ColumnTypeName::CharArray,
17562                // v7.37.5 ζ-A — MONEY[] (OID 791) ship-triage
17563                // follow-up.
17564                ColumnTypeName::Money => ColumnTypeName::MoneyArray,
17565                other => {
17566                    return Err(self.err(alloc::format!("{other:?}[] not yet supported")));
17567                }
17568            };
17569            // v7.17.0 Phase 3.P0-40 — second `[]` widens 1D → 2D
17570            // for INT/TEXT/BIGINT. Anything else is an error.
17571            if matches!(self.peek(), Token::LBracket) {
17572                self.advance();
17573                if !matches!(self.peek(), Token::RBracket) {
17574                    return Err(self.err(alloc::format!(
17575                        "TYPE[][] second dimension takes no size; got {:?}",
17576                        self.peek()
17577                    )));
17578                }
17579                self.advance();
17580                ty = match ty {
17581                    ColumnTypeName::IntArray => ColumnTypeName::IntArray2D,
17582                    ColumnTypeName::BigIntArray => ColumnTypeName::BigIntArray2D,
17583                    ColumnTypeName::TextArray => ColumnTypeName::TextArray2D,
17584                    // v7.39 (read01 round 75) — bool[][].
17585                    ColumnTypeName::BoolArray => ColumnTypeName::BoolArray2D,
17586                    other => {
17587                        return Err(self.err(alloc::format!(
17588                            "v7.17 2D arrays support INT[][] / BIGINT[][] / \
17589                             TEXT[][] only; got {other:?}"
17590                        )));
17591                    }
17592                };
17593            }
17594        }
17595        Ok((
17596            ty,
17597            implied_auto_increment,
17598            implied_not_null,
17599            user_type_ref,
17600            collation,
17601            collation_explicit,
17602            collation_name,
17603            is_unsigned,
17604            inline_enum_variants,
17605            inline_set_variants,
17606            mysql_int_width,
17607            mysql_fsp,
17608            mysql_declared_timestamp,
17609            mysql_float_md,
17610        ))
17611    }
17612
17613    fn parse_column_def(&mut self) -> Result<ColumnDef, ParseError> {
17614        // v7.20 — PG reserves the table-constraint keywords, so a
17615        // BARE `UNIQUE` / `PRIMARY` / … in column position is a
17616        // malformed constraint clause (e.g. `UNIQUE a` missing its
17617        // parens), not a column named "unique". Since v7.17's
17618        // unknown-type leniency (`user_type_ref`) such a clause
17619        // would otherwise parse as a column with a user-defined
17620        // type — silently accepting invalid DDL. Quoted
17621        // identifiers ("unique" / `unique`) remain valid names.
17622        if let Token::Ident(s) = self.peek()
17623            && [
17624                "unique",
17625                "primary",
17626                "foreign",
17627                "constraint",
17628                "check",
17629                "references",
17630                "exclude",
17631            ]
17632            .iter()
17633            .any(|kw| s.eq_ignore_ascii_case(kw))
17634        {
17635            return Err(self.err(alloc::format!(
17636                "unexpected reserved keyword '{s}' at start of column definition \
17637                 (malformed table constraint?)"
17638            )));
17639        }
17640        let name_tok = self.pos;
17641        let name = self.expect_ident_like()?;
17642        // v7.39.3 — MySQL 9.7.2 reports a column by the SPELLING it was
17643        // declared with: `MyCol` stays `MyCol` in SHOW COLUMNS, in
17644        // information_schema, and in SHOW CREATE (measured). SPG folded
17645        // an unquoted name, so a table restored from a dump reported
17646        // names the application had never written.
17647        //
17648        // The written form comes back from the source span, which only
17649        // the MySQL dialect keeps. The span runs to the START of the
17650        // next token, so a comment or unusual spacing between them
17651        // arrives with it — hence the check that what came back is the
17652        // same identifier. It is not decoration: without it,
17653        // `CREATE TABLE t (MyCol /* c */ INT)` names the column
17654        // `MyCol /* c */`.
17655        let name = self
17656            .source_span(name_tok, name_tok)
17657            .map(|raw| raw.trim().trim_matches('`').trim_matches('"'))
17658            .filter(|raw| raw.eq_ignore_ascii_case(&name))
17659            .map_or(name, alloc::string::String::from);
17660        let (
17661            ty,
17662            implied_auto_increment,
17663            implied_not_null,
17664            user_type_ref,
17665            collation,
17666            collation_explicit,
17667            collation_name,
17668            is_unsigned,
17669            inline_enum_variants,
17670            inline_set_variants,
17671            mysql_int_width,
17672            mysql_fsp,
17673            mysql_declared_timestamp,
17674            mysql_float_md,
17675        ) = self.parse_type_with_implied_flags()?;
17676        // Column constraints: `DEFAULT <expr>`, `NOT NULL`, and the
17677        // MySQL-flavoured `AUTO_INCREMENT` may appear in any order;
17678        // each at most once.
17679        let mut default: Option<Expr> = None;
17680        let mut nullable = !implied_not_null;
17681        let mut nullability_seen = implied_not_null;
17682        let mut auto_increment = implied_auto_increment;
17683        let mut is_primary_key = false;
17684        let mut is_unique = false;
17685        let mut unique_nulls_not_distinct = false;
17686        let mut constraint_deferrable = false;
17687        let mut constraint_initially_deferred = false;
17688        let mut check: Option<Expr> = None;
17689        let mut on_update_runtime: Option<Expr> = None;
17690        let mut generated_stored_expr: Option<Box<Expr>> = None;
17691        let mut identity_always = false;
17692        loop {
17693            // v7.22 (mailrs round-13 gap 3) — PG 18 catalogs
17694            // not-null constraints by name and pg_dump emits them
17695            // inline: `id bigint CONSTRAINT contacts_id_not_null1
17696            // NOT NULL`. Accept and discard the name; whatever
17697            // constraint follows is parsed by the arms below.
17698            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("constraint")) {
17699                // v7.39 (round 308, V29) — a name on an inline
17700                // REFERENCES belongs to the FOREIGN KEY, and the caller
17701                // (`parse_column_def_with_fk`) is what builds it, so
17702                // leave the whole clause for it. Dropping the name here
17703                // is what made `CONSTRAINT fk_a REFERENCES …` come back
17704                // as the synthesised `c_pid_fkey` — which then could
17705                // not be matched by `SET CONSTRAINTS fk_a`. Peek only:
17706                // `advance()` takes tokens by `mem::replace`, so there
17707                // is no rewinding once consumed.
17708                if matches!(
17709                    self.tokens.get(self.pos + 2),
17710                    Some(Token::Ident(s)) if s.eq_ignore_ascii_case("references")
17711                ) {
17712                    break;
17713                }
17714                self.advance();
17715                let _name = self.expect_ident_like()?;
17716                continue;
17717            }
17718            // v7.39 (round 379) — MySQL's SHORT generated-column form
17719            // omits `GENERATED ALWAYS`: `<col> <type> AS (<expr>)
17720            // [STORED | VIRTUAL]`. mysqldump emits the long form (handled
17721            // below), but hand-written schemas and app migrations use this.
17722            // STORED / VIRTUAL is optional (MySQL defaults to VIRTUAL);
17723            // SPG computes-and-stores either way, like the long form.
17724            if matches!(self.peek(), Token::As) {
17725                self.advance();
17726                if !matches!(self.peek(), Token::LParen) {
17727                    return Err(self.err(alloc::format!(
17728                        "expected '(' after AS in a generated column, got {:?}",
17729                        self.peek()
17730                    )));
17731                }
17732                self.advance();
17733                let expr = self.parse_expr(0)?;
17734                if !matches!(self.peek(), Token::RParen) {
17735                    return Err(self.err(alloc::format!(
17736                        "expected ')' after AS (<expr>), got {:?}",
17737                        self.peek()
17738                    )));
17739                }
17740                self.advance();
17741                if matches!(self.peek(), Token::Ident(s)
17742                    if s.eq_ignore_ascii_case("stored") || s.eq_ignore_ascii_case("virtual"))
17743                {
17744                    self.advance();
17745                }
17746                generated_stored_expr = Some(alloc::boxed::Box::new(expr));
17747                continue;
17748            }
17749            // v7.22 (round-13 T2) — inline `GENERATED { ALWAYS |
17750            // BY DEFAULT } AS IDENTITY [(seq options)]` (PG 10+;
17751            // the modern replacement for SERIAL in hand-written
17752            // schemas). Both flavours map onto the auto-increment
17753            // machinery — SPG's serial semantics ≈ BY DEFAULT;
17754            // ALWAYS's reject-explicit-values nuance is documented
17755            // leniency. Generated EXPRESSION columns
17756            // (`AS (expr) STORED`) are not supported: error loudly
17757            // instead of silently storing NULLs.
17758            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("generated")) {
17759                self.advance();
17760                let mut saw_generated_always = false;
17761                match self.peek().clone() {
17762                    Token::Ident(s) if s.eq_ignore_ascii_case("always") => {
17763                        self.advance();
17764                        saw_generated_always = true;
17765                    }
17766                    Token::Ident(b) | Token::QuotedIdent(b) if b.eq_ignore_ascii_case("by") => {
17767                        self.advance();
17768                        if !matches!(self.peek(), Token::Default) {
17769                            return Err(self.err(alloc::format!(
17770                                "expected DEFAULT after GENERATED BY, got {:?}",
17771                                self.peek()
17772                            )));
17773                        }
17774                        self.advance();
17775                    }
17776                    other => {
17777                        return Err(self.err(alloc::format!(
17778                            "expected ALWAYS or BY DEFAULT after GENERATED, got {other:?}"
17779                        )));
17780                    }
17781                }
17782                if !matches!(self.peek(), Token::As) {
17783                    return Err(self.err(alloc::format!(
17784                        "expected AS after GENERATED ALWAYS/BY DEFAULT, got {:?}",
17785                        self.peek()
17786                    )));
17787                }
17788                self.advance();
17789                // v7.37.7(sentori Epic 3 P1)— `GENERATED ALWAYS AS
17790                // ( <expr> ) STORED` stored computed-column. The
17791                // expression is captured for the engine to recompute
17792                // on every INSERT / UPDATE. v7.37.7 accepts the
17793                // STORED keyword only; PG also has VIRTUAL, which
17794                // v7.37.7 carves out (sentori only uses STORED).
17795                if matches!(self.peek(), Token::LParen) {
17796                    self.advance();
17797                    let expr = self.parse_expr(0)?;
17798                    if !matches!(self.peek(), Token::RParen) {
17799                        return Err(self.err(alloc::format!(
17800                            "expected ')' after GENERATED ALWAYS AS (<expr>), got {:?}",
17801                            self.peek()
17802                        )));
17803                    }
17804                    self.advance();
17805                    let stored = match self.peek() {
17806                        Token::Ident(s) | Token::QuotedIdent(s)
17807                            if s.eq_ignore_ascii_case("stored") =>
17808                        {
17809                            self.advance();
17810                            true
17811                        }
17812                        // v7.38 (read01 P4.14) — accept PG 18's VIRTUAL
17813                        // generated columns. SPG computes them on write and
17814                        // persists like STORED; the two are observably
17815                        // identical for query results (the value, recompute
17816                        // on base-column change, and NOT NULL enforcement all
17817                        // match), so a PG 18 schema/dump using VIRTUAL loads
17818                        // and behaves correctly. The compute-on-read storage
17819                        // saving is an invisible internal difference.
17820                        Token::Ident(s) | Token::QuotedIdent(s)
17821                            if s.eq_ignore_ascii_case("virtual") =>
17822                        {
17823                            self.advance();
17824                            false
17825                        }
17826                        other => {
17827                            return Err(self.err(alloc::format!(
17828                                "expected STORED or VIRTUAL after GENERATED ALWAYS AS (<expr>), \
17829                                 got {other:?}"
17830                            )));
17831                        }
17832                    };
17833                    let _ = stored; // STORED / VIRTUAL both compute-and-store.
17834                    generated_stored_expr = Some(Box::new(expr));
17835                    continue;
17836                }
17837                self.expect_keyword_ident("identity")?;
17838                // Optional `(START WITH 1 INCREMENT BY 1 …)` —
17839                // consume the balanced parens and discard (SPG's
17840                // auto-increment is max+1-scan based).
17841                if matches!(self.peek(), Token::LParen) {
17842                    let mut depth = 0usize;
17843                    loop {
17844                        match self.advance() {
17845                            Token::LParen => depth += 1,
17846                            Token::RParen => {
17847                                depth -= 1;
17848                                if depth == 0 {
17849                                    break;
17850                                }
17851                            }
17852                            Token::Eof => {
17853                                return Err(self.err(
17854                                    "unterminated sequence-options parens after IDENTITY".into(),
17855                                ));
17856                            }
17857                            _ => {}
17858                        }
17859                    }
17860                }
17861                auto_increment = true;
17862                // v7.38 (read01) — remember the ALWAYS flavour so the engine
17863                // can reject explicit non-DEFAULT INSERT values (unless
17864                // OVERRIDING SYSTEM VALUE) the way PG does.
17865                identity_always = saw_generated_always;
17866                // PG identity columns are implicitly NOT NULL.
17867                nullable = false;
17868                continue;
17869            }
17870            // v7.17.0 Phase 2.1 — MySQL `ON UPDATE
17871            // CURRENT_TIMESTAMP[(N)]`. Only CURRENT_TIMESTAMP
17872            // is accepted today. The "ON" token is an Ident
17873            // (not reserved) — peek before consuming.
17874            if matches!(self.peek(), Token::On)
17875                && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("update"))
17876            {
17877                self.advance(); // ON
17878                self.advance(); // update
17879                // Accept CURRENT_TIMESTAMP / CURRENT_TIMESTAMP(N).
17880                let next = self.peek().clone();
17881                match next {
17882                    Token::Ident(s) | Token::QuotedIdent(s)
17883                        if s.eq_ignore_ascii_case("current_timestamp") =>
17884                    {
17885                        self.advance();
17886                        // Optional `(N)` precision.
17887                        if matches!(self.peek(), Token::LParen) {
17888                            self.advance();
17889                            if !matches!(self.peek(), Token::Integer(_)) {
17890                                return Err(self.err(alloc::format!(
17891                                    "expected integer precision inside CURRENT_TIMESTAMP(…), got {:?}",
17892                                    self.peek()
17893                                )));
17894                            }
17895                            self.advance();
17896                            if !matches!(self.peek(), Token::RParen) {
17897                                return Err(self.err(alloc::format!(
17898                                    "expected ')' after CURRENT_TIMESTAMP precision, got {:?}",
17899                                    self.peek()
17900                                )));
17901                            }
17902                            self.advance();
17903                        }
17904                        on_update_runtime = Some(Expr::FunctionCall {
17905                            name: "now".into(),
17906                            args: Vec::new(),
17907                        });
17908                        continue;
17909                    }
17910                    other => {
17911                        return Err(self.err(alloc::format!(
17912                            "v7.17 only supports ON UPDATE CURRENT_TIMESTAMP, got {other:?}"
17913                        )));
17914                    }
17915                }
17916            }
17917            if matches!(self.peek(), Token::Default) {
17918                if default.is_some() {
17919                    return Err(self.err("DEFAULT specified twice".into()));
17920                }
17921                self.advance();
17922                default = Some(self.parse_expr(0)?);
17923                continue;
17924            }
17925            // v7.39 (round 621) — `NOT DEFERRABLE` shares this arm's leading
17926            // token with NOT NULL and sits EARLIER in the loop than the
17927            // deferrability arm, so without the lookahead it was reported as
17928            // "NOT NULL specified twice" (or "expected NULL after NOT").
17929            if matches!(self.peek(), Token::Not)
17930                && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("deferrable"))
17931            {
17932                // NOT DEFERRABLE — explicit immediate; nothing to carry.
17933                self.consume_optional_deferrable_clauses()?;
17934                continue;
17935            }
17936            if matches!(self.peek(), Token::Not) {
17937                if nullability_seen {
17938                    return Err(self.err("NOT NULL specified twice".into()));
17939                }
17940                self.advance();
17941                if !matches!(self.peek(), Token::Null) {
17942                    return Err(self.err(format!(
17943                        "expected NULL after NOT in column def, got {:?}",
17944                        self.peek()
17945                    )));
17946                }
17947                self.advance();
17948                nullable = false;
17949                nullability_seen = true;
17950                continue;
17951            }
17952            // v7.14.0 — MySQL accepts a bare `NULL` as an explicit
17953            // "this column is nullable" marker (the default in
17954            // standard SQL anyway). mysqldump emits it routinely
17955            // (`col TYPE NULL DEFAULT NULL` for nullable
17956            // timestamps etc). Accept + no-op.
17957            if matches!(self.peek(), Token::Null) {
17958                if nullability_seen && !nullable {
17959                    // v7.39 (round 761, F31 tranche 2 #31) — PG's
17960                    // sentence, PG18-measured (the table name is the
17961                    // caller's; the column half is exact).
17962                    return Err(self.err(alloc::format!(
17963                        "conflicting NULL/NOT NULL declarations for column \"{name}\""
17964                    )));
17965                }
17966                self.advance();
17967                nullable = true;
17968                nullability_seen = true;
17969                continue;
17970            }
17971            // `AUTO_INCREMENT` or its abbreviated form `AUTOINCREMENT`
17972            // arrives as a bare Ident. Match either, case-insensitive.
17973            if let Token::Ident(s) = self.peek()
17974                && (s.eq_ignore_ascii_case("auto_increment")
17975                    || s.eq_ignore_ascii_case("autoincrement"))
17976            {
17977                if auto_increment {
17978                    return Err(self.err("AUTO_INCREMENT specified twice".into()));
17979                }
17980                self.advance();
17981                auto_increment = true;
17982                continue;
17983            }
17984            // v7.9.13 — inline `PRIMARY KEY` column constraint
17985            // (mailrs F1). Implies `NOT NULL`. The engine creates
17986            // a BTree index for the PK column at CREATE TABLE time
17987            // so FK parent-side index lookups resolve.
17988            // v7.39 (round 621) — `[NOT] DEFERRABLE [INITIALLY {DEFERRED |
17989            // IMMEDIATE}]` after an inline PK / UNIQUE / REFERENCES. Every
17990            // spelling was a parse error, so a pg_dump carrying one stopped
17991            // mid-restore. The clauses are consumed by the same helper the FK
17992            // path has used since round 288 and recorded nowhere: SPG enforces
17993            // the constraint IMMEDIATELY either way, which fails earlier than
17994            // PG inside a transaction that violates-then-repairs — a refusal,
17995            // not a wrong answer. True deferral is the open remainder of F08.
17996            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("deferrable") || s.eq_ignore_ascii_case("initially"))
17997                || (matches!(self.peek(), Token::Not)
17998                    && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s)) if s.eq_ignore_ascii_case("deferrable")))
17999            {
18000                // v7.39 (round 711) — CARRIED now (the storing half of
18001                // F08); round 621 only consumed.
18002                let (d, idef) = self.consume_deferrable_clauses_timed()?;
18003                constraint_deferrable |= d;
18004                constraint_initially_deferred |= idef;
18005                continue;
18006            }
18007            if let Token::Ident(s) = self.peek()
18008                && s.eq_ignore_ascii_case("primary")
18009            {
18010                if is_primary_key {
18011                    return Err(self.err("PRIMARY KEY specified twice".into()));
18012                }
18013                // Peek-ahead for the required `KEY` token.
18014                let next = self.tokens.get(self.pos + 1);
18015                let next_is_key = matches!(
18016                    next,
18017                    Some(Token::Ident(k)) if k.eq_ignore_ascii_case("key")
18018                );
18019                if !next_is_key {
18020                    return Err(self.err(format!(
18021                        "expected KEY after PRIMARY in column def, got {:?}",
18022                        next
18023                    )));
18024                }
18025                self.advance(); // PRIMARY
18026                self.advance(); // KEY
18027                is_primary_key = true;
18028                if nullability_seen && nullable {
18029                    return Err(self.err(
18030                        "column declared NULL but inline PRIMARY KEY implies NOT NULL".into(),
18031                    ));
18032                }
18033                nullable = false;
18034                nullability_seen = true;
18035                continue;
18036            }
18037            // v7.13.0 — inline `UNIQUE` column constraint
18038            // (mailrs round-5 G2). Fold into a single-column
18039            // table-level UNIQUE at CREATE TABLE post-process time.
18040            if let Token::Ident(s) = self.peek()
18041                && s.eq_ignore_ascii_case("unique")
18042            {
18043                if is_unique {
18044                    return Err(self.err("UNIQUE specified twice".into()));
18045                }
18046                self.advance();
18047                is_unique = true;
18048                // v7.38 (read01 P4.19) — optional `NULLS [NOT] DISTINCT`
18049                // (PG 15+); default is NULLS DISTINCT per the SQL standard.
18050                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("nulls")) {
18051                    let n1 = self.tokens.get(self.pos + 1);
18052                    let n2 = self.tokens.get(self.pos + 2);
18053                    if matches!(n1, Some(Token::Not)) && matches!(n2, Some(Token::Distinct)) {
18054                        self.advance(); // NULLS
18055                        self.advance(); // NOT
18056                        self.advance(); // DISTINCT
18057                        unique_nulls_not_distinct = true;
18058                    } else if matches!(n1, Some(Token::Distinct)) {
18059                        self.advance(); // NULLS
18060                        self.advance(); // DISTINCT
18061                    }
18062                }
18063                continue;
18064            }
18065            // v7.13.0 — inline `CHECK (<expr>)` column constraint
18066            // (mailrs round-5 G3). PG semantics: column-level
18067            // CHECK is equivalent to a table-level CHECK. Multiple
18068            // inline CHECKs on the same column AND together.
18069            if let Token::Ident(s) = self.peek()
18070                && s.eq_ignore_ascii_case("check")
18071            {
18072                self.advance();
18073                if !matches!(self.peek(), Token::LParen) {
18074                    return Err(self.err(alloc::format!(
18075                        "expected '(' after CHECK in column def, got {:?}",
18076                        self.peek()
18077                    )));
18078                }
18079                self.advance();
18080                let pred = self.parse_expr(0)?;
18081                if !matches!(self.peek(), Token::RParen) {
18082                    return Err(self.err(alloc::format!(
18083                        "expected ')' to close CHECK predicate, got {:?}",
18084                        self.peek()
18085                    )));
18086                }
18087                self.advance();
18088                check = Some(match check.take() {
18089                    Some(prev) => Expr::Binary {
18090                        op: BinOp::And,
18091                        lhs: Box::new(prev),
18092                        rhs: Box::new(pred),
18093                    },
18094                    None => pred,
18095                });
18096                continue;
18097            }
18098            break;
18099        }
18100        Ok(ColumnDef {
18101            name,
18102            ty,
18103            nullable,
18104            default,
18105            auto_increment,
18106            is_primary_key,
18107            is_unique,
18108            unique_nulls_not_distinct,
18109            constraint_deferrable,
18110            constraint_initially_deferred,
18111            check,
18112            user_type_ref,
18113            on_update_runtime,
18114            collation,
18115            collation_explicit,
18116            collation_name,
18117            is_unsigned,
18118            inline_enum_variants,
18119            inline_set_variants,
18120            generated_stored_expr,
18121            identity_always,
18122            mysql_int_width,
18123            mysql_fsp,
18124            mysql_declared_timestamp,
18125            mysql_float_md,
18126        })
18127    }
18128
18129    /// `NUMERIC` may appear without parameters, with one (precision
18130    /// only, scale=0), or with both. Returns `(precision, scale)` with
18131    /// 0 = unspecified for the bare form.
18132    fn parse_optional_numeric_params(&mut self) -> Result<(u16, i16), ParseError> {
18133        if !matches!(self.peek(), Token::LParen) {
18134            // Bare `NUMERIC` — PG treats this as "unlimited precision";
18135            // we surface it as precision=0 to mean "unconstrained" so
18136            // the engine doesn't need a separate variant.
18137            return Ok((0, 0));
18138        }
18139        self.advance();
18140        // v7.39 (round 272) — PG's declared precision runs to 1000, and
18141        // it words the out-of-range case with the value it saw. SPG
18142        // capped at 38 (i128's width), so a `numeric(50,10)` column PG
18143        // accepts failed to parse at all; values wider than i128 are
18144        // carried by the arbitrary-precision form.
18145        let precision = match self.advance() {
18146            Token::Integer(n) if (1..=1000).contains(&n) => {
18147                u16::try_from(n).expect("range-checked")
18148            }
18149            Token::Integer(n) => {
18150                return Err(ParseError {
18151                    message: format!("NUMERIC precision {n} must be between 1 and 1000"),
18152                    token_pos: self.consumed_pos(),
18153                });
18154            }
18155            other => {
18156                return Err(ParseError {
18157                    message: format!(
18158                        "NUMERIC precision must be an integer in 1..=1000, got {other:?}"
18159                    ),
18160                    token_pos: self.consumed_pos(),
18161                });
18162            }
18163        };
18164        // v7.39 (round 273) — PG's declared scale runs -1000..=1000 and is
18165        // NOT bounded by the precision (`numeric(10,11)` is legal; a value
18166        // then overflows). A negative scale rounds to tens / hundreds / …
18167        let scale = if matches!(self.peek(), Token::Comma) {
18168            self.advance();
18169            let neg = if matches!(self.peek(), Token::Minus) {
18170                self.advance();
18171                true
18172            } else {
18173                false
18174            };
18175            match self.advance() {
18176                Token::Integer(n) => {
18177                    let signed = if neg { -n } else { n };
18178                    if !(-1000..=1000).contains(&signed) {
18179                        return Err(ParseError {
18180                            message: format!(
18181                                "NUMERIC scale {signed} must be between -1000 and 1000"
18182                            ),
18183                            token_pos: self.consumed_pos(),
18184                        });
18185                    }
18186                    i16::try_from(signed).expect("range-checked")
18187                }
18188                other => {
18189                    return Err(ParseError {
18190                        message: format!("NUMERIC scale must be an integer, got {other:?}"),
18191                        token_pos: self.consumed_pos(),
18192                    });
18193                }
18194            }
18195        } else {
18196            0
18197        };
18198        if !matches!(self.peek(), Token::RParen) {
18199            return Err(self.err(format!(
18200                "expected ')' to close NUMERIC params, got {:?}",
18201                self.peek()
18202            )));
18203        }
18204        self.advance();
18205        Ok((precision, scale))
18206    }
18207
18208    /// Parse `(N)` where `N` is a positive integer literal — used by the
18209    /// `VARCHAR`/`CHAR`/`VECTOR` column types. `label` is the type name
18210    /// for the error message.
18211    /// v6.0.1: parse the optional `USING <encoding>` clause that
18212    /// follows `VECTOR(N)` in a column definition. Missing clause
18213    /// → `VecEncoding::F32` (pre-v6 default). Unknown encoding
18214    /// ident → `ParseError` listing the encodings recognised today.
18215    fn parse_optional_vector_encoding(&mut self) -> Result<VecEncoding, ParseError> {
18216        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("using")) {
18217            return Ok(VecEncoding::F32);
18218        }
18219        // v7.13.2 — mailrs round-6 S6: `USING` after a vector type
18220        // overlaps with `ALTER COLUMN TYPE … USING <expr>`. Only
18221        // consume the token when the very next token is a known
18222        // vector-encoding keyword (SQ8 / HALF). Otherwise leave
18223        // `USING` for the caller — it's the rewrite-expression form.
18224        let n1 = self.tokens.get(self.pos + 1);
18225        let next_is_encoding = matches!(
18226            n1,
18227            Some(Token::Ident(s))
18228                if s.eq_ignore_ascii_case("sq8") || s.eq_ignore_ascii_case("half")
18229        );
18230        if !next_is_encoding {
18231            return Ok(VecEncoding::F32);
18232        }
18233        self.advance();
18234        let enc_ident = match self.advance() {
18235            Token::Ident(s) => s,
18236            other => {
18237                return Err(self.err(format!(
18238                    "expected vector encoding after USING, got {other:?}"
18239                )));
18240            }
18241        };
18242        match enc_ident.to_ascii_lowercase().as_str() {
18243            "sq8" => Ok(VecEncoding::Sq8),
18244            // v6.0.3: `HALF` (pgvector convention) selects IEEE-754
18245            // binary16 per-element storage.
18246            "half" => Ok(VecEncoding::F16),
18247            other => Err(self.err(format!(
18248                "unknown vector encoding {other:?}; supported: SQ8, HALF"
18249            ))),
18250        }
18251    }
18252
18253    /// v7.17.0 Phase 4.3 — peek at the MySQL display-width
18254    /// without consuming it. Returns `Some(N)` when the next
18255    /// tokens are `( <int> )`; None otherwise. Used by the
18256    /// TINYINT classifier to decide whether to map to Bool or
18257    /// SmallInt.
18258    fn peek_optional_paren_size_value(&self) -> Option<i64> {
18259        if !matches!(self.peek(), Token::LParen) {
18260            return None;
18261        }
18262        let next = self.tokens.get(self.pos + 1)?;
18263        let n = match next {
18264            Token::Integer(n) => *n,
18265            _ => return None,
18266        };
18267        if !matches!(self.tokens.get(self.pos + 2), Some(Token::RParen)) {
18268            return None;
18269        }
18270        Some(n)
18271    }
18272
18273    /// v7.14.0 — consume an optional MySQL display-width
18274    /// parenthesised number after an integer type, returning
18275    /// nothing. `TINYINT(1)` etc.
18276    /// v7.39 (round 360) — does the parenthesised group ahead contain a
18277    /// comma, i.e. is it MySQL's `(m,d)` rather than PG's `(p)`?
18278    fn peek_paren_has_comma(&self) -> bool {
18279        let mut i = self.pos + 1;
18280        let mut depth = 1usize;
18281        while depth > 0 {
18282            match self.tokens.get(i) {
18283                Some(Token::LParen) => depth += 1,
18284                Some(Token::RParen) => depth -= 1,
18285                Some(Token::Comma) if depth == 1 => return true,
18286                None | Some(Token::Eof) => return false,
18287                _ => {}
18288            }
18289            i += 1;
18290        }
18291        false
18292    }
18293
18294    /// v7.39 (round 424) — the same optional `(N)` modifier, but RETURNING
18295    /// the number. Temporal columns need it: MySQL's `DATETIME(3)` declares a
18296    /// fractional-seconds precision that drives write truncation and render
18297    /// padding, where `consume_optional_paren_size` throws it away.
18298    /// `Some(0)` for an explicit `(0)`, `None` when no modifier is written.
18299    fn take_optional_paren_size(&mut self) -> Option<u8> {
18300        let Some(Token::Integer(n)) = self
18301            .tokens
18302            .get(self.pos + 1)
18303            .filter(|_| matches!(self.peek(), Token::LParen))
18304            .cloned()
18305        else {
18306            self.consume_optional_paren_size();
18307            return None;
18308        };
18309        if !matches!(self.tokens.get(self.pos + 2), Some(Token::RParen)) {
18310            self.consume_optional_paren_size();
18311            return None;
18312        }
18313        self.consume_optional_paren_size();
18314        u8::try_from(n).ok()
18315    }
18316
18317    fn consume_optional_paren_size(&mut self) {
18318        if !matches!(self.peek(), Token::LParen) {
18319            return;
18320        }
18321        self.advance();
18322        // Skip until matching RParen (allow nested or any tokens).
18323        let mut depth = 1usize;
18324        while depth > 0 {
18325            match self.peek() {
18326                Token::LParen => depth += 1,
18327                Token::RParen => depth -= 1,
18328                Token::Eof => return,
18329                _ => {}
18330            }
18331            self.advance();
18332        }
18333    }
18334
18335    fn parse_paren_size(&mut self, label: &str) -> Result<u32, ParseError> {
18336        if !matches!(self.peek(), Token::LParen) {
18337            return Err(self.err(format!("{label} type requires (N), got {:?}", self.peek())));
18338        }
18339        self.advance();
18340        let n = match self.advance() {
18341            Token::Integer(n) if n > 0 => u32::try_from(n).map_err(|_| ParseError {
18342                message: format!("{label} size too large: {n}"),
18343                token_pos: self.consumed_pos(),
18344            })?,
18345            other => {
18346                return Err(ParseError {
18347                    message: format!("expected positive integer {label} size, got {other:?}"),
18348                    token_pos: self.consumed_pos(),
18349                });
18350            }
18351        };
18352        if !matches!(self.peek(), Token::RParen) {
18353            return Err(self.err(format!(
18354                "expected ')' after {label} size, got {:?}",
18355                self.peek()
18356            )));
18357        }
18358        self.advance();
18359        Ok(n)
18360    }
18361
18362    /// v7.39 (round 406) — the `ON CONFLICT DO NOTHING` clause that MySQL's
18363    /// `INSERT IGNORE` lowers to: a bare target (arbitrate on every unique
18364    /// key, like MySQL) whose action skips conflicting rows.
18365    /// v7.39 (round 419) — resolve the conflict clause for ANY of the four
18366    /// INSERT source forms (VALUES / SELECT / parenthesized source / WITH).
18367    /// Before this the MySQL upsert lowerings (`ON DUPLICATE KEY UPDATE`,
18368    /// `REPLACE INTO`) were wired into the VALUES branch ONLY, so the very
18369    /// common bulk-upsert spellings —
18370    ///     INSERT INTO t SELECT … ON DUPLICATE KEY UPDATE c = VALUES(c)
18371    ///     REPLACE INTO t SELECT …
18372    /// — were a parse error / a duplicate-key failure respectively.
18373    ///
18374    /// Precedence: an explicitly written clause beats a statement-level flag.
18375    /// `ON DUPLICATE KEY UPDATE` first, then PG's own `ON CONFLICT`, then the
18376    /// implicit `REPLACE` and `IGNORE` lowerings.
18377    fn parse_insert_conflict_clause(
18378        &mut self,
18379        replace: bool,
18380        ignore: bool,
18381    ) -> Result<Option<crate::ast::OnConflictClause>, ParseError> {
18382        if let Some(c) = self.parse_optional_on_duplicate_key()? {
18383            return Ok(Some(c));
18384        }
18385        if let Some(c) = self.parse_optional_on_conflict()? {
18386            return Ok(Some(c));
18387        }
18388        if replace {
18389            // REPLACE INTO = delete-then-insert, which PG spells as
18390            // `ON CONFLICT DO UPDATE SET` over every column; the engine
18391            // reads an empty assignment list as "take the incoming row".
18392            return Ok(Some(crate::ast::OnConflictClause {
18393                target_columns: Vec::new(),
18394                index_where: None,
18395                constraint_name: None,
18396                mysql_lowered: true,
18397                action: crate::ast::OnConflictAction::Update {
18398                    assignments: Vec::new(),
18399                    where_: None,
18400                },
18401            }));
18402        }
18403        if ignore {
18404            return Ok(Some(Self::insert_ignore_clause()));
18405        }
18406        Ok(None)
18407    }
18408
18409    /// v7.39 (round 419, extracted from the VALUES branch) — MySQL's
18410    /// `ON DUPLICATE KEY UPDATE col = expr [, …]`. Bare target (MySQL
18411    /// watches every unique key, which `mysql_lowered` records); `VALUES(col)`
18412    /// in an assignment is MySQL's spelling of `EXCLUDED.col`.
18413    fn parse_optional_on_duplicate_key(
18414        &mut self,
18415    ) -> Result<Option<crate::ast::OnConflictClause>, ParseError> {
18416        if !(matches!(self.peek(), Token::On)
18417            && matches!(self.tokens.get(self.pos + 1),
18418                Some(Token::Ident(s)) if s.eq_ignore_ascii_case("duplicate")))
18419        {
18420            return Ok(None);
18421        }
18422        self.advance(); // ON
18423        self.advance(); // DUPLICATE
18424        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("key")) {
18425            return Err(self.err(format!(
18426                "expected KEY after ON DUPLICATE, got {:?}",
18427                self.peek()
18428            )));
18429        }
18430        self.advance();
18431        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("update")) {
18432            return Err(self.err(format!(
18433                "expected UPDATE after ON DUPLICATE KEY, got {:?}",
18434                self.peek()
18435            )));
18436        }
18437        self.advance();
18438        let mut assignments: Vec<(String, Expr)> = Vec::new();
18439        loop {
18440            let col = self.expect_ident_like()?;
18441            if !matches!(self.peek(), Token::Eq) {
18442                return Err(self.err(format!(
18443                    "expected '=' in ON DUPLICATE KEY UPDATE, got {:?}",
18444                    self.peek()
18445                )));
18446            }
18447            self.advance();
18448            let mut expr = self.parse_expr(0)?;
18449            Self::rewrite_mysql_values_refs(&mut expr);
18450            assignments.push((col, expr));
18451            if matches!(self.peek(), Token::Comma) {
18452                self.advance();
18453                continue;
18454            }
18455            break;
18456        }
18457        Ok(Some(crate::ast::OnConflictClause {
18458            target_columns: Vec::new(),
18459            index_where: None,
18460            constraint_name: None,
18461            mysql_lowered: true,
18462            action: crate::ast::OnConflictAction::Update {
18463                assignments,
18464                where_: None,
18465            },
18466        }))
18467    }
18468
18469    fn insert_ignore_clause() -> crate::ast::OnConflictClause {
18470        crate::ast::OnConflictClause {
18471            target_columns: Vec::new(),
18472            index_where: None,
18473            constraint_name: None,
18474            mysql_lowered: true,
18475            action: crate::ast::OnConflictAction::Nothing,
18476        }
18477    }
18478
18479    fn parse_insert_stmt(&mut self, replace: bool) -> Result<Statement, ParseError> {
18480        debug_assert!(
18481            matches!(self.peek(), Token::Insert)
18482                || (replace
18483                    && matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("replace")))
18484        );
18485        self.advance();
18486        // v7.39 (round 406) — MySQL `INSERT IGNORE INTO t …` skips a row that
18487        // would raise a duplicate-key error instead of failing the statement,
18488        // i.e. `ON CONFLICT DO NOTHING` over every unique key. IGNORE is a
18489        // plain ident to the lexer; only the MySQL dialect accepts it here.
18490        let ignore = self.mysql_dialect
18491            && matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("ignore"));
18492        if ignore {
18493            self.advance();
18494        }
18495        if !matches!(self.peek(), Token::Into) {
18496            return Err(self.err(format!("expected INTO after INSERT, got {:?}", self.peek())));
18497        }
18498        self.advance();
18499        let table = self.expect_ident_like()?;
18500        // v7.39 (round 240) — `INSERT INTO t AS alias`: PG's insert_target
18501        // grammar requires the AS keyword here (a bare identifier would be
18502        // ambiguous with a column list). The alias is what the ON CONFLICT
18503        // DO UPDATE expressions refer to the target row by.
18504        let alias = if matches!(self.peek(), Token::As) {
18505            self.advance();
18506            Some(self.expect_ident_like()?)
18507        } else {
18508            None
18509        };
18510        // v7.39 (round 428) — MySQL's SET-form INSERT:
18511        //     INSERT INTO t SET a = 1, b = 'x'
18512        // It is exactly `INSERT INTO t (a, b) VALUES (1, 'x')` — omitted
18513        // columns take their DEFAULT, `SET a = DEFAULT` is legal, and it
18514        // composes with IGNORE / ON DUPLICATE KEY UPDATE / REPLACE (all
18515        // measured). So it lowers to the column list + one VALUES row and
18516        // rejoins the ordinary path, which already handles every one of
18517        // those. PG has no such spelling, hence the dialect gate.
18518        if self.mysql_dialect
18519            && matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("set"))
18520        {
18521            self.advance(); // SET
18522            let mut names = Vec::new();
18523            let mut values = Vec::new();
18524            loop {
18525                names.push(self.expect_ident_like()?);
18526                if !matches!(self.peek(), Token::Eq) {
18527                    return Err(self.err(alloc::format!(
18528                        "expected '=' in INSERT … SET, got {:?}",
18529                        self.peek()
18530                    )));
18531                }
18532                self.advance();
18533                // `SET a = DEFAULT` rides the same `__column_default` marker
18534                // the VALUES-row and UPDATE-SET paths use; the INSERT
18535                // executor resolves it against the target column.
18536                if matches!(self.peek(), Token::Default) {
18537                    self.advance();
18538                    values.push(Expr::FunctionCall {
18539                        name: "__column_default".to_string(),
18540                        args: Vec::new(),
18541                    });
18542                } else {
18543                    values.push(self.parse_expr(0)?);
18544                }
18545                if matches!(self.peek(), Token::Comma) {
18546                    self.advance();
18547                    continue;
18548                }
18549                break;
18550            }
18551            let on_conflict = self.parse_insert_conflict_clause(replace, ignore)?;
18552            let returning = self.parse_optional_returning()?;
18553            return Ok(Statement::Insert(InsertStatement {
18554                ctes: Vec::new(),
18555                table,
18556                alias,
18557                columns: Some(names),
18558                rows: alloc::vec![values],
18559                select_source: None,
18560                // MySQL's SET form has no `OVERRIDING …` clause (that is
18561                // PG's identity-column spelling).
18562                overriding: Overriding::None,
18563                mysql_ignore: ignore,
18564                on_conflict,
18565                returning,
18566            }));
18567        }
18568        // Optional column list — `INSERT INTO t (a, b) VALUES ...`.
18569        // v7.39 (round 151) — a SELECT or WITH right after the paren is
18570        // a parenthesized query source instead (PG select_with_parens:
18571        // `INSERT INTO t (SELECT …)` / `INSERT INTO t (WITH … SELECT …)`);
18572        // both keywords are reserved in PG, so no column list can start
18573        // with them.
18574        let columns = if matches!(self.peek(), Token::LParen) {
18575            self.advance();
18576            if matches!(self.peek(), Token::Select) || self.peek_is_with_kw() {
18577                let select_stmt = if self.peek_is_with_kw() {
18578                    self.advance();
18579                    self.parse_nested_with_select()?
18580                } else {
18581                    match self.parse_select_stmt()? {
18582                        Statement::Select(s) => s,
18583                        other => {
18584                            return Err(self.err(alloc::format!(
18585                                "expected SELECT in parenthesized INSERT source, got {other:?}"
18586                            )));
18587                        }
18588                    }
18589                };
18590                if !matches!(self.peek(), Token::RParen) {
18591                    return Err(self.err(format!(
18592                        "expected ')' after parenthesized INSERT source, got {:?}",
18593                        self.peek()
18594                    )));
18595                }
18596                self.advance();
18597                let on_conflict = self.parse_insert_conflict_clause(replace, ignore)?;
18598                let returning = self.parse_optional_returning()?;
18599                return Ok(Statement::Insert(InsertStatement {
18600                    ctes: Vec::new(),
18601                    table,
18602                    alias: alias.clone(),
18603                    columns: None,
18604                    rows: Vec::new(),
18605                    select_source: Some(Box::new(select_stmt)),
18606                    on_conflict,
18607                    returning,
18608                    overriding: Overriding::None,
18609                    mysql_ignore: ignore,
18610                }));
18611            }
18612            let mut names = Vec::new();
18613            loop {
18614                names.push(self.expect_ident_like()?);
18615                match self.peek() {
18616                    Token::Comma => {
18617                        self.advance();
18618                    }
18619                    Token::RParen => {
18620                        self.advance();
18621                        break;
18622                    }
18623                    other => {
18624                        return Err(self.err(format!(
18625                            "expected ',' or ')' in INSERT column list, got {other:?}"
18626                        )));
18627                    }
18628                }
18629            }
18630            Some(names)
18631        } else {
18632            None
18633        };
18634        // PG 10+ `OVERRIDING {SYSTEM | USER} VALUE` — pg_dump emits
18635        // OVERRIDING SYSTEM VALUE for its identity columns. The clause
18636        // is captured on the statement so the engine can apply PG's
18637        // GENERATED ALWAYS / BY DEFAULT interaction (v7.38, read01).
18638        let overriding = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("overriding"))
18639        {
18640            self.advance();
18641            let which = self.expect_ident_like()?;
18642            let ov = if which.eq_ignore_ascii_case("system") {
18643                Overriding::System
18644            } else if which.eq_ignore_ascii_case("user") {
18645                Overriding::User
18646            } else {
18647                return Err(self.err(format!(
18648                    "expected SYSTEM or USER after OVERRIDING, got {which:?}"
18649                )));
18650            };
18651            if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("value")) {
18652                return Err(self.err(format!(
18653                    "expected VALUE after OVERRIDING {}, got {:?}",
18654                    which.to_ascii_uppercase(),
18655                    self.peek()
18656                )));
18657            }
18658            self.advance();
18659            ov
18660        } else {
18661            Overriding::None
18662        };
18663        // `INSERT INTO t DEFAULT VALUES` — a single row made
18664        // entirely of column defaults. Lower to the permuted
18665        // column-list path with an empty list: every schema column
18666        // is unmapped, so the engine fills each from its default
18667        // (serials advance, plain defaults evaluate, the rest NULL).
18668        if matches!(self.peek(), Token::Default) {
18669            self.advance();
18670            if !matches!(self.peek(), Token::Values) {
18671                return Err(self.err(format!(
18672                    "expected VALUES after DEFAULT in INSERT, got {:?}",
18673                    self.peek()
18674                )));
18675            }
18676            self.advance();
18677            if columns.is_some() {
18678                return Err(self.err("DEFAULT VALUES cannot follow an INSERT column list".into()));
18679            }
18680            let on_conflict = self.parse_insert_conflict_clause(replace, ignore)?;
18681            let returning = self.parse_optional_returning()?;
18682            return Ok(Statement::Insert(InsertStatement {
18683                ctes: Vec::new(),
18684                table,
18685                alias: alias.clone(),
18686                columns: Some(Vec::new()),
18687                rows: alloc::vec![Vec::new()],
18688                select_source: None,
18689                on_conflict,
18690                returning,
18691                overriding,
18692                mysql_ignore: ignore,
18693            }));
18694        }
18695        // v7.13.0 — `INSERT INTO t [(cols)] SELECT …` (mailrs
18696        // round-5 G4). Dispatch on VALUES vs SELECT. v7.39 (round 151)
18697        // — a WITH-headed source query (`INSERT INTO t WITH c AS (…)
18698        // SELECT …`) heads the SOURCE select, as in PG (the statement's
18699        // own WITH comes before INSERT).
18700        if matches!(self.peek(), Token::Select) || self.peek_is_with_kw() {
18701            let select_stmt = if self.peek_is_with_kw() {
18702                self.advance();
18703                self.parse_nested_with_select()?
18704            } else {
18705                match self.parse_select_stmt()? {
18706                    Statement::Select(s) => s,
18707                    other => {
18708                        return Err(self.err(alloc::format!(
18709                            "expected SELECT after INSERT INTO ... target, got {other:?}"
18710                        )));
18711                    }
18712                }
18713            };
18714            let on_conflict = self.parse_insert_conflict_clause(replace, ignore)?;
18715            let returning = self.parse_optional_returning()?;
18716            return Ok(Statement::Insert(InsertStatement {
18717                ctes: Vec::new(),
18718                table,
18719                alias: alias.clone(),
18720                columns,
18721                rows: Vec::new(),
18722                select_source: Some(Box::new(select_stmt)),
18723                on_conflict,
18724                returning,
18725                overriding,
18726                mysql_ignore: ignore,
18727            }));
18728        }
18729        if !matches!(self.peek(), Token::Values) {
18730            return Err(self.err(format!(
18731                "expected VALUES or SELECT after table name, got {:?}",
18732                self.peek()
18733            )));
18734        }
18735        self.advance();
18736        if !matches!(self.peek(), Token::LParen) {
18737            return Err(self.err(format!("expected '(' after VALUES, got {:?}", self.peek())));
18738        }
18739        let mut rows = Vec::new();
18740        loop {
18741            // Each iteration consumes one `(expr, expr, …)` tuple.
18742            if !matches!(self.peek(), Token::LParen) {
18743                return Err(self.err(format!(
18744                    "expected '(' for next VALUES tuple, got {:?}",
18745                    self.peek()
18746                )));
18747            }
18748            self.advance();
18749            let mut tuple = Vec::new();
18750            loop {
18751                // v7.38 (read01) — `INSERT INTO t VALUES (…, DEFAULT, …)` uses
18752                // the column's declared default for that slot. Rides out as the
18753                // same `__column_default` marker call the UPDATE `SET c = DEFAULT`
18754                // path uses; the INSERT executor resolves it per target column.
18755                if matches!(self.peek(), Token::Default) {
18756                    self.advance();
18757                    tuple.push(Expr::FunctionCall {
18758                        name: "__column_default".to_string(),
18759                        args: Vec::new(),
18760                    });
18761                } else {
18762                    tuple.push(self.parse_expr(0)?);
18763                }
18764                match self.peek() {
18765                    Token::Comma => {
18766                        self.advance();
18767                    }
18768                    Token::RParen => {
18769                        self.advance();
18770                        break;
18771                    }
18772                    other => {
18773                        return Err(self.err(format!(
18774                            "expected ',' or ')' in VALUES tuple, got {other:?}"
18775                        )));
18776                    }
18777                }
18778            }
18779            if tuple.is_empty() {
18780                return Err(self.err("INSERT VALUES tuple requires at least one value".into()));
18781            }
18782            rows.push(tuple);
18783            // Continue with comma-separated tuples.
18784            if matches!(self.peek(), Token::Comma) {
18785                self.advance();
18786            } else {
18787                break;
18788            }
18789        }
18790        // MySQL `ON DUPLICATE KEY UPDATE col = expr [, …]` — lowers
18791        // to ON CONFLICT DO UPDATE with an empty conflict target
18792        // (the engine picks the table's first unique index, which
18793        // matches MySQL's any-unique-key behaviour for the common
18794        // single-key case). `VALUES(col)` in the assignments is
18795        // MySQL's spelling of EXCLUDED.col.
18796        let on_conflict = self.parse_insert_conflict_clause(replace, ignore)?;
18797        let returning = self.parse_optional_returning()?;
18798        Ok(Statement::Insert(InsertStatement {
18799            ctes: Vec::new(),
18800            table,
18801            alias,
18802            columns,
18803            rows,
18804            select_source: None,
18805            on_conflict,
18806            returning,
18807            overriding,
18808            mysql_ignore: ignore,
18809        }))
18810    }
18811
18812    /// MySQL's `VALUES(col)` inside ON DUPLICATE KEY UPDATE reads
18813    /// the incoming row's value — exactly PG's EXCLUDED.col.
18814    fn rewrite_mysql_values_refs(e: &mut Expr) {
18815        match e {
18816            Expr::FunctionCall { name, args }
18817                if name.eq_ignore_ascii_case("values")
18818                    && args.len() == 1
18819                    && matches!(&args[0], Expr::Column(c) if c.qualifier.is_none()) =>
18820            {
18821                let Expr::Column(c) = &args[0] else {
18822                    unreachable!("guarded above");
18823                };
18824                *e = Expr::Column(crate::ast::ColumnName {
18825                    qualifier: Some("EXCLUDED".to_string()),
18826                    name: c.name.clone(),
18827                });
18828            }
18829            Expr::FunctionCall { args, .. } => {
18830                for a in args {
18831                    Self::rewrite_mysql_values_refs(a);
18832                }
18833            }
18834            Expr::Binary { lhs, rhs, .. } => {
18835                Self::rewrite_mysql_values_refs(lhs);
18836                Self::rewrite_mysql_values_refs(rhs);
18837            }
18838            Expr::Unary { expr, .. } | Expr::Cast { expr, .. } => {
18839                Self::rewrite_mysql_values_refs(expr);
18840            }
18841            Expr::Case {
18842                operand,
18843                branches,
18844                else_branch,
18845            } => {
18846                if let Some(op) = operand {
18847                    Self::rewrite_mysql_values_refs(op);
18848                }
18849                for (w, t) in branches {
18850                    Self::rewrite_mysql_values_refs(w);
18851                    Self::rewrite_mysql_values_refs(t);
18852                }
18853                if let Some(el) = else_branch {
18854                    Self::rewrite_mysql_values_refs(el);
18855                }
18856            }
18857            _ => {}
18858        }
18859    }
18860
18861    /// v7.9.7 — parse the optional `ON CONFLICT (cols) DO …`
18862    /// clause sitting between the INSERT body and the trailing
18863    /// RETURNING. All keywords come in as bare idents; `ON` is
18864    /// a reserved Token though.
18865    fn parse_optional_on_conflict(
18866        &mut self,
18867    ) -> Result<Option<crate::ast::OnConflictClause>, ParseError> {
18868        if !matches!(self.peek(), Token::On) {
18869            return Ok(None);
18870        }
18871        // Peek further: we want exactly "ON CONFLICT ...". If the
18872        // next ident isn't "conflict", let some other parser handle.
18873        let next_is_conflict = matches!(
18874            self.tokens.get(self.pos + 1),
18875            Some(Token::Ident(s) | Token::QuotedIdent(s)) if s.eq_ignore_ascii_case("conflict")
18876        );
18877        if !next_is_conflict {
18878            return Ok(None);
18879        }
18880        self.advance(); // ON
18881        self.advance(); // CONFLICT
18882        // v7.37.17 (17.6 siblings) — `ON CONSTRAINT <name>` names
18883        // the constraint instead of listing columns (the pg_dump
18884        // form); the engine resolves it.
18885        let mut constraint_name: Option<String> = None;
18886        if matches!(self.peek(), Token::On) {
18887            self.advance(); // ON
18888            match self.advance() {
18889                Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("constraint") => {
18890                }
18891                other => {
18892                    return Err(self.err(alloc::format!(
18893                        "expected CONSTRAINT after ON CONFLICT ON, got {other:?}"
18894                    )));
18895                }
18896            }
18897            constraint_name = Some(self.expect_ident_like()?);
18898        }
18899        // Optional `(col [, col]*)` target list.
18900        let mut target_columns: Vec<String> = Vec::new();
18901        if matches!(self.peek(), Token::LParen) {
18902            self.advance();
18903            loop {
18904                target_columns.push(self.expect_ident_like()?);
18905                match self.peek() {
18906                    Token::Comma => {
18907                        self.advance();
18908                    }
18909                    Token::RParen => {
18910                        self.advance();
18911                        break;
18912                    }
18913                    other => {
18914                        return Err(self.err(alloc::format!(
18915                            "expected ',' or ')' in ON CONFLICT target list, got {other:?}"
18916                        )));
18917                    }
18918                }
18919            }
18920        }
18921        // v7.39 (round 240) — optional index predicate after the target
18922        // list: `ON CONFLICT (col) WHERE pred DO …`. PG uses it to infer a
18923        // PARTIAL unique index; SPG's arbiters are full indexes, which
18924        // satisfy any predicate, so it is parsed and carried but not
18925        // consulted (recorded residual: partial-unique-index arbiters).
18926        let index_where = if !target_columns.is_empty() && matches!(self.peek(), Token::Where) {
18927            self.advance();
18928            Some(self.parse_expr(0)?)
18929        } else {
18930            None
18931        };
18932        // Required `DO`.
18933        match self.advance() {
18934            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("do") => {}
18935            other => {
18936                return Err(self.err(alloc::format!(
18937                    "expected DO after ON CONFLICT [(…)], got {other:?}"
18938                )));
18939            }
18940        }
18941        // Action: NOTHING | UPDATE SET …
18942        let action = match self.advance() {
18943            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("nothing") => {
18944                crate::ast::OnConflictAction::Nothing
18945            }
18946            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("update") => {
18947                self.parse_on_conflict_update_action()?
18948            }
18949            other => {
18950                return Err(self.err(alloc::format!(
18951                    "expected NOTHING or UPDATE after ON CONFLICT DO, got {other:?}"
18952                )));
18953            }
18954        };
18955        Ok(Some(crate::ast::OnConflictClause {
18956            target_columns,
18957            index_where,
18958            constraint_name,
18959            mysql_lowered: false,
18960            action,
18961        }))
18962    }
18963
18964    /// v7.9.7 — tail of `ON CONFLICT … DO UPDATE`: parse
18965    /// `SET col = expr [, …] [WHERE cond]`. Caller already
18966    /// consumed `UPDATE`.
18967    fn parse_on_conflict_update_action(
18968        &mut self,
18969    ) -> Result<crate::ast::OnConflictAction, ParseError> {
18970        // `SET`
18971        match self.advance() {
18972            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("set") => {}
18973            other => {
18974                return Err(self.err(alloc::format!(
18975                    "expected SET after ON CONFLICT DO UPDATE, got {other:?}"
18976                )));
18977            }
18978        }
18979        let mut assignments: Vec<(String, Expr)> = Vec::new();
18980        loop {
18981            let col = self.expect_ident_like()?;
18982            if !matches!(self.peek(), Token::Eq) {
18983                return Err(self.err(alloc::format!(
18984                    "expected `=` after column in ON CONFLICT DO UPDATE SET, got {:?}",
18985                    self.peek()
18986                )));
18987            }
18988            self.advance();
18989            let value = self.parse_expr(0)?;
18990            assignments.push((col, value));
18991            if matches!(self.peek(), Token::Comma) {
18992                self.advance();
18993                continue;
18994            }
18995            break;
18996        }
18997        let where_ = if matches!(self.peek(), Token::Where) {
18998            self.advance();
18999            Some(self.parse_expr(0)?)
19000        } else {
19001            None
19002        };
19003        Ok(crate::ast::OnConflictAction::Update {
19004            assignments,
19005            where_,
19006        })
19007    }
19008
19009    fn parse_select_list(&mut self) -> Result<Vec<SelectItem>, ParseError> {
19010        let mut items = Vec::new();
19011        // v7.39 (round 341, V66) — PG's target list may be EMPTY
19012        // (`opt_target_list: target_list | /*EMPTY*/`): `SELECT FROM t`
19013        // answers one zero-column row per row of t, and a bare `SELECT`
19014        // answers a single zero-column row. SPG required at least one
19015        // item, so both were syntax errors. Recognised by the token that
19016        // follows — nothing that can start an expression appears here.
19017        if self.select_list_is_empty_here() {
19018            return Ok(items);
19019        }
19020        loop {
19021            items.push(self.parse_select_item()?);
19022            if matches!(self.peek(), Token::Comma) {
19023                self.advance();
19024            } else {
19025                break;
19026            }
19027        }
19028        Ok(items)
19029    }
19030
19031    /// Is the target list empty at this point — i.e. does the next token
19032    /// end the SELECT's item list rather than start an item?
19033    fn select_list_is_empty_here(&self) -> bool {
19034        match self.peek() {
19035            Token::From
19036            | Token::Where
19037            | Token::Group
19038            | Token::Having
19039            | Token::Order
19040            | Token::Limit
19041            | Token::Offset
19042            | Token::Semicolon
19043            | Token::RParen
19044            | Token::Union
19045            | Token::Except
19046            | Token::Eof => true,
19047            // `FETCH FIRST … ROWS ONLY` and `WINDOW w AS …` are spelled
19048            // with unreserved keywords, so they arrive as plain idents.
19049            Token::Ident(s) => {
19050                s.eq_ignore_ascii_case("fetch")
19051                    || s.eq_ignore_ascii_case("window")
19052                    || s.eq_ignore_ascii_case("intersect")
19053            }
19054            _ => false,
19055        }
19056    }
19057
19058    fn parse_select_item(&mut self) -> Result<SelectItem, ParseError> {
19059        if matches!(self.peek(), Token::Star) {
19060            self.advance();
19061            return Ok(SelectItem::Wildcard);
19062        }
19063        // v7.39 (read01 round 128) — qualified wildcard `qualifier.*`. Intercept
19064        // BEFORE `parse_expr`, which would treat `q.` as a qualified column and
19065        // choke on the `*` ("expected identifier, got Star"). The lookahead is
19066        // `<ident> . *` with nothing binding tighter.
19067        if let Token::Ident(q) | Token::QuotedIdent(q) = self.peek().clone() {
19068            if matches!(self.tokens.get(self.pos + 1), Some(Token::Dot))
19069                && matches!(self.tokens.get(self.pos + 2), Some(Token::Star))
19070            {
19071                self.advance(); // qualifier
19072                self.advance(); // .
19073                self.advance(); // *
19074                return Ok(SelectItem::QualifiedWildcard(q));
19075            }
19076        }
19077        let start_tok = self.pos;
19078        let expr = self.parse_expr(0)?;
19079        let end_tok = self.consumed_pos();
19080        // v7.39 (read01 round 69) — `(f(args)).*`: expand the RECORD a
19081        // multi-column function returns into columns. Marked here and lowered in
19082        // `parse_bare_select`, where the FROM clause is in hand.
19083        if matches!(self.peek(), Token::Dot)
19084            && matches!(self.tokens.get(self.pos + 1), Some(Token::Star))
19085        {
19086            self.advance(); // .
19087            self.advance(); // *
19088            return Ok(SelectItem::Expr {
19089                expr: Expr::FunctionCall {
19090                    name: "__record_expand".to_string(),
19091                    args: alloc::vec![expr],
19092                },
19093                alias: None,
19094            });
19095        }
19096        // v7.39.2 — MySQL lets a STRING name a projection item, with or
19097        // without `AS`: `SELECT 1 'x'`, `SELECT COUNT(*) 'total'`,
19098        // `SELECT 1 'a b'` (which is why one quotes it). SPG answered
19099        // `syntax error at or near "'x'"` to all of them.
19100        //
19101        // Only here, not in `parse_optional_alias`: that one also names
19102        // TABLES, and MySQL 9.7.2 refuses a string there — `FROM t 'ta'`
19103        // and `FROM t AS 'ta'` are both syntax errors, measured. And only
19104        // after the lexer's own rule has joined adjacent literals, or
19105        // `SELECT 'a' 'b'` would read as a literal aliased `b` where
19106        // MySQL answers the concatenation `ab`.
19107        if self.mysql_dialect {
19108            let at_as = matches!(self.peek(), Token::As)
19109                && matches!(self.tokens.get(self.pos + 1), Some(Token::String(_)));
19110            if at_as {
19111                self.advance();
19112            }
19113            if let Token::String(name) = self.peek().clone() {
19114                self.advance();
19115                return Ok(SelectItem::Expr {
19116                    expr,
19117                    alias: Some(name),
19118                });
19119            }
19120        }
19121        let alias = match self.parse_optional_alias()? {
19122            Some(a) => Some(a),
19123            None => self.mysql_item_label(&expr, start_tok, end_tok),
19124        };
19125        Ok(SelectItem::Expr { expr, alias })
19126    }
19127
19128    /// v7.39 (round 506) — the name MariaDB 11 gives a projection item that
19129    /// carries no `AS`, filled in here so every downstream path reports it
19130    /// without knowing the rule. `None` leaves the item un-aliased, which is
19131    /// what a PG session always gets.
19132    ///
19133    /// Measured against MariaDB 11, three rules and no more:
19134    ///
19135    /// | item             | label      | why                          |
19136    /// |------------------|------------|------------------------------|
19137    /// | `lbl.a`          | `a`        | a column reports its name    |
19138    /// | `'it''s'`        | `it's`     | a string reports its VALUE   |
19139    /// | `a  +  b`        | `a  +  b`  | anything else, source text   |
19140    ///
19141    /// The third is why this lives in the parser at all: the label is the
19142    /// text the client WROTE, down to the spacing, so it cannot be printed
19143    /// back out of the parsed shape. `COUNT( * )` names itself `COUNT( * )`.
19144    ///
19145    /// Comments survive, and that is right: through a `mariadb` CLI both
19146    /// servers answer `a  + b` for `SELECT a /* c */ + b`, but that is the
19147    /// CLIENT stripping the comment before it sends. Asked over the raw
19148    /// protocol, MariaDB answers `a /* c */ + b` — byte for byte what this
19149    /// produces.
19150    fn mysql_item_label(&self, expr: &Expr, start_tok: usize, end_tok: usize) -> Option<String> {
19151        if !self.mysql_dialect {
19152            return None;
19153        }
19154        match expr {
19155            // A column already reports its own name downstream; naming it
19156            // again here would only re-state the qualifier the label drops.
19157            Expr::Column(_) => None,
19158            // v7.39.3 — `SELECT 'a' 'b'` is ONE literal whose value is
19159            // `ab`, and MySQL 9.7.2 names the column `a`: the label is
19160            // the first segment as written, not the joined value
19161            // (measured). The lexer logs where it joined them.
19162            Expr::Literal(Literal::String(v)) => Some(
19163                self.merged_first_len(start_tok)
19164                    .and_then(|n| v.get(..n))
19165                    .map_or_else(|| v.clone(), String::from),
19166            ),
19167            _ => self.source_span(start_tok, end_tok).map(str::to_string),
19168        }
19169    }
19170
19171    /// v7.37.17 (17.6 siblings) — parse `(row), (row), …` after a
19172    /// consumed VALUES keyword. Each row lowers to a constant SELECT
19173    /// with PG's default column1..columnN names; subsequent rows
19174    /// chain as UNION ALL peers. Shared by the FROM-position
19175    /// `( VALUES … )` arm and the top-level bare VALUES statement.
19176    fn parse_values_rows_body(&mut self) -> Result<SelectStatement, ParseError> {
19177        let mut row_selects: Vec<SelectStatement> = Vec::new();
19178        loop {
19179            if !matches!(self.peek(), Token::LParen) {
19180                return Err(self.err(alloc::format!(
19181                    "expected '(' to start a VALUES row, got {:?}",
19182                    self.peek()
19183                )));
19184            }
19185            self.advance(); // (
19186            let mut items: Vec<SelectItem> = Vec::new();
19187            loop {
19188                let expr = self.parse_expr(0)?;
19189                items.push(SelectItem::Expr {
19190                    expr,
19191                    alias: Some(alloc::format!("column{}", items.len() + 1)),
19192                });
19193                match self.peek() {
19194                    Token::Comma => {
19195                        self.advance();
19196                    }
19197                    Token::RParen => break,
19198                    other => {
19199                        return Err(self.err(alloc::format!(
19200                            "expected ',' or ')' in VALUES row, got {other:?}"
19201                        )));
19202                    }
19203                }
19204            }
19205            self.advance(); // )
19206            row_selects.push(SelectStatement {
19207                locking: None,
19208                ctes: Vec::new(),
19209                distinct: false,
19210                distinct_on: Vec::new(),
19211                items,
19212                from: None,
19213                where_: None,
19214                group_by: None,
19215                group_by_all: false,
19216                having: None,
19217                unions: Vec::new(),
19218                order_by: Vec::new(),
19219                limit: None,
19220                offset: None,
19221                limit_with_ties: false,
19222                window_check_exprs: Vec::new(),
19223            });
19224            if matches!(self.peek(), Token::Comma) {
19225                self.advance();
19226                continue;
19227            }
19228            break;
19229        }
19230        let mut head = row_selects.remove(0);
19231        head.unions = row_selects
19232            .into_iter()
19233            .map(|s| (UnionKind::All, s))
19234            .collect();
19235        Ok(head)
19236    }
19237
19238    fn parse_table_ref(&mut self) -> Result<TableRef, ParseError> {
19239        // v7.39 (round 621) — `FROM ONLY <table>` excludes a table's
19240        // children. It was read as a table NAMED `only`, so the query
19241        // failed on `relation "only" does not exist`.
19242        //
19243        // v7.39 (round 644) — and it is no longer a no-op. Round 621
19244        // absorbed the keyword, reasoning that SPG's children are
19245        // separate relations a plain scan does not descend into, so ONLY
19246        // already described the scan. That stopped being true when a
19247        // partition parent started unioning its children: measured,
19248        // `SELECT count(*) FROM ONLY <partitioned parent>` answered 2
19249        // where PG answers 0. The flag is carried now.
19250        let mut only = false;
19251        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("only"))
19252            && matches!(
19253                self.tokens.get(self.pos + 1),
19254                Some(Token::Ident(_) | Token::QuotedIdent(_))
19255            )
19256        {
19257            only = true;
19258            self.advance();
19259        }
19260        // `LATERAL generate_series(...)` / `LATERAL unnest(...)` —
19261        // for these SRFs the keyword is noise at parse time: the
19262        // join executor already substitutes outer-column references
19263        // into unnest_expr / generate_series_args per outer row
19264        // (v7.37.43-T4.5 substitute_outer_in_table_ref), and PG
19265        // licences the correlation even without the keyword. Absorb
19266        // it and fall through to the SRF arms below.
19267        // v7.39 (read01 round 69) — `LATERAL <fn>(args)` for ANY function, not
19268        // just the four builtin SRFs: a user set-returning function on a JOIN's
19269        // right side is the whole point of LATERAL. The keyword stays noise at
19270        // parse time — the join executor substitutes the outer row into the
19271        // call's arguments per outer row.
19272        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("lateral"))
19273            && matches!(
19274                self.tokens.get(self.pos + 1),
19275                // The json_each family has its OWN `LATERAL …` arm below, which
19276                // needs to see the keyword — absorbing it here would send those
19277                // calls down the generic table-function channel instead.
19278                Some(Token::Ident(s) | Token::QuotedIdent(s)) if !is_json_each_name(s)
19279            )
19280            && matches!(self.tokens.get(self.pos + 2), Some(Token::LParen))
19281        {
19282            self.advance(); // LATERAL
19283        }
19284        // v7.37.43-T4.5 — `LATERAL jsonb_each_text(<expr>)` —
19285        // set-returning function whose argument may reference a
19286        // preceding FROM item. We rewrite this to
19287        // `LATERAL (SELECT key, value FROM jsonb_each_text(<expr>)
19288        // AS __srf__) AS <alias>` so the existing LATERAL subquery
19289        // executor handles per-outer-row evaluation and the
19290        // SRF-primary jsonb_each_text path handles the inner
19291        // materialisation. Sentori 0067 backfill is the dogfood
19292        // shape.
19293        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("lateral"))
19294            && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s) | Token::QuotedIdent(s)) if is_json_each_name(s))
19295            && matches!(self.tokens.get(self.pos + 2), Some(Token::LParen))
19296        {
19297            self.advance(); // LATERAL
19298            let each_fn = match self.peek() {
19299                Token::Ident(s) | Token::QuotedIdent(s) => s.to_ascii_lowercase(),
19300                _ => unreachable!(),
19301            };
19302            self.advance(); // jsonb_each[_text] / json_each[_text]
19303            self.advance(); // (
19304            let arg = self.parse_expr(0)?;
19305            if !matches!(self.peek(), Token::RParen) {
19306                return Err(self.err(alloc::format!(
19307                    "expected ')' after LATERAL {each_fn}() argument, got {:?}",
19308                    self.peek()
19309                )));
19310            }
19311            self.advance();
19312            let (alias_ident, column_aliases) = self.parse_optional_alias_with_columns()?;
19313            let alias = alias_ident.clone().unwrap_or_else(|| each_fn.clone());
19314            // Synthesise: SELECT __srf__.key AS <key_alias>, __srf__.value AS <value_alias>
19315            //               FROM jsonb_each_text(<arg>) AS __srf__
19316            // PG's `AS kv(key, value)` column-alias list maps
19317            // positions to names; default to (key, value) when
19318            // omitted (matching the SRF's natural column names).
19319            let srf_alias = "__srf__".to_string();
19320            let key_alias = column_aliases
19321                .first()
19322                .cloned()
19323                .unwrap_or_else(|| "key".to_string());
19324            let value_alias = column_aliases
19325                .get(1)
19326                .cloned()
19327                .unwrap_or_else(|| "value".to_string());
19328            let inner_select = crate::ast::SelectStatement {
19329                locking: None,
19330                ctes: Vec::new(),
19331                distinct: false,
19332                distinct_on: Vec::new(),
19333                items: alloc::vec![
19334                    crate::ast::SelectItem::Expr {
19335                        expr: crate::ast::Expr::Column(crate::ast::ColumnName {
19336                            qualifier: Some(srf_alias.clone()),
19337                            name: "key".to_string(),
19338                        }),
19339                        alias: Some(key_alias),
19340                    },
19341                    crate::ast::SelectItem::Expr {
19342                        expr: crate::ast::Expr::Column(crate::ast::ColumnName {
19343                            qualifier: Some(srf_alias.clone()),
19344                            name: "value".to_string(),
19345                        }),
19346                        alias: Some(value_alias),
19347                    },
19348                ],
19349                from: Some(crate::ast::FromClause {
19350                    primary: TableRef {
19351                        name: srf_alias.clone(),
19352                        alias: Some(srf_alias.clone()),
19353                        only: false,
19354                        as_of_segment: None,
19355                        unnest_expr: None,
19356                        unnest_column_aliases: Vec::new(),
19357                        with_ordinality: false,
19358                        generate_series_args: None,
19359                        lateral_subquery: None,
19360                        jsonb_each_text_arg: Some((each_fn, Box::new(arg))),
19361                        table_fn_call: None,
19362                        rows_from: None,
19363                        json_table: None,
19364                        scalar_fn_item: false,
19365                    },
19366                    joins: Vec::new(),
19367                }),
19368                where_: None,
19369                group_by: None,
19370                group_by_all: false,
19371                having: None,
19372                unions: Vec::new(),
19373                order_by: Vec::new(),
19374                limit: None,
19375                offset: None,
19376                limit_with_ties: false,
19377                window_check_exprs: Vec::new(),
19378            };
19379            return Ok(TableRef {
19380                name: alias.clone(),
19381                alias: Some(alias),
19382                only: false,
19383                as_of_segment: None,
19384                unnest_expr: None,
19385                unnest_column_aliases: Vec::new(),
19386                with_ordinality: false,
19387                generate_series_args: None,
19388                lateral_subquery: Some(Box::new(inner_select)),
19389                jsonb_each_text_arg: None,
19390                table_fn_call: None,
19391                rows_from: None,
19392                json_table: None,
19393                scalar_fn_item: false,
19394            });
19395        }
19396        // v7.37.43-T4.5 — bare `CROSS JOIN jsonb_each_text(t.col)`
19397        // without an explicit `LATERAL` keyword is the same shape
19398        // PG accepts (SRF naturally licences lateral correlation).
19399        // We mirror the LATERAL rewrite when the argument syntactic-
19400        // ally references an outer column (Column { qualifier:
19401        // Some(_), … }). For simplicity we apply the rewrite
19402        // whenever the SRF directly follows JOIN/CROSS JOIN/comma
19403        // in the FROM-list — caller-side join parsing positions
19404        // this peek correctly.
19405        // (Implementation note: detection lives below; the LATERAL
19406        // branch above already covers the explicit form; the bare
19407        // form falls through to the plain SRF arm and the engine
19408        // treats it as a constant-arg SRF if no outer reference is
19409        // present.)
19410        // v7.17.0 Phase 3.P0-41 — `LATERAL ( SELECT … )` derived
19411        // table. Detect at the head so it claims precedence over
19412        // every other table-ref shape (unnest / generate_series /
19413        // bare ident); the lateral subquery itself follows the
19414        // regular SELECT grammar.
19415        // v7.37.17 (17.6 siblings) — `FROM ( VALUES (…), (…) ) [AS]
19416        // t(cols)`. Each row lowers to a constant SELECT with PG's
19417        // default column1..columnN names; subsequent rows chain as
19418        // UNION ALL peers. The result rides the derived-table
19419        // lateral_subquery channel — zero executor work.
19420        if matches!(self.peek(), Token::LParen)
19421            && matches!(self.tokens.get(self.pos + 1), Some(Token::Values))
19422        {
19423            self.advance(); // (
19424            self.advance(); // VALUES
19425            let head = self.parse_values_rows_body()?;
19426            if !matches!(self.peek(), Token::RParen) {
19427                return Err(self.err(alloc::format!(
19428                    "expected ')' after VALUES list, got {:?}",
19429                    self.peek()
19430                )));
19431            }
19432            self.advance();
19433            let (alias_ident, column_aliases) = self.parse_optional_alias_with_columns()?;
19434            let name = alias_ident.clone().unwrap_or_else(|| "values".to_string());
19435            return Ok(TableRef {
19436                name,
19437                alias: alias_ident,
19438                only: false,
19439                as_of_segment: None,
19440                unnest_expr: None,
19441                unnest_column_aliases: column_aliases,
19442                with_ordinality: false,
19443                generate_series_args: None,
19444                lateral_subquery: Some(Box::new(head)),
19445                jsonb_each_text_arg: None,
19446                table_fn_call: None,
19447                rows_from: None,
19448                json_table: None,
19449                scalar_fn_item: false,
19450            });
19451        }
19452        // v7.37.17 (17.6 siblings) — plain derived table:
19453        // `FROM ( SELECT … ) [AS] alias`. Rides the same
19454        // lateral_subquery channel the explicit LATERAL form uses —
19455        // an uncorrelated inner SELECT executes identically. The
19456        // inner parse carries UNION tails (they live on
19457        // SelectStatement.unions).
19458        // v7.37 D.20 — the derived-table inner may itself be a
19459        // parenthesized set-operation group (`FROM ((SELECT…) UNION
19460        // (SELECT…)) s`) or a CTE (`FROM (WITH … SELECT …) z`), not just a
19461        // bare `(SELECT …)`. parse_one_statement already routes a leading
19462        // `(` set-op group (its LParen arm) and a leading WITH
19463        // (parse_with_cte_then_select), so widen the second-token gate to
19464        // Select | LParen | WITH.
19465        // v7.39 (round 869) — `Table` joins that gate. `TABLE t` is
19466        // PG's spelling of `SELECT * FROM t` and is accepted wherever a
19467        // SELECT is, so `FROM (TABLE t) x` has to parse. The desugaring
19468        // has existed since the shorthand landed and `parse_bare_select`
19469        // already routes it ("valid anywhere a SELECT head is"); what was
19470        // missing is this second-token gate, and the CTE body's dispatch
19471        // below. Round 868 found both by putting the shorthand in a
19472        // subquery — the top-level forms had been the only ones tested.
19473        if matches!(self.peek(), Token::LParen)
19474            && (matches!(
19475                self.tokens.get(self.pos + 1),
19476                Some(Token::Select | Token::LParen | Token::Table)
19477            ) || matches!(self.tokens.get(self.pos + 1),
19478                    Some(Token::Ident(s) | Token::QuotedIdent(s)) if s.eq_ignore_ascii_case("with")))
19479        {
19480            self.advance(); // (
19481            let inner = match self.parse_one_statement()? {
19482                Statement::Select(s) => s,
19483                other => {
19484                    return Err(self.err(alloc::format!(
19485                        "expected SELECT inside derived table ( … ), got {other:?}"
19486                    )));
19487                }
19488            };
19489            if !matches!(self.peek(), Token::RParen) {
19490                return Err(self.err(alloc::format!(
19491                    "expected ')' after derived-table subquery, got {:?}",
19492                    self.peek()
19493                )));
19494            }
19495            self.advance();
19496            // `AS t(a, b)` column-alias list rides the
19497            // unnest_column_aliases field (same positional-rename
19498            // contract the unnest SRFs use).
19499            let (alias_ident, column_aliases) = self.parse_optional_alias_with_columns()?;
19500            let name = alias_ident
19501                .clone()
19502                .unwrap_or_else(|| "subquery".to_string());
19503            return Ok(TableRef {
19504                name,
19505                alias: alias_ident,
19506                only: false,
19507                as_of_segment: None,
19508                unnest_expr: None,
19509                unnest_column_aliases: column_aliases,
19510                with_ordinality: false,
19511                generate_series_args: None,
19512                lateral_subquery: Some(Box::new(inner)),
19513                jsonb_each_text_arg: None,
19514                table_fn_call: None,
19515                rows_from: None,
19516                json_table: None,
19517                scalar_fn_item: false,
19518            });
19519        }
19520        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("lateral"))
19521            && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
19522        {
19523            self.advance(); // LATERAL
19524            self.advance(); // (
19525            // Parse the inner SELECT.
19526            let inner = match self.parse_one_statement()? {
19527                Statement::Select(s) => s,
19528                other => {
19529                    return Err(self.err(alloc::format!(
19530                        "expected SELECT inside LATERAL ( … ), got {other:?}"
19531                    )));
19532                }
19533            };
19534            if !matches!(self.peek(), Token::RParen) {
19535                return Err(self.err(alloc::format!(
19536                    "expected ')' after LATERAL subquery, got {:?}",
19537                    self.peek()
19538                )));
19539            }
19540            self.advance();
19541            // v7.37 D.28 — `LATERAL (…) AS t(cols)` column-alias list (also how a
19542            // `(VALUES …) t(g)` derived table round-trips through view-body
19543            // Display, which renders on the lateral_subquery channel).
19544            let (alias_ident, column_aliases) = self.parse_optional_alias_with_columns()?;
19545            let name = alias_ident.clone().unwrap_or_else(|| "lateral".to_string());
19546            return Ok(TableRef {
19547                name,
19548                alias: alias_ident,
19549                only: false,
19550                as_of_segment: None,
19551                unnest_expr: None,
19552                unnest_column_aliases: column_aliases,
19553                with_ordinality: false,
19554                generate_series_args: None,
19555                lateral_subquery: Some(Box::new(inner)),
19556                jsonb_each_text_arg: None,
19557                table_fn_call: None,
19558                rows_from: None,
19559                json_table: None,
19560                scalar_fn_item: false,
19561            });
19562        }
19563        // v7.37.43-T4.5 — `jsonb_each_text(<expr>)` set-returning
19564        // function as a FROM item. Emits one row per (key, value)
19565        // pair in the JSONB object argument as TEXT columns. May
19566        // be wrapped in CROSS JOIN LATERAL when the argument
19567        // references a preceding FROM item (sentori migration
19568        // 0067 backfill shape: `CROSS JOIN LATERAL
19569        // jsonb_each_text(t.json_col) AS kv(key, value)`).
19570        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if is_json_each_name(s))
19571            && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
19572        {
19573            let each_fn = match self.peek() {
19574                Token::Ident(s) | Token::QuotedIdent(s) => s.to_ascii_lowercase(),
19575                _ => unreachable!(),
19576            };
19577            self.advance(); // jsonb_each[_text] / json_each[_text]
19578            self.advance(); // (
19579            let arg = self.parse_expr(0)?;
19580            if !matches!(self.peek(), Token::RParen) {
19581                return Err(self.err(alloc::format!(
19582                    "expected ')' after {each_fn}() argument, got {:?}",
19583                    self.peek()
19584                )));
19585            }
19586            self.advance();
19587            let (alias_ident, column_aliases) = self.parse_optional_alias_with_columns()?;
19588            let name = alias_ident.clone().unwrap_or_else(|| each_fn.clone());
19589            return Ok(TableRef {
19590                name,
19591                alias: alias_ident,
19592                only: false,
19593                as_of_segment: None,
19594                unnest_expr: None,
19595                // `AS t(k, v)` renames key/value positionally, same as the
19596                // LATERAL-position form already does.
19597                unnest_column_aliases: column_aliases,
19598                with_ordinality: false,
19599                generate_series_args: None,
19600                lateral_subquery: None,
19601                jsonb_each_text_arg: Some((each_fn, Box::new(arg))),
19602                table_fn_call: None,
19603                rows_from: None,
19604                json_table: None,
19605                scalar_fn_item: false,
19606            });
19607        }
19608        // `jsonb_to_recordset(J) AS t(a int, b text)` / `jsonb_to_record`
19609        // (+ json_ variants) — record-returning JSON functions with a
19610        // column-definition list. Desugar to a derived table that
19611        // projects each declared column from the JSON via `->>` + a cast,
19612        // over `jsonb_array_elements(J)` for the *set (per-element) form.
19613        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if is_json_to_record_name(s))
19614            && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
19615        {
19616            return self.parse_json_to_record_from();
19617        }
19618        // v7.38 (T15) — `regexp_matches(s, pat[, flags])` as a FROM item. Each
19619        // row is a text[] of capture groups, so it cannot desugar to unnest
19620        // (that would flatten the array). Wrap it as a derived table
19621        // `(SELECT regexp_matches(args)) AS <alias>(<col>)` — the SELECT-list
19622        // SRF path already emits one text[] row per match. PG names the column
19623        // `regexp_matches`; an `AS a(col)` alias overrides it.
19624        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
19625                if s.eq_ignore_ascii_case("regexp_matches"))
19626            && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
19627        {
19628            self.advance(); // fn name
19629            self.advance(); // (
19630            let mut fn_args: Vec<Expr> = Vec::new();
19631            loop {
19632                fn_args.push(self.parse_expr(0)?);
19633                if matches!(self.peek(), Token::Comma) {
19634                    self.advance();
19635                    continue;
19636                }
19637                break;
19638            }
19639            if !matches!(self.peek(), Token::RParen) {
19640                return Err(self.err(alloc::format!(
19641                    "expected ')' after regexp_matches() arguments, got {:?}",
19642                    self.peek()
19643                )));
19644            }
19645            self.advance();
19646            // v7.39 (read01 round 78) — WITH ORDINALITY sits BEFORE the alias
19647            // (`f(x) WITH ORDINALITY AS t(v, o)`), and this arm never looked for
19648            // it, so it died on the `with` token while every other table function
19649            // accepted it.
19650            let with_ordinality = self.absorb_with_ordinality();
19651            let (alias_ident, column_aliases) = self.parse_optional_alias_with_columns()?;
19652            let table_alias = alias_ident
19653                .clone()
19654                .unwrap_or_else(|| "regexp_matches".to_string());
19655            // PG names a single-column function's output column after the ALIAS
19656            // when one is given (`FROM regexp_matches(…) AS m` → column `m`), so
19657            // `m` reads as that column and not as a whole-row composite. Naming
19658            // it after the function regardless made `SELECT m[1] FROM … AS m`
19659            // subscript a record.
19660            let col_name = column_aliases
19661                .first()
19662                .cloned()
19663                .or_else(|| alias_ident.clone())
19664                .unwrap_or_else(|| "regexp_matches".to_string());
19665            let inner = crate::ast::SelectStatement {
19666                locking: None,
19667                ctes: Vec::new(),
19668                distinct: false,
19669                distinct_on: Vec::new(),
19670                items: alloc::vec![SelectItem::Expr {
19671                    expr: Expr::FunctionCall {
19672                        name: "regexp_matches".to_string(),
19673                        args: fn_args,
19674                    },
19675                    alias: Some(col_name),
19676                }],
19677                from: None,
19678                where_: None,
19679                group_by: None,
19680                group_by_all: false,
19681                having: None,
19682                unions: Vec::new(),
19683                order_by: Vec::new(),
19684                limit: None,
19685                offset: None,
19686                limit_with_ties: false,
19687                window_check_exprs: Vec::new(),
19688            };
19689            return Ok(TableRef {
19690                name: table_alias.clone(),
19691                alias: Some(table_alias),
19692                only: false,
19693                as_of_segment: None,
19694                unnest_expr: None,
19695                unnest_column_aliases: column_aliases,
19696                with_ordinality,
19697                generate_series_args: None,
19698                lateral_subquery: Some(Box::new(inner)),
19699                jsonb_each_text_arg: None,
19700                table_fn_call: None,
19701                rows_from: None,
19702                json_table: None,
19703                // regexp_matches returns text[], a base type: `SELECT m FROM
19704                // regexp_matches(…) AS m` is the array, not a composite wrapping it.
19705                scalar_fn_item: true,
19706            });
19707        }
19708        // v7.37.17 (17.6 siblings) — `jsonb_array_elements[_text](<expr>)`
19709        // / json_ variants as a FROM item. Rewritten into
19710        // `unnest(<same fn>(<expr>))`: the scalar form returns the
19711        // elements as a TEXT array, and the existing unnest SRF path
19712        // materialises one row per element. PG's natural column name
19713        // is `value`; an `AS a(col)` column-alias list overrides it.
19714        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
19715                if s.eq_ignore_ascii_case("jsonb_array_elements")
19716                    || s.eq_ignore_ascii_case("json_array_elements")
19717                    || s.eq_ignore_ascii_case("jsonb_array_elements_text")
19718                    || s.eq_ignore_ascii_case("json_array_elements_text")
19719                    || s.eq_ignore_ascii_case("jsonb_object_keys")
19720                    || s.eq_ignore_ascii_case("json_object_keys")
19721                    || s.eq_ignore_ascii_case("jsonb_path_query")
19722                    || s.eq_ignore_ascii_case("json_path_query")
19723                    || s.eq_ignore_ascii_case("generate_subscripts")
19724                    || s.eq_ignore_ascii_case("string_to_table")
19725                    || s.eq_ignore_ascii_case("regexp_split_to_table"))
19726            && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
19727        {
19728            let fn_name = match self.peek() {
19729                Token::Ident(s) | Token::QuotedIdent(s) => s.to_ascii_lowercase(),
19730                _ => unreachable!(),
19731            };
19732            self.advance(); // fn name
19733            self.advance(); // (
19734            let mut fn_args: Vec<Expr> = Vec::new();
19735            loop {
19736                fn_args.push(self.parse_expr(0)?);
19737                if matches!(self.peek(), Token::Comma) {
19738                    self.advance();
19739                    continue;
19740                }
19741                break;
19742            }
19743            if !matches!(self.peek(), Token::RParen) {
19744                return Err(self.err(alloc::format!(
19745                    "expected ')' after {fn_name}() arguments, got {:?}",
19746                    self.peek()
19747                )));
19748            }
19749            self.advance();
19750            let with_ordinality = self.absorb_with_ordinality();
19751            let (alias_ident, column_aliases) = self.parse_optional_alias_with_columns()?;
19752            let name = alias_ident.clone().unwrap_or_else(|| fn_name.clone());
19753            // PG's natural column name: the array-elements SRFs
19754            // declare an OUT parameter `value`; jsonb_object_keys
19755            // and generate_subscripts have none, so the column is
19756            // named after the function. A bare table alias on a
19757            // single-column SRF renames the column too (PG: `FROM
19758            // generate_subscripts(a, 1) AS s` projects column s) —
19759            // except for the OUT-parameter SRFs, whose column stays
19760            // `value` under a bare alias.
19761            let natural_col = if fn_name.ends_with("_array_elements")
19762                || fn_name.ends_with("_array_elements_text")
19763            {
19764                "value".to_string()
19765            } else {
19766                alias_ident.clone().unwrap_or_else(|| fn_name.clone())
19767            };
19768            let mut srf_cols = alloc::vec![column_aliases.first().cloned().unwrap_or(natural_col)];
19769            // Keep any further entries — the second names the
19770            // ordinality column under WITH ORDINALITY.
19771            srf_cols.extend(column_aliases.into_iter().skip(1));
19772            // The *_to_table SRFs are row-streams over the existing
19773            // *_to_array scalars — map the call target; the display
19774            // name (alias / column defaults) keeps the SRF spelling.
19775            let call_name = match fn_name.as_str() {
19776                "string_to_table" => "string_to_array".to_string(),
19777                "regexp_split_to_table" => "regexp_split_to_array".to_string(),
19778                _ => fn_name,
19779            };
19780            // v7.38 (read01, T-srf/T-lateral) — an SRF argument that references a
19781            // preceding FROM item (bare or qualified column) is correlated;
19782            // route it through the per-outer-row lateral channel.
19783            let expr = crate::ast::Expr::FunctionCall {
19784                name: call_name,
19785                args: fn_args,
19786            };
19787            let correlated = Self::expr_has_any_column(&expr);
19788            let tref = TableRef {
19789                name,
19790                alias: alias_ident,
19791                only: false,
19792                as_of_segment: None,
19793                unnest_expr: Some(Box::new(expr)),
19794                unnest_column_aliases: srf_cols,
19795                with_ordinality,
19796                generate_series_args: None,
19797                lateral_subquery: None,
19798                jsonb_each_text_arg: None,
19799                table_fn_call: None,
19800                rows_from: None,
19801                json_table: None,
19802                // Each of these returns a BASE type (jsonb / text / int), so the item's
19803                // row type is that scalar: `SELECT j FROM jsonb_array_elements('[1]') j`
19804                // is `1`, not `(1)`. WITH ORDINALITY makes it a real two-column item.
19805                scalar_fn_item: !with_ordinality,
19806            };
19807            return Ok(if correlated {
19808                Self::wrap_correlated_srf(tref)
19809            } else {
19810                tref
19811            });
19812        }
19813        // `ROWS FROM ( srf(args) [, srf(args)]* )` — SQL-standard
19814        // explicit parallel-zip syntax. Each entry lowers to its
19815        // array-returning scalar form (unnest(x) → x itself; the
19816        // FROM-SRF rewrite family → their scalar array calls) and
19817        // the list rides the multi-arg unnest zip channel:
19818        // NULL-padded to the longest, WITH ORDINALITY appends the
19819        // counter. generate_series has no scalar array form and
19820        // errors honestly.
19821        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("rows"))
19822            && matches!(self.tokens.get(self.pos + 1), Some(Token::From))
19823            && matches!(self.tokens.get(self.pos + 2), Some(Token::LParen))
19824        {
19825            self.advance(); // ROWS
19826            self.advance(); // FROM
19827            self.advance(); // (
19828            let mut entries: Vec<Expr> = Vec::new();
19829            // v7.39 (read01 round 74) — the generic channel, filled in parallel.
19830            // Used only when some entry has no array form.
19831            let mut generic: Vec<(String, Vec<Expr>)> = Vec::new();
19832            loop {
19833                let fn_name = self.expect_ident_like()?.to_ascii_lowercase();
19834                if !matches!(self.peek(), Token::LParen) {
19835                    return Err(self.err(alloc::format!(
19836                        "expected '(' after {fn_name} in ROWS FROM, got {:?}",
19837                        self.peek()
19838                    )));
19839                }
19840                self.advance();
19841                let mut fn_args: Vec<Expr> = Vec::new();
19842                if !matches!(self.peek(), Token::RParen) {
19843                    loop {
19844                        fn_args.push(self.parse_expr(0)?);
19845                        if matches!(self.peek(), Token::Comma) {
19846                            self.advance();
19847                            continue;
19848                        }
19849                        break;
19850                    }
19851                }
19852                if !matches!(self.peek(), Token::RParen) {
19853                    return Err(self.err(alloc::format!(
19854                        "expected ')' after {fn_name}() arguments in ROWS FROM, got {:?}",
19855                        self.peek()
19856                    )));
19857                }
19858                self.advance();
19859                let entry = match fn_name.as_str() {
19860                    "unnest" => {
19861                        if fn_args.len() != 1 {
19862                            return Err(
19863                                self.err("unnest inside ROWS FROM takes exactly one array".into())
19864                            );
19865                        }
19866                        fn_args.pop().expect("len checked")
19867                    }
19868                    "jsonb_array_elements"
19869                    | "json_array_elements"
19870                    | "jsonb_array_elements_text"
19871                    | "json_array_elements_text"
19872                    | "jsonb_object_keys"
19873                    | "json_object_keys"
19874                    | "generate_subscripts" => crate::ast::Expr::FunctionCall {
19875                        name: fn_name,
19876                        args: fn_args,
19877                    },
19878                    "string_to_table" => crate::ast::Expr::FunctionCall {
19879                        name: "string_to_array".to_string(),
19880                        args: fn_args,
19881                    },
19882                    "regexp_split_to_table" => crate::ast::Expr::FunctionCall {
19883                        name: "regexp_split_to_array".to_string(),
19884                        args: fn_args,
19885                    },
19886                    // v7.39 (read01 round 74) — an SRF with no array form
19887                    // (`generate_series`, a user `RETURNS SETOF` function) has no
19888                    // scalar expression to zip, so the WHOLE list switches to the
19889                    // rows_from channel, which runs each function and zips the
19890                    // rows themselves. The all-array case keeps the old lowering:
19891                    // it is well-trodden and this must not disturb it.
19892                    _ => {
19893                        generic.push((fn_name, fn_args));
19894                        if matches!(self.peek(), Token::Comma) {
19895                            self.advance();
19896                            continue;
19897                        }
19898                        break;
19899                    }
19900                };
19901                generic.push((
19902                    // The array-able entries carry their lowered expr along, so a
19903                    // MIXED list still works: the engine sees the scalar array
19904                    // form and unnests it.
19905                    "__array".to_string(),
19906                    alloc::vec![entry.clone()],
19907                ));
19908                entries.push(entry);
19909                if matches!(self.peek(), Token::Comma) {
19910                    self.advance();
19911                    continue;
19912                }
19913                break;
19914            }
19915            if !matches!(self.peek(), Token::RParen) {
19916                return Err(self.err(alloc::format!(
19917                    "expected ')' to close ROWS FROM, got {:?}",
19918                    self.peek()
19919                )));
19920            }
19921            self.advance();
19922            let with_ordinality = self.absorb_with_ordinality();
19923            let (alias_ident, unnest_column_aliases) = self.parse_optional_alias_with_columns()?;
19924            let name = alias_ident.clone().unwrap_or_else(|| "rows".to_string());
19925            // v7.39 (read01 round 74) — some entry had no array form, so the whole
19926            // list rides the generic channel.
19927            if generic.iter().any(|(n, _)| n != "__array") {
19928                let correlated = generic
19929                    .iter()
19930                    .any(|(_, a)| a.iter().any(Self::expr_has_any_column));
19931                let tref = TableRef {
19932                    name,
19933                    alias: alias_ident,
19934                    only: false,
19935                    as_of_segment: None,
19936                    unnest_expr: None,
19937                    unnest_column_aliases,
19938                    with_ordinality,
19939                    generate_series_args: None,
19940                    lateral_subquery: None,
19941                    jsonb_each_text_arg: None,
19942                    table_fn_call: None,
19943                    rows_from: Some(generic),
19944                    json_table: None,
19945                    scalar_fn_item: false,
19946                };
19947                return Ok(if correlated {
19948                    Self::wrap_correlated_srf(tref)
19949                } else {
19950                    tref
19951                });
19952            }
19953            let correlated = entries.iter().any(Self::expr_has_any_column);
19954            let expr = if entries.len() == 1 {
19955                entries.pop().expect("len checked")
19956            } else {
19957                crate::ast::Expr::FunctionCall {
19958                    name: "__unnest_zip".to_string(),
19959                    args: entries,
19960                }
19961            };
19962            let tref = TableRef {
19963                name,
19964                alias: alias_ident,
19965                only: false,
19966                as_of_segment: None,
19967                unnest_expr: Some(Box::new(expr)),
19968                unnest_column_aliases,
19969                with_ordinality,
19970                generate_series_args: None,
19971                lateral_subquery: None,
19972                jsonb_each_text_arg: None,
19973                table_fn_call: None,
19974                rows_from: None,
19975                json_table: None,
19976                scalar_fn_item: false,
19977            };
19978            return Ok(if correlated {
19979                Self::wrap_correlated_srf(tref)
19980            } else {
19981                tref
19982            });
19983        }
19984        // v7.11.7 — `FROM unnest(<expr>) [AS] <alias>` set-returning
19985        // source. Detect at the head before the bare-ident fallback;
19986        // unnest is not a reserved token.
19987        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("unnest"))
19988            && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
19989        {
19990            self.advance(); // unnest
19991            self.advance(); // (
19992            let mut srf_args = alloc::vec![self.parse_expr(0)?];
19993            while matches!(self.peek(), Token::Comma) {
19994                self.advance();
19995                srf_args.push(self.parse_expr(0)?);
19996            }
19997            if !matches!(self.peek(), Token::RParen) {
19998                return Err(self.err(alloc::format!(
19999                    "expected ')' after unnest() argument, got {:?}",
20000                    self.peek()
20001                )));
20002            }
20003            self.advance();
20004            // Multi-arg unnest(a, b, …) zips the arrays in
20005            // parallel, NULL-padding to the longest (PG's ROWS
20006            // FROM shorthand). Lower onto the unnest channel as an
20007            // internal marker call the executors unpack.
20008            let expr = if srf_args.len() == 1 {
20009                srf_args.pop().expect("len checked")
20010            } else {
20011                crate::ast::Expr::FunctionCall {
20012                    name: "__unnest_zip".to_string(),
20013                    args: srf_args,
20014                }
20015            };
20016            let with_ordinality = self.absorb_with_ordinality();
20017            let (alias_ident, unnest_column_aliases) = self.parse_optional_alias_with_columns()?;
20018            let name = alias_ident.clone().unwrap_or_else(|| "unnest".to_string());
20019            let correlated = Self::expr_has_any_column(&expr);
20020            let tref = TableRef {
20021                name,
20022                alias: alias_ident,
20023                only: false,
20024                as_of_segment: None,
20025                unnest_expr: Some(Box::new(expr)),
20026                unnest_column_aliases,
20027                with_ordinality,
20028                generate_series_args: None,
20029                lateral_subquery: None,
20030                jsonb_each_text_arg: None,
20031                table_fn_call: None,
20032                rows_from: None,
20033                json_table: None,
20034                scalar_fn_item: false,
20035            };
20036            return Ok(if correlated {
20037                Self::wrap_correlated_srf(tref)
20038            } else {
20039                tref
20040            });
20041        }
20042        // v7.39 (round 205, JSON_TABLE epic) — `JSON_TABLE(doc, '$path'
20043        // COLUMNS (...))` has bespoke syntax (a COLUMNS clause the
20044        // generic table-fn arg parser can't read), so it is intercepted
20045        // here BEFORE the generic dispatch. The doc expr may reference
20046        // outer columns (implicit LATERAL) — same correlated-wrap rule.
20047        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
20048                if s.eq_ignore_ascii_case("json_table"))
20049            && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
20050        {
20051            let tref = self.parse_json_table_ref()?;
20052            let correlated = tref
20053                .json_table
20054                .as_deref()
20055                .is_some_and(|jt| Self::expr_has_any_column(&jt.doc));
20056            return Ok(if correlated {
20057                Self::wrap_correlated_srf(tref)
20058            } else {
20059                tref
20060            });
20061        }
20062        // v7.39 (read01 partitionfuncs.c) — generic FROM-position table
20063        // functions dispatched by name (`pg_partition_tree('t')`,
20064        // `pg_partition_ancestors('t')`). Same head-detection shape as
20065        // unnest; the engine executor owns the row shape per function.
20066        // v7.39 (read01 round 65) — and a USER function in FROM position
20067        // (`FROM rows_of(2)`). The SRFs with their own FROM pipeline
20068        // (generate_series / unnest / the json_each family) keep it — their arms
20069        // sit further down, so they are excluded here by name rather than by
20070        // ordering. Anything else that is an ident followed by `(` is a table
20071        // function; the engine executor decides whether it is a builtin, a
20072        // set-returning user function, or an error.
20073        // 7.38.1 S5.1 — pg_dump spells its table functions
20074        // schema-qualified (`pg_catalog.pg_options_to_table(...)`);
20075        // strip the pg_catalog prefix here so the same head-detection
20076        // fires. Only pg_catalog: a user schema's `s.f(x)` keeps its
20077        // meaning.
20078        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("pg_catalog"))
20079            && matches!(self.tokens.get(self.pos + 1), Some(Token::Dot))
20080            && matches!(
20081                self.tokens.get(self.pos + 2),
20082                Some(Token::Ident(_) | Token::QuotedIdent(_))
20083            )
20084            && matches!(self.tokens.get(self.pos + 3), Some(Token::LParen))
20085        {
20086            self.advance(); // pg_catalog
20087            self.advance(); // .
20088        }
20089        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
20090                if !s.eq_ignore_ascii_case("generate_series")
20091                    && !s.eq_ignore_ascii_case("unnest")
20092                    && !is_json_each_name(s))
20093            && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
20094        {
20095            // Body out-of-line — this parse sits on the FROM/subquery
20096            // recursion chain (debug frame-cliff discipline).
20097            // v7.39 (read01 round 69) — a call whose arguments reference an outer
20098            // column (`t JOIN LATERAL dbl(t.id)`) is CORRELATED: it runs once per
20099            // outer row, so it rides the lateral channel. Same rule the unnest
20100            // arm uses.
20101            let tref = self.parse_table_fn_ref()?;
20102            let correlated = tref
20103                .table_fn_call
20104                .as_deref()
20105                .is_some_and(|(_, args)| args.iter().any(Self::expr_has_any_column));
20106            return Ok(if correlated {
20107                Self::wrap_correlated_srf(tref)
20108            } else {
20109                tref
20110            });
20111        }
20112        // v7.17.0 Phase 3.10 — `FROM generate_series(start, stop
20113        // [, step])` set-returning source. Same shape as unnest:
20114        // detect at the head, parse the comma-separated arg list,
20115        // dispatch downstream through the engine's set-returning
20116        // path. Supports integer triplets (mailrs's `WITH row_no AS
20117        // (SELECT * FROM generate_series(1, N))` pattern) and
20118        // TIMESTAMP + INTERVAL triplets (the Tier-A audit's
20119        // date-range iteration pattern, which pre-3.10 had no
20120        // direct equivalent in SPG).
20121        if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("generate_series"))
20122            && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
20123        {
20124            self.advance(); // generate_series
20125            self.advance(); // (
20126            let mut args: Vec<Expr> = Vec::new();
20127            loop {
20128                args.push(self.parse_expr(0)?);
20129                if matches!(self.peek(), Token::Comma) {
20130                    self.advance();
20131                    continue;
20132                }
20133                break;
20134            }
20135            if !matches!(self.peek(), Token::RParen) {
20136                return Err(self.err(alloc::format!(
20137                    "expected ')' after generate_series() arguments, got {:?}",
20138                    self.peek()
20139                )));
20140            }
20141            self.advance();
20142            if args.len() < 2 || args.len() > 3 {
20143                return Err(self.err(alloc::format!(
20144                    "generate_series() expects 2 or 3 arguments (start, stop [, step]); got {}",
20145                    args.len()
20146                )));
20147            }
20148            let with_ordinality = self.absorb_with_ordinality();
20149            let (alias_ident, column_aliases) = self.parse_optional_alias_with_columns()?;
20150            let name = alias_ident
20151                .clone()
20152                .unwrap_or_else(|| "generate_series".to_string());
20153            let correlated = args.iter().any(Self::expr_has_any_column);
20154            let tref = TableRef {
20155                name,
20156                alias: alias_ident,
20157                only: false,
20158                as_of_segment: None,
20159                unnest_expr: None,
20160                unnest_column_aliases: column_aliases,
20161                with_ordinality,
20162                generate_series_args: Some(args),
20163                lateral_subquery: None,
20164                jsonb_each_text_arg: None,
20165                table_fn_call: None,
20166                rows_from: None,
20167                json_table: None,
20168                scalar_fn_item: false,
20169            };
20170            return Ok(if correlated {
20171                Self::wrap_correlated_srf(tref)
20172            } else {
20173                tref
20174            });
20175        }
20176        // v7.16.2 — preserve information_schema / pg_catalog
20177        // qualifiers (mailrs round-10 A.3). The generic
20178        // `expect_ident_like` strip silently drops the schema;
20179        // we want the engine to recognise these PG meta tables
20180        // and synthesise rows from the live catalog. Produce a
20181        // synthetic name (`__spg_info_columns` etc.) so the
20182        // engine's SELECT-side router can dispatch without
20183        // clashing with any user-defined `columns` table.
20184        let (name, meta_original) = if let Some((synth, orig)) = self.try_peek_meta_qualified() {
20185            (synth, Some(orig))
20186        } else if let Some((synth, orig)) = self.try_peek_meta_bare() {
20187            (synth, Some(orig))
20188        } else {
20189            (self.expect_ident_like()?, None)
20190        };
20191        // v6.10.2 — optional `AS OF SEGMENT '<id>'` cold-tier
20192        // time-travel clause. Parse BEFORE the alias so the
20193        // alias can still ride at the tail (`tbl AS OF SEGMENT
20194        // '5' alias`). `AS` is a reserved keyword token, while
20195        // `OF` and `SEGMENT` are bare idents.
20196        let as_of_segment = if matches!(self.peek(), Token::As)
20197            && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(s) | Token::QuotedIdent(s)) if s.eq_ignore_ascii_case("of"))
20198        {
20199            self.advance(); // AS
20200            self.advance(); // OF
20201            let kw = match self.peek().clone() {
20202                Token::Ident(s) | Token::QuotedIdent(s) => s,
20203                other => {
20204                    return Err(self.err(format!("expected SEGMENT after AS OF, got {other:?}")));
20205                }
20206            };
20207            if !kw.eq_ignore_ascii_case("segment") {
20208                return Err(self.err(format!(
20209                    "expected SEGMENT after AS OF, got {kw:?}; v6.10.2 supports SEGMENT only"
20210                )));
20211            }
20212            self.advance();
20213            // Segment id literal — accept either a string or
20214            // integer for operator ergonomics.
20215            let id = match self.advance() {
20216                Token::String(s) => s
20217                    .parse::<u32>()
20218                    .map_err(|e| self.err(format!("AS OF SEGMENT id parse: {e}")))?,
20219                Token::Integer(n) => u32::try_from(n)
20220                    .map_err(|e| self.err(format!("AS OF SEGMENT id parse: {e}")))?,
20221                other => {
20222                    return Err(self.err(format!(
20223                        "expected segment id literal after AS OF SEGMENT, got {other:?}"
20224                    )));
20225                }
20226            };
20227            Some(id)
20228        } else {
20229            None
20230        };
20231        // TABLESAMPLE is not a reserved token — keep the bare-ident
20232        // alias rule from swallowing it (`FROM t TABLESAMPLE …`).
20233        let alias = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("tablesample"))
20234        {
20235            None
20236        } else {
20237            self.parse_optional_alias()?
20238        };
20239        // r1052 — a catalog name rewritten to its synthetic form keeps
20240        // the WRITTEN name as the relation's alias, so `pg_cast.oid`
20241        // still binds after `pg_cast` became `__spg_pg_cast`. PG
20242        // semantics: the visible name of `pg_catalog.pg_cast` IS
20243        // `pg_cast`. Without this, every table-name-qualified column
20244        // on a synthesised catalog answered "missing FROM-clause
20245        // entry" — which is the wall pg_dump hit on its first
20246        // pg_proc/pg_cast query.
20247        let alias = match (&alias, &meta_original) {
20248            (None, Some(orig)) if *orig != name => Some(orig.clone()),
20249            _ => alias,
20250        };
20251        // `TABLESAMPLE BERNOULLI(p) | SYSTEM(p)` follows the alias
20252        // (PG grammar). BERNOULLI lowers to a per-row
20253        // `random() < p/100` conjunct on the enclosing SELECT's
20254        // WHERE — exact row-level Bernoulli semantics. SYSTEM
20255        // shares the lowering: SPG has no page structure to
20256        // sample, and the row-level form returns the same expected
20257        // fraction. REPEATABLE(seed) promises a deterministic
20258        // sample SPG cannot honour yet — honest error rather than
20259        // a silently ignored seed.
20260        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("tablesample")) {
20261            self.advance();
20262            let method = self.expect_ident_like()?;
20263            if !method.eq_ignore_ascii_case("bernoulli") && !method.eq_ignore_ascii_case("system") {
20264                return Err(self.err(alloc::format!(
20265                    "TABLESAMPLE method {method:?} not supported; use BERNOULLI or SYSTEM"
20266                )));
20267            }
20268            if !matches!(self.peek(), Token::LParen) {
20269                return Err(self.err(alloc::format!(
20270                    "expected '(' after TABLESAMPLE {}, got {:?}",
20271                    method.to_ascii_uppercase(),
20272                    self.peek()
20273                )));
20274            }
20275            self.advance();
20276            let percent = self.parse_expr(0)?;
20277            if !matches!(self.peek(), Token::RParen) {
20278                return Err(self.err(alloc::format!(
20279                    "expected ')' after TABLESAMPLE percentage, got {:?}",
20280                    self.peek()
20281                )));
20282            }
20283            self.advance();
20284            // REPEATABLE(seed) → a deterministic per-row draw seeded by
20285            // `seed`, so the sample is stable across repeats and rescans.
20286            // Non-REPEATABLE keeps the non-deterministic `random()` draw.
20287            let mut sample_seed: Option<Expr> = None;
20288            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("repeatable")) {
20289                self.advance();
20290                if !matches!(self.peek(), Token::LParen) {
20291                    return Err(self.err(alloc::format!(
20292                        "expected '(' after REPEATABLE, got {:?}",
20293                        self.peek()
20294                    )));
20295                }
20296                self.advance();
20297                let seed = self.parse_expr(0)?;
20298                if !matches!(self.peek(), Token::RParen) {
20299                    return Err(self.err(alloc::format!(
20300                        "expected ')' after REPEATABLE seed, got {:?}",
20301                        self.peek()
20302                    )));
20303                }
20304                self.advance();
20305                sample_seed = Some(seed);
20306            }
20307            let draw = match sample_seed {
20308                Some(seed) => Expr::FunctionCall {
20309                    name: "__tsm_fract".to_string(),
20310                    args: alloc::vec![seed],
20311                },
20312                None => Expr::FunctionCall {
20313                    name: "random".to_string(),
20314                    args: Vec::new(),
20315                },
20316            };
20317            self.pending_sample_preds.push(Expr::Binary {
20318                lhs: Box::new(draw),
20319                op: crate::ast::BinOp::Lt,
20320                rhs: Box::new(Expr::Binary {
20321                    lhs: Box::new(percent),
20322                    op: crate::ast::BinOp::Div,
20323                    rhs: Box::new(Expr::Literal(crate::ast::Literal::Float(100.0))),
20324                }),
20325            });
20326        }
20327        Ok(TableRef {
20328            name,
20329            alias,
20330            only,
20331            as_of_segment,
20332            unnest_expr: None,
20333            unnest_column_aliases: Vec::new(),
20334            with_ordinality: false,
20335            generate_series_args: None,
20336            lateral_subquery: None,
20337            jsonb_each_text_arg: None,
20338            table_fn_call: None,
20339            rows_from: None,
20340            json_table: None,
20341            scalar_fn_item: false,
20342        })
20343    }
20344
20345    /// v7.13.2 — mailrs round-6 S5. Like `parse_optional_alias`
20346    /// but also accepts `AS alias(col [, col, …])` — the
20347    /// PG-standard table-function column-list form. The column
20348    /// list is only honoured when paired with `UNNEST(...)` in
20349    /// the parent; other call sites currently discard it.
20350    /// True when the expression tree contains a qualified column
20351    /// reference (`t.col`) — the syntactic marker that an SRF
20352    /// argument correlates with a preceding FROM item.
20353    fn expr_has_qualified_column(e: &Expr) -> bool {
20354        match e {
20355            Expr::Column(c) => c.qualifier.is_some(),
20356            Expr::Binary { lhs, rhs, .. } => {
20357                Self::expr_has_qualified_column(lhs) || Self::expr_has_qualified_column(rhs)
20358            }
20359            Expr::Unary { expr, .. } => Self::expr_has_qualified_column(expr),
20360            Expr::Cast { expr, .. } => Self::expr_has_qualified_column(expr),
20361            Expr::FunctionCall { args, .. } => args.iter().any(Self::expr_has_qualified_column),
20362            Expr::Case {
20363                operand,
20364                branches,
20365                else_branch,
20366            } => {
20367                operand
20368                    .as_deref()
20369                    .is_some_and(Self::expr_has_qualified_column)
20370                    || branches.iter().any(|(w, t)| {
20371                        Self::expr_has_qualified_column(w) || Self::expr_has_qualified_column(t)
20372                    })
20373                    || else_branch
20374                        .as_deref()
20375                        .is_some_and(Self::expr_has_qualified_column)
20376            }
20377            _ => false,
20378        }
20379    }
20380
20381    /// v7.38 (read01, T-lateral) — like `expr_has_qualified_column` but also
20382    /// counts a bare (unqualified) column. A set-returning function has no
20383    /// input columns of its own, so ANY column in its arguments is an outer
20384    /// (correlated) reference — `generate_series(1, n)` correlates on `n`.
20385    fn expr_has_any_column(e: &Expr) -> bool {
20386        match e {
20387            Expr::Column(_) => true,
20388            Expr::Binary { lhs, rhs, .. } => {
20389                Self::expr_has_any_column(lhs) || Self::expr_has_any_column(rhs)
20390            }
20391            Expr::Unary { expr, .. } => Self::expr_has_any_column(expr),
20392            Expr::Cast { expr, .. } => Self::expr_has_any_column(expr),
20393            Expr::FunctionCall { args, .. } => args.iter().any(Self::expr_has_any_column),
20394            // v7.39 (round 759, F31-B8b) — a column INSIDE an array
20395            // constructor or subscript fell to the `_ => false` arm, so
20396            // `unnest(ARRAY[x, x + 1])` never wrapped into the lateral
20397            // channel and the eager peer eval answered `column "x" does
20398            // not exist` (the substitution walker already recurses both
20399            // shapes; only this detector was blind to them).
20400            Expr::Array(items) => items.iter().any(Self::expr_has_any_column),
20401            Expr::ArraySubscript { target, index } => {
20402                Self::expr_has_any_column(target) || Self::expr_has_any_column(index)
20403            }
20404            Expr::Case {
20405                operand,
20406                branches,
20407                else_branch,
20408            } => {
20409                operand.as_deref().is_some_and(Self::expr_has_any_column)
20410                    || branches
20411                        .iter()
20412                        .any(|(w, t)| Self::expr_has_any_column(w) || Self::expr_has_any_column(t))
20413                    || else_branch
20414                        .as_deref()
20415                        .is_some_and(Self::expr_has_any_column)
20416            }
20417            _ => false,
20418        }
20419    }
20420
20421    /// Wrap a correlated SRF table ref (`unnest(t.col)` /
20422    /// `generate_series(1, t.n)`) into the lateral_subquery
20423    /// channel: `SELECT * FROM <srf>` executes per outer row with
20424    /// outer references substituted (v7.37.43-T4.5 machinery).
20425    /// Uncorrelated SRFs stay on their plain channels.
20426    fn wrap_correlated_srf(srf: TableRef) -> TableRef {
20427        let name = srf.name.clone();
20428        let alias = srf.alias.clone();
20429        let inner = crate::ast::SelectStatement {
20430            locking: None,
20431            ctes: Vec::new(),
20432            distinct: false,
20433            distinct_on: Vec::new(),
20434            items: alloc::vec![crate::ast::SelectItem::Wildcard],
20435            from: Some(crate::ast::FromClause {
20436                primary: srf,
20437                joins: Vec::new(),
20438            }),
20439            where_: None,
20440            group_by: None,
20441            group_by_all: false,
20442            having: None,
20443            unions: Vec::new(),
20444            order_by: Vec::new(),
20445            limit: None,
20446            offset: None,
20447            limit_with_ties: false,
20448            window_check_exprs: Vec::new(),
20449        };
20450        TableRef {
20451            name,
20452            alias,
20453            only: false,
20454            as_of_segment: None,
20455            unnest_expr: None,
20456            unnest_column_aliases: Vec::new(),
20457            with_ordinality: false,
20458            generate_series_args: None,
20459            lateral_subquery: Some(Box::new(inner)),
20460            jsonb_each_text_arg: None,
20461            table_fn_call: None,
20462            rows_from: None,
20463            json_table: None,
20464            scalar_fn_item: false,
20465        }
20466    }
20467
20468    /// True when the expression tree contains an unresolved
20469    /// `OVER w` marker (see parse_over_clause).
20470    fn expr_has_named_window(e: &Expr) -> bool {
20471        match e {
20472            Expr::WindowFunction { partition_by, .. } => matches!(
20473                partition_by.as_slice(),
20474                [Expr::Column(c)] if matches!(
20475                    c.qualifier.as_deref(),
20476                    Some("__named_window__") | Some("__named_window_ref__")
20477                )
20478            ),
20479            Expr::Binary { lhs, rhs, .. } => {
20480                Self::expr_has_named_window(lhs) || Self::expr_has_named_window(rhs)
20481            }
20482            Expr::Unary { expr, .. } | Expr::Cast { expr, .. } => Self::expr_has_named_window(expr),
20483            Expr::FunctionCall { args, .. } => args.iter().any(Self::expr_has_named_window),
20484            Expr::Case {
20485                operand,
20486                branches,
20487                else_branch,
20488            } => {
20489                operand.as_deref().is_some_and(Self::expr_has_named_window)
20490                    || branches.iter().any(|(w, t)| {
20491                        Self::expr_has_named_window(w) || Self::expr_has_named_window(t)
20492                    })
20493                    || else_branch
20494                        .as_deref()
20495                        .is_some_and(Self::expr_has_named_window)
20496            }
20497            _ => false,
20498        }
20499    }
20500
20501    /// v7.39 (round 705) — the NAMES the expression references through the
20502    /// `OVER w` markers, so `parse_bare_select` can tell which WINDOW
20503    /// definitions nothing referenced. Traversal mirrors
20504    /// `expr_has_named_window` above.
20505    fn collect_named_window_refs(e: &Expr, into: &mut Vec<String>) {
20506        match e {
20507            Expr::WindowFunction { partition_by, .. } => {
20508                if let [Expr::Column(c)] = partition_by.as_slice()
20509                    && matches!(
20510                        c.qualifier.as_deref(),
20511                        Some("__named_window__") | Some("__named_window_ref__")
20512                    )
20513                {
20514                    into.push(c.name.clone());
20515                }
20516            }
20517            Expr::Binary { lhs, rhs, .. } => {
20518                Self::collect_named_window_refs(lhs, into);
20519                Self::collect_named_window_refs(rhs, into);
20520            }
20521            Expr::Unary { expr, .. } | Expr::Cast { expr, .. } => {
20522                Self::collect_named_window_refs(expr, into);
20523            }
20524            Expr::FunctionCall { args, .. } => {
20525                for a in args {
20526                    Self::collect_named_window_refs(a, into);
20527                }
20528            }
20529            Expr::Case {
20530                operand,
20531                branches,
20532                else_branch,
20533            } => {
20534                if let Some(o) = operand.as_deref() {
20535                    Self::collect_named_window_refs(o, into);
20536                }
20537                for (w, t) in branches {
20538                    Self::collect_named_window_refs(w, into);
20539                    Self::collect_named_window_refs(t, into);
20540                }
20541                if let Some(eb) = else_branch.as_deref() {
20542                    Self::collect_named_window_refs(eb, into);
20543                }
20544            }
20545            _ => {}
20546        }
20547    }
20548
20549    /// Inline named-window definitions into the `OVER w` markers.
20550    /// An unknown name errors (PG: window "w" does not exist).
20551    #[allow(clippy::type_complexity)]
20552    fn substitute_named_windows(
20553        e: &mut Expr,
20554        defs: &[(
20555            String,
20556            (
20557                Vec<Expr>,
20558                Vec<(Expr, bool, Option<bool>)>,
20559                Option<WindowFrame>,
20560            ),
20561        )],
20562    ) -> Result<(), String> {
20563        match e {
20564            Expr::WindowFunction {
20565                partition_by,
20566                order_by,
20567                frame,
20568                ..
20569            } => {
20570                // `is_copy` distinguishes `OVER (w1 …)` (a refinable copy)
20571                // from the bare `OVER w1` (a plain reference).
20572                let named = match partition_by.as_slice() {
20573                    [Expr::Column(c)] => match c.qualifier.as_deref() {
20574                        Some("__named_window__") => Some((c.name.clone(), false)),
20575                        Some("__named_window_ref__") => Some((c.name.clone(), true)),
20576                        _ => None,
20577                    },
20578                    _ => None,
20579                };
20580                if let Some((wname, is_copy)) = named {
20581                    let Some((_, def)) = defs.iter().find(|(n, _)| n.eq_ignore_ascii_case(&wname))
20582                    else {
20583                        return Err(alloc::format!("window {wname:?} does not exist"));
20584                    };
20585                    if !is_copy {
20586                        *partition_by = def.0.clone();
20587                        *order_by = def.1.clone();
20588                        *frame = def.2.clone();
20589                        return Ok(());
20590                    }
20591                    // v7.39 (round 229) — PG's copy rules, probed against
20592                    // 18.4: a copy inherits the partitioning, may supply an
20593                    // ordering only when the base has none, and may not copy
20594                    // a base that already carries a frame (its own frame
20595                    // would be ambiguous with the inherited one).
20596                    if !def.1.is_empty() && !order_by.is_empty() {
20597                        return Err(alloc::format!(
20598                            "cannot override ORDER BY clause of window \"{wname}\""
20599                        ));
20600                    }
20601                    if def.2.is_some() {
20602                        return Err(alloc::format!(
20603                            "cannot copy window \"{wname}\" because it has a frame clause"
20604                        ));
20605                    }
20606                    *partition_by = def.0.clone();
20607                    if order_by.is_empty() {
20608                        *order_by = def.1.clone();
20609                    }
20610                }
20611                Ok(())
20612            }
20613            Expr::Binary { lhs, rhs, .. } => {
20614                Self::substitute_named_windows(lhs, defs)?;
20615                Self::substitute_named_windows(rhs, defs)
20616            }
20617            Expr::Unary { expr, .. } | Expr::Cast { expr, .. } => {
20618                Self::substitute_named_windows(expr, defs)
20619            }
20620            Expr::FunctionCall { args, .. } => {
20621                for a in args {
20622                    Self::substitute_named_windows(a, defs)?;
20623                }
20624                Ok(())
20625            }
20626            Expr::Case {
20627                operand,
20628                branches,
20629                else_branch,
20630            } => {
20631                if let Some(op) = operand {
20632                    Self::substitute_named_windows(op, defs)?;
20633                }
20634                for (w, t) in branches {
20635                    Self::substitute_named_windows(w, defs)?;
20636                    Self::substitute_named_windows(t, defs)?;
20637                }
20638                if let Some(el) = else_branch {
20639                    Self::substitute_named_windows(el, defs)?;
20640                }
20641                Ok(())
20642            }
20643            _ => Ok(()),
20644        }
20645    }
20646
20647    /// SQL-standard `TABLE name` shorthand — builds the equivalent
20648    /// `SELECT * FROM name` head. Callers own set-op chain / tail
20649    /// composition.
20650    fn parse_table_shorthand(&mut self) -> Result<SelectStatement, ParseError> {
20651        debug_assert!(matches!(self.peek(), Token::Table));
20652        self.advance(); // TABLE
20653        let tname = self.expect_ident_like()?;
20654        Ok(SelectStatement {
20655            locking: None,
20656            ctes: Vec::new(),
20657            distinct: false,
20658            distinct_on: Vec::new(),
20659            items: alloc::vec![SelectItem::Wildcard],
20660            from: Some(FromClause {
20661                primary: TableRef {
20662                    name: tname,
20663                    alias: None,
20664                    only: false,
20665                    as_of_segment: None,
20666                    unnest_expr: None,
20667                    unnest_column_aliases: Vec::new(),
20668                    with_ordinality: false,
20669                    generate_series_args: None,
20670                    lateral_subquery: None,
20671                    jsonb_each_text_arg: None,
20672                    table_fn_call: None,
20673                    rows_from: None,
20674                    json_table: None,
20675                    scalar_fn_item: false,
20676                },
20677                joins: Vec::new(),
20678            }),
20679            where_: None,
20680            group_by: None,
20681            group_by_all: false,
20682            having: None,
20683            unions: Vec::new(),
20684            order_by: Vec::new(),
20685            limit: None,
20686            offset: None,
20687            limit_with_ties: false,
20688            window_check_exprs: Vec::new(),
20689        })
20690    }
20691
20692    /// `jsonb_to_recordset(J) AS t(c1 t1, c2 t2, …)` (and record / json_
20693    /// variants) → a derived table that reads each declared column out of
20694    /// the JSON with `(row ->> 'ci')::ti`. The *set form iterates
20695    /// `jsonb_array_elements(J)` (one row per element, column `value`);
20696    /// the scalar *record form projects a single row straight off `J`.
20697    /// Rides the existing lateral-subquery channel, so no new executor or
20698    /// AST is needed.
20699    fn parse_json_to_record_from(&mut self) -> Result<TableRef, ParseError> {
20700        use crate::ast::{
20701            BinOp, ColumnName, Expr, FromClause, Literal, SelectItem, SelectStatement,
20702        };
20703        let fn_name = match self.peek() {
20704            Token::Ident(s) | Token::QuotedIdent(s) => s.to_ascii_lowercase(),
20705            _ => unreachable!("caller guarded is_json_to_record_name"),
20706        };
20707        self.advance(); // fn name
20708        self.advance(); // (
20709        let mut arg = self.parse_expr(0)?;
20710        // populate_record(base, json): the base only carries the record
20711        // type here — the JSON argument is the second expression.
20712        let mut base: Option<Expr> = None;
20713        if matches!(self.peek(), Token::Comma) {
20714            self.advance();
20715            base = Some(arg);
20716            arg = self.parse_expr(0)?;
20717        }
20718        if !matches!(self.peek(), Token::RParen) {
20719            return Err(self.err(alloc::format!(
20720                "expected ')' after {fn_name}() argument, got {:?}",
20721                self.peek()
20722            )));
20723        }
20724        self.advance(); // )
20725        let is_set = fn_name.ends_with("recordset");
20726        // `[AS] alias ( col type [, …] )` column-definition list.
20727        if matches!(self.peek(), Token::As) {
20728            self.advance();
20729        }
20730        let alias_opt = match self.peek() {
20731            Token::Ident(s) | Token::QuotedIdent(s) => {
20732                let a = s.clone();
20733                self.advance();
20734                Some(a)
20735            }
20736            _ => None,
20737        };
20738        // v7.39 (read01 round 76) — the populate family's canonical PG
20739        // spelling carries no column list at all: the row shape comes from
20740        // the BASE argument's declared type (`jsonb_populate_record(NULL::t,
20741        // j)`). The parser has no catalog, so hand the two arguments to the
20742        // engine's table-function channel, which does. Only `*_to_record*`
20743        // (whose base is bare `record`) genuinely requires the list.
20744        if !matches!(self.peek(), Token::LParen) {
20745            if let Some(base_expr) = base {
20746                let alias = alias_opt.unwrap_or_else(|| fn_name.clone());
20747                return Ok(TableRef {
20748                    name: alias.clone(),
20749                    alias: Some(alias),
20750                    only: false,
20751                    as_of_segment: None,
20752                    unnest_expr: None,
20753                    unnest_column_aliases: Vec::new(),
20754                    with_ordinality: false,
20755                    generate_series_args: None,
20756                    lateral_subquery: None,
20757                    jsonb_each_text_arg: None,
20758                    table_fn_call: Some(Box::new((fn_name, alloc::vec![base_expr, arg]))),
20759                    rows_from: None,
20760                    json_table: None,
20761                    scalar_fn_item: false,
20762                });
20763            }
20764            return Err(self.err(alloc::format!(
20765                "expected '(' to start the {fn_name} column-definition list, got {:?}",
20766                self.peek()
20767            )));
20768        }
20769        let Some(alias) = alias_opt else {
20770            return Err(self.err(alloc::format!(
20771                "{fn_name}(...) needs a column-definition list, e.g. AS t(a int, b text)"
20772            )));
20773        };
20774        self.advance(); // (
20775        let mut coldefs: Vec<(String, crate::ast::CastTarget)> = Vec::new();
20776        loop {
20777            let col = self.expect_ident_like()?;
20778            let ty = self.parse_cast_target()?;
20779            coldefs.push((col, ty));
20780            if matches!(self.peek(), Token::Comma) {
20781                self.advance();
20782                continue;
20783            }
20784            if matches!(self.peek(), Token::RParen) {
20785                self.advance();
20786                break;
20787            }
20788            return Err(self.err(alloc::format!(
20789                "expected ',' or ')' in {fn_name} column list, got {:?}",
20790                self.peek()
20791            )));
20792        }
20793        if coldefs.is_empty() {
20794            return Err(self.err(alloc::format!(
20795                "{fn_name} column-definition list must declare at least one column"
20796            )));
20797        }
20798        // Per column: (base ->> 'col')::type AS col. The base is the
20799        // per-element `value` column for the *set form, or the argument
20800        // itself for the scalar record form.
20801        let items: Vec<SelectItem> = coldefs
20802            .into_iter()
20803            .map(|(col, ty)| {
20804                let base = if is_set {
20805                    Expr::Column(ColumnName {
20806                        qualifier: None,
20807                        name: "value".to_string(),
20808                    })
20809                } else {
20810                    arg.clone()
20811                };
20812                SelectItem::Expr {
20813                    expr: Expr::Cast {
20814                        expr: Box::new(Expr::Binary {
20815                            lhs: Box::new(base),
20816                            op: BinOp::JsonGetText,
20817                            rhs: Box::new(Expr::Literal(Literal::String(col.clone()))),
20818                        }),
20819                        target: ty,
20820                    },
20821                    alias: Some(col),
20822                }
20823            })
20824            .collect();
20825        let from = if is_set {
20826            let elem_fn = if fn_name.starts_with("jsonb") {
20827                "jsonb_array_elements"
20828            } else {
20829                "json_array_elements"
20830            };
20831            Some(FromClause {
20832                primary: TableRef {
20833                    name: "value".to_string(),
20834                    alias: None,
20835                    only: false,
20836                    as_of_segment: None,
20837                    unnest_expr: Some(Box::new(Expr::FunctionCall {
20838                        name: elem_fn.to_string(),
20839                        args: alloc::vec![arg],
20840                    })),
20841                    unnest_column_aliases: alloc::vec!["value".to_string()],
20842                    with_ordinality: false,
20843                    generate_series_args: None,
20844                    lateral_subquery: None,
20845                    jsonb_each_text_arg: None,
20846                    table_fn_call: None,
20847                    rows_from: None,
20848                    json_table: None,
20849                    scalar_fn_item: false,
20850                },
20851                joins: Vec::new(),
20852            })
20853        } else {
20854            None
20855        };
20856        let inner = SelectStatement {
20857            locking: None,
20858            ctes: Vec::new(),
20859            distinct: false,
20860            distinct_on: Vec::new(),
20861            items,
20862            from,
20863            where_: None,
20864            group_by: None,
20865            group_by_all: false,
20866            having: None,
20867            unions: Vec::new(),
20868            order_by: Vec::new(),
20869            limit: None,
20870            offset: None,
20871            limit_with_ties: false,
20872            window_check_exprs: Vec::new(),
20873        };
20874        Ok(TableRef {
20875            name: alias.clone(),
20876            alias: Some(alias),
20877            only: false,
20878            as_of_segment: None,
20879            unnest_expr: None,
20880            unnest_column_aliases: Vec::new(),
20881            with_ordinality: false,
20882            generate_series_args: None,
20883            lateral_subquery: Some(Box::new(inner)),
20884            jsonb_each_text_arg: None,
20885            table_fn_call: None,
20886            rows_from: None,
20887            json_table: None,
20888            scalar_fn_item: false,
20889        })
20890    }
20891
20892    /// Absorb `WITH ORDINALITY` after an SRF call in FROM position.
20893    /// Returns true when the clause was present. `WITH` alone (a
20894    /// CTE can never start here) is not enough — the ORDINALITY
20895    /// ident must follow, so a stray WITH still errors downstream.
20896    fn absorb_with_ordinality(&mut self) -> bool {
20897        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("with"))
20898            && matches!(self.tokens.get(self.pos + 1),
20899                Some(Token::Ident(s)) if s.eq_ignore_ascii_case("ordinality"))
20900        {
20901            self.advance();
20902            self.advance();
20903            true
20904        } else {
20905            false
20906        }
20907    }
20908
20909    /// v7.39 (read01 partitionfuncs.c) — parse a FROM-position table
20910    /// function reference (`pg_partition_tree('t') [AS a(c, …)]`).
20911    /// Out-of-line: the caller sits on the FROM recursion chain.
20912    #[inline(never)]
20913    fn parse_table_fn_ref(&mut self) -> Result<TableRef, ParseError> {
20914        let fn_name = match self.advance() {
20915            Token::Ident(s) | Token::QuotedIdent(s) => s.to_ascii_lowercase(),
20916            _ => unreachable!("caller peeked an ident"),
20917        };
20918        self.advance(); // (
20919        let mut args: Vec<Expr> = Vec::new();
20920        if !matches!(self.peek(), Token::RParen) {
20921            loop {
20922                args.push(self.parse_expr(0)?);
20923                if matches!(self.peek(), Token::Comma) {
20924                    self.advance();
20925                    continue;
20926                }
20927                break;
20928            }
20929        }
20930        if !matches!(self.peek(), Token::RParen) {
20931            return Err(self.err(alloc::format!(
20932                "expected ')' after {fn_name}() arguments, got {:?}",
20933                self.peek()
20934            )));
20935        }
20936        self.advance();
20937        // v7.39 (read01 round 68) — `f(args) WITH ORDINALITY AS a(x, n)`: the
20938        // counter column rides after the function's own, and the alias list
20939        // names it.
20940        let with_ordinality = self.absorb_with_ordinality();
20941        let (alias_ident, unnest_column_aliases) = self.parse_optional_alias_with_columns()?;
20942        let name = alias_ident.clone().unwrap_or_else(|| fn_name.clone());
20943        Ok(TableRef {
20944            name,
20945            alias: alias_ident,
20946            only: false,
20947            as_of_segment: None,
20948            unnest_expr: None,
20949            unnest_column_aliases,
20950            with_ordinality,
20951            generate_series_args: None,
20952            lateral_subquery: None,
20953            jsonb_each_text_arg: None,
20954            table_fn_call: Some(Box::new((fn_name, args))),
20955            rows_from: None,
20956            json_table: None,
20957            scalar_fn_item: false,
20958        })
20959    }
20960
20961    /// v7.39 (round 205, JSON_TABLE) — parse
20962    /// `JSON_TABLE(<doc>, '<row_path>' [PASSING …] COLUMNS (<coldefs>))
20963    /// [AS <alias>]`. The COLUMNS list is a recursive tree (NESTED
20964    /// PATH nests another COLUMNS). Out-of-line (FROM recursion chain).
20965    #[inline(never)]
20966    fn parse_json_table_ref(&mut self) -> Result<TableRef, ParseError> {
20967        self.advance(); // json_table
20968        self.advance(); // (
20969        let doc = Box::new(self.parse_expr(0)?);
20970        self.expect_comma_json_table()?;
20971        let row_path = self.parse_json_string_literal("JSON_TABLE row path")?;
20972        // Optional `PASSING <expr> AS <name> [, …]`.
20973        let mut passing: Vec<(String, Expr)> = Vec::new();
20974        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("passing")) {
20975            self.advance();
20976            loop {
20977                let e = self.parse_expr(0)?;
20978                if !matches!(self.peek(), Token::As) {
20979                    return Err(self.err("expected AS after JSON_TABLE PASSING value".into()));
20980                }
20981                self.advance();
20982                let vname = match self.advance() {
20983                    Token::Ident(s) | Token::QuotedIdent(s) => s,
20984                    other => {
20985                        return Err(self.err(alloc::format!(
20986                            "expected PASSING variable name, got {other:?}"
20987                        )));
20988                    }
20989                };
20990                passing.push((vname, e));
20991                if matches!(self.peek(), Token::Comma) {
20992                    self.advance();
20993                    continue;
20994                }
20995                break;
20996            }
20997        }
20998        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("columns")) {
20999            return Err(self.err("expected COLUMNS in JSON_TABLE".into()));
21000        }
21001        self.advance();
21002        let columns = self.parse_json_table_columns()?;
21003        if !matches!(self.peek(), Token::RParen) {
21004            return Err(self.err(alloc::format!(
21005                "expected ')' to close JSON_TABLE, got {:?}",
21006                self.peek()
21007            )));
21008        }
21009        self.advance();
21010        let alias_ident = self.parse_optional_alias()?;
21011        let name = alias_ident
21012            .clone()
21013            .unwrap_or_else(|| String::from("json_table"));
21014        Ok(TableRef {
21015            name,
21016            alias: alias_ident,
21017            only: false,
21018            as_of_segment: None,
21019            unnest_expr: None,
21020            unnest_column_aliases: Vec::new(),
21021            with_ordinality: false,
21022            generate_series_args: None,
21023            lateral_subquery: None,
21024            jsonb_each_text_arg: None,
21025            table_fn_call: None,
21026            rows_from: None,
21027            json_table: Some(Box::new(crate::ast::JsonTable {
21028                doc,
21029                row_path,
21030                columns,
21031                passing,
21032            })),
21033            scalar_fn_item: false,
21034        })
21035    }
21036
21037    fn expect_comma_json_table(&mut self) -> Result<(), ParseError> {
21038        if !matches!(self.peek(), Token::Comma) {
21039            return Err(self.err(alloc::format!(
21040                "expected ',' after JSON_TABLE document, got {:?}",
21041                self.peek()
21042            )));
21043        }
21044        self.advance();
21045        Ok(())
21046    }
21047
21048    fn parse_json_string_literal(&mut self, what: &str) -> Result<String, ParseError> {
21049        match self.advance() {
21050            Token::String(s) => Ok(s),
21051            other => Err(self.err(alloc::format!(
21052                "expected {what} string literal, got {other:?}"
21053            ))),
21054        }
21055    }
21056
21057    /// v7.39 (round 205) — `( <coldef> [, <coldef>]* )`.
21058    #[inline(never)]
21059    fn parse_json_table_columns(
21060        &mut self,
21061    ) -> Result<alloc::vec::Vec<crate::ast::JsonTableColumn>, ParseError> {
21062        if !matches!(self.peek(), Token::LParen) {
21063            return Err(self.err("expected '(' after COLUMNS".into()));
21064        }
21065        self.advance();
21066        let mut cols = Vec::new();
21067        loop {
21068            cols.push(self.parse_json_table_one_column()?);
21069            if matches!(self.peek(), Token::Comma) {
21070                self.advance();
21071                continue;
21072            }
21073            break;
21074        }
21075        if !matches!(self.peek(), Token::RParen) {
21076            return Err(self.err(alloc::format!(
21077                "expected ')' after JSON_TABLE COLUMNS, got {:?}",
21078                self.peek()
21079            )));
21080        }
21081        self.advance();
21082        Ok(cols)
21083    }
21084
21085    fn parse_json_table_one_column(&mut self) -> Result<crate::ast::JsonTableColumn, ParseError> {
21086        use crate::ast::{JsonTableColumn, JsonTableOnBehavior};
21087        // NESTED [PATH] '<p>' COLUMNS (...)
21088        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("nested")) {
21089            self.advance();
21090            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("path")) {
21091                self.advance();
21092            }
21093            let path = self.parse_json_string_literal("NESTED PATH")?;
21094            if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("columns")) {
21095                return Err(self.err("expected COLUMNS after NESTED PATH".into()));
21096            }
21097            self.advance();
21098            let columns = self.parse_json_table_columns()?;
21099            return Ok(JsonTableColumn::Nested { path, columns });
21100        }
21101        // <name> ...
21102        let name = match self.advance() {
21103            Token::Ident(s) | Token::QuotedIdent(s) => s,
21104            other => {
21105                return Err(self.err(alloc::format!("expected column name, got {other:?}")));
21106            }
21107        };
21108        // <name> FOR ORDINALITY
21109        if matches!(self.peek(), Token::For) {
21110            self.advance();
21111            if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("ordinality")) {
21112                return Err(self.err("expected ORDINALITY after FOR".into()));
21113            }
21114            self.advance();
21115            return Ok(JsonTableColumn::Ordinality { name });
21116        }
21117        // <name> <type> [FORMAT JSON] {PATH '<p>' | EXISTS [PATH '<p>']} [WITH WRAPPER] [ON …]
21118        let ty = self.parse_column_type_name()?;
21119        let mut format_json = false;
21120        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("format")) {
21121            self.advance();
21122            if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("json")) {
21123                return Err(self.err("expected JSON after FORMAT".into()));
21124            }
21125            self.advance();
21126            format_json = true;
21127        }
21128        let mut exists = false;
21129        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("exists")) {
21130            self.advance();
21131            exists = true;
21132        }
21133        let mut path = alloc::format!("$.{name}");
21134        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("path")) {
21135            self.advance();
21136            path = self.parse_json_string_literal("column PATH")?;
21137        }
21138        if !exists && matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("format")) {
21139            // `FORMAT JSON` after PATH (alternate placement).
21140            self.advance();
21141            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("json")) {
21142                self.advance();
21143            }
21144            format_json = true;
21145        }
21146        let mut wrapper = false;
21147        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("with")) {
21148            self.advance();
21149            // optional CONDITIONAL/UNCONDITIONAL
21150            if matches!(self.peek(), Token::Ident(s)
21151                if s.eq_ignore_ascii_case("unconditional")
21152                    || s.eq_ignore_ascii_case("conditional"))
21153            {
21154                self.advance();
21155            }
21156            if !matches!(self.peek(), Token::Ident(s)
21157                if s.eq_ignore_ascii_case("wrapper") || s.eq_ignore_ascii_case("array"))
21158            {
21159                return Err(self.err("expected WRAPPER after WITH".into()));
21160            }
21161            self.advance();
21162            // optional `ARRAY` after `WRAPPER`, or `WRAPPER` after `ARRAY`
21163            if matches!(self.peek(), Token::Ident(s)
21164                if s.eq_ignore_ascii_case("wrapper") || s.eq_ignore_ascii_case("array"))
21165            {
21166                self.advance();
21167            }
21168            wrapper = true;
21169        }
21170        // ON EMPTY / ON ERROR clauses (two, in any order).
21171        let mut on_empty = JsonTableOnBehavior::Null;
21172        let mut on_error = JsonTableOnBehavior::Null;
21173        for _ in 0..2 {
21174            let behavior = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("error"))
21175            {
21176                self.advance();
21177                Some(JsonTableOnBehavior::Error)
21178            } else if matches!(self.peek(), Token::Null) {
21179                self.advance();
21180                Some(JsonTableOnBehavior::Null)
21181            } else if matches!(self.peek(), Token::Default) {
21182                self.advance();
21183                Some(JsonTableOnBehavior::Default(Box::new(self.parse_expr(0)?)))
21184            } else {
21185                None
21186            };
21187            let Some(behavior) = behavior else { break };
21188            // `ON {EMPTY|ERROR}`
21189            if !matches!(self.peek(), Token::On) {
21190                return Err(self.err("expected ON after JSON_TABLE column behavior".into()));
21191            }
21192            self.advance();
21193            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("empty")) {
21194                self.advance();
21195                on_empty = behavior;
21196            } else if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("error")) {
21197                self.advance();
21198                on_error = behavior;
21199            } else {
21200                return Err(self.err("expected EMPTY or ERROR after ON".into()));
21201            }
21202        }
21203        Ok(JsonTableColumn::Regular {
21204            name,
21205            ty,
21206            path,
21207            exists,
21208            format_json,
21209            wrapper,
21210            on_empty,
21211            on_error,
21212        })
21213    }
21214
21215    fn parse_optional_alias_with_columns(
21216        &mut self,
21217    ) -> Result<(Option<String>, Vec<String>), ParseError> {
21218        let alias = self.parse_optional_alias()?;
21219        if alias.is_none() {
21220            return Ok((None, Vec::new()));
21221        }
21222        let mut cols: Vec<String> = Vec::new();
21223        if matches!(self.peek(), Token::LParen) {
21224            self.advance();
21225            while let Token::Ident(s) | Token::QuotedIdent(s) = self.peek().clone() {
21226                self.advance();
21227                cols.push(s);
21228                if matches!(self.peek(), Token::Comma) {
21229                    self.advance();
21230                    continue;
21231                }
21232                break;
21233            }
21234            if matches!(self.peek(), Token::RParen) {
21235                self.advance();
21236            }
21237        }
21238        Ok((alias, cols))
21239    }
21240
21241    /// v7.37.16 — parse a `left(str, n)` / `right(str, n)` function call
21242    /// whose keyword token was already consumed and whose `(` is the
21243    /// current token. Factored out of `parse_atom` (and marked
21244    /// `#[inline(never)]`) so its `Vec`/loop locals stay OFF the giant
21245    /// recursive `parse_atom` frame — inlining them there enlarges the
21246    /// per-nesting-level stack cost that `MAX_NEST_DEPTH` is tuned
21247    /// against, risking an overflow before the budget triggers.
21248    #[inline(never)]
21249    fn parse_lr_string_function_call(&mut self, name: &str) -> Result<Expr, ParseError> {
21250        self.advance(); // (
21251        let mut args = Vec::new();
21252        if !matches!(self.peek(), Token::RParen) {
21253            loop {
21254                args.push(self.parse_expr(0)?);
21255                match self.peek() {
21256                    Token::Comma => {
21257                        self.advance();
21258                    }
21259                    Token::RParen => break,
21260                    other => {
21261                        return Err(self.err(alloc::format!(
21262                            "expected ',' or ')' in {name}() args, got {other:?}"
21263                        )));
21264                    }
21265                }
21266            }
21267        }
21268        self.advance(); // )
21269        Ok(Expr::FunctionCall {
21270            name: name.into(),
21271            args,
21272        })
21273    }
21274
21275    /// FROM-clause: a primary table reference plus zero-or-more joined
21276    /// peers expressed via either `, <table>` (cross-product, no ON) or
21277    /// `[INNER|LEFT|RIGHT [OUTER]|FULL [OUTER]|CROSS] JOIN <table> [ON expr]`.
21278    /// v1.10 keeps the join list flat (left-associative nested-loop
21279    /// semantics).
21280    fn parse_from_clause(&mut self) -> Result<FromClause, ParseError> {
21281        let primary = self.parse_table_ref()?;
21282        let primary_qual = primary
21283            .alias
21284            .clone()
21285            .unwrap_or_else(|| primary.name.clone());
21286        let joins = self.parse_from_joins(&primary_qual)?;
21287        Ok(FromClause { primary, joins })
21288    }
21289
21290    /// v7.39 (round 420) — the join tail of a FROM clause, factored out of
21291    /// [`Self::parse_from_clause`] so MySQL's multi-table UPDATE can read the
21292    /// SAME grammar after its target table has already been consumed.
21293    /// (`advance()` destroys the tokens it returns — `mem::replace(.., Eof)`
21294    /// — so re-parsing by rewinding `self.pos` is not possible; the tail must
21295    /// be parsed forward, once.)
21296    /// `left_primary_qual` is the qualifier (alias, else name) of whatever
21297    /// sits to the LEFT of the first join — the FROM primary, or the UPDATE
21298    /// target in the MySQL multi-table form. It only feeds the `USING (…)`
21299    /// desugaring, which needs a name for the left side of each equality.
21300    fn parse_from_joins(&mut self, left_primary_qual: &str) -> Result<Vec<FromJoin>, ParseError> {
21301        let mut joins = Vec::new();
21302        loop {
21303            // `, <table>` — cross-product with no ON.
21304            if matches!(self.peek(), Token::Comma) {
21305                self.advance();
21306                let table = self.parse_table_ref()?;
21307                joins.push(FromJoin {
21308                    kind: JoinKind::Cross,
21309                    table,
21310                    on: None,
21311                    using_cols: None,
21312                    natural: false,
21313                });
21314                continue;
21315            }
21316            // v7.37.16 — optional leading `NATURAL` before the join
21317            // kind: `NATURAL JOIN`, `NATURAL LEFT JOIN`, etc. NATURAL is
21318            // not a lexer keyword (it arrives as a bare Ident), so match
21319            // it case-insensitively here. When present, no ON/USING
21320            // clause is allowed — the common columns are resolved at
21321            // execution time.
21322            let natural = matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("natural"));
21323            if natural {
21324                self.advance();
21325            }
21326            // Explicit JOIN syntax. Accept INNER JOIN, LEFT [OUTER] JOIN,
21327            // CROSS JOIN, and bare JOIN (defaults to INNER).
21328            let kind =
21329                match self.peek() {
21330                    Token::Inner => {
21331                        self.advance();
21332                        if !matches!(self.peek(), Token::Join) {
21333                            return Err(self
21334                                .err(format!("expected JOIN after INNER, got {:?}", self.peek())));
21335                        }
21336                        self.advance();
21337                        JoinKind::Inner
21338                    }
21339                    Token::Left => {
21340                        self.advance();
21341                        if matches!(self.peek(), Token::Outer) {
21342                            self.advance();
21343                        }
21344                        if !matches!(self.peek(), Token::Join) {
21345                            return Err(self.err(format!(
21346                                "expected JOIN after LEFT [OUTER], got {:?}",
21347                                self.peek()
21348                            )));
21349                        }
21350                        self.advance();
21351                        JoinKind::Left
21352                    }
21353                    Token::Cross => {
21354                        self.advance();
21355                        if !matches!(self.peek(), Token::Join) {
21356                            return Err(self
21357                                .err(format!("expected JOIN after CROSS, got {:?}", self.peek())));
21358                        }
21359                        self.advance();
21360                        JoinKind::Cross
21361                    }
21362                    // v7.37.16 — RIGHT [OUTER] JOIN. OUTER is optional noise.
21363                    Token::Right => {
21364                        self.advance();
21365                        if matches!(self.peek(), Token::Outer) {
21366                            self.advance();
21367                        }
21368                        if !matches!(self.peek(), Token::Join) {
21369                            return Err(self.err(format!(
21370                                "expected JOIN after RIGHT [OUTER], got {:?}",
21371                                self.peek()
21372                            )));
21373                        }
21374                        self.advance();
21375                        JoinKind::Right
21376                    }
21377                    // v7.37.16 — FULL [OUTER] JOIN. OUTER is optional noise.
21378                    Token::Full => {
21379                        self.advance();
21380                        if matches!(self.peek(), Token::Outer) {
21381                            self.advance();
21382                        }
21383                        if !matches!(self.peek(), Token::Join) {
21384                            return Err(self.err(format!(
21385                                "expected JOIN after FULL [OUTER], got {:?}",
21386                                self.peek()
21387                            )));
21388                        }
21389                        self.advance();
21390                        JoinKind::FullOuter
21391                    }
21392                    Token::Join => {
21393                        self.advance();
21394                        JoinKind::Inner
21395                    }
21396                    _ => break,
21397                };
21398            let table = self.parse_table_ref()?;
21399            // v7.37.7 C.1 — USING (col_list) sugar. Desugars to
21400            // `prev_table.col1 = table.col1 AND prev_table.col2 = table.col2 …`
21401            // where prev_table is the most-recent left-side table
21402            // (the previous join's table if any, else the FROM primary).
21403            // PG semantics around column merging are richer (USING'd
21404            // cols become deduplicated single output columns); for
21405            // sugar purposes the predicate-only form covers the
21406            // baseline corpus shape and chained `… JOIN x USING (k)
21407            // JOIN y USING (k)` calls.
21408            // v7.37.16 — NATURAL joins carry no ON/USING clause; the
21409            // common columns resolve at execution time.
21410            if natural {
21411                joins.push(FromJoin {
21412                    kind,
21413                    table,
21414                    on: None,
21415                    using_cols: None,
21416                    natural: true,
21417                });
21418                continue;
21419            }
21420            let using_match = matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("using"));
21421            // v7.37.16 — capture the USING column list (in addition to
21422            // the ON desugar below) so the executor can perform PG's
21423            // column-merge on the output side.
21424            let mut using_cols: Option<Vec<String>> = None;
21425            let on = if matches!(self.peek(), Token::On) {
21426                self.advance();
21427                Some(self.parse_expr(0)?)
21428            } else if using_match {
21429                self.advance();
21430                if !matches!(self.peek(), Token::LParen) {
21431                    return Err(
21432                        self.err(format!("expected '(' after USING, got {:?}", self.peek()))
21433                    );
21434                }
21435                self.advance();
21436                let mut cols: Vec<String> = Vec::new();
21437                loop {
21438                    match self.peek().clone() {
21439                        Token::Ident(s) | Token::QuotedIdent(s) => {
21440                            self.advance();
21441                            cols.push(s);
21442                        }
21443                        other => {
21444                            return Err(self.err(format!(
21445                                "expected column name inside USING (…), got {other:?}"
21446                            )));
21447                        }
21448                    }
21449                    match self.peek() {
21450                        Token::Comma => {
21451                            self.advance();
21452                            continue;
21453                        }
21454                        Token::RParen => {
21455                            self.advance();
21456                            break;
21457                        }
21458                        other => {
21459                            return Err(self.err(format!(
21460                                "expected ',' or ')' inside USING (…), got {other:?}"
21461                            )));
21462                        }
21463                    }
21464                }
21465                if cols.is_empty() {
21466                    return Err(self.err("USING (…) requires at least one column".to_string()));
21467                }
21468                using_cols = Some(cols.clone());
21469                // Pick the left-side alias: prev join's table if any,
21470                // else FROM primary. Use alias when present, else
21471                // table name (PG-equivalent qualifier).
21472                let left_qual: String = joins
21473                    .last()
21474                    .map(|j| {
21475                        j.table
21476                            .alias
21477                            .clone()
21478                            .unwrap_or_else(|| j.table.name.clone())
21479                    })
21480                    .unwrap_or_else(|| alloc::string::String::from(left_primary_qual));
21481                let right_qual = table.alias.clone().unwrap_or_else(|| table.name.clone());
21482                let mut iter = cols.into_iter().map(|c| Expr::Binary {
21483                    lhs: alloc::boxed::Box::new(Expr::Column(crate::ast::ColumnName {
21484                        qualifier: Some(left_qual.clone()),
21485                        name: c.clone(),
21486                    })),
21487                    op: crate::ast::BinOp::Eq,
21488                    rhs: alloc::boxed::Box::new(Expr::Column(crate::ast::ColumnName {
21489                        qualifier: Some(right_qual.clone()),
21490                        name: c,
21491                    })),
21492                });
21493                let first = iter.next().expect("at least one col");
21494                Some(iter.fold(first, |acc, pred| Expr::Binary {
21495                    lhs: alloc::boxed::Box::new(acc),
21496                    op: crate::ast::BinOp::And,
21497                    rhs: alloc::boxed::Box::new(pred),
21498                }))
21499            } else if kind == JoinKind::Cross {
21500                None
21501            } else {
21502                return Err(self.err(format!(
21503                    "expected ON or USING after {:?} JOIN, got {:?}",
21504                    kind,
21505                    self.peek()
21506                )));
21507            };
21508            joins.push(FromJoin {
21509                kind,
21510                table,
21511                on,
21512                using_cols,
21513                natural: false,
21514            });
21515        }
21516        Ok(joins)
21517    }
21518
21519    /// Optional alias after an expression or table:
21520    /// `AS <ident>` is unambiguous; a bare `<ident>` directly after is also
21521    /// accepted (PG-style implicit alias). Returns `None` if the next token
21522    /// is not alias-shaped (e.g. comma, FROM, WHERE, semicolon, EOF, operator).
21523    fn parse_optional_alias(&mut self) -> Result<Option<String>, ParseError> {
21524        if matches!(self.peek(), Token::As) {
21525            self.advance();
21526            // v7.39 (round 340, V56) — after AS the next token MUST be an
21527            // identifier. This used to return None and "let the caller
21528            // surface the error on the next expectation", but when AS is
21529            // the LAST token there is no next expectation: `SELECT 1 AS`
21530            // parsed clean and silently dropped the alias. PG rejects it.
21531            if let Token::Ident(_) | Token::QuotedIdent(_) = self.peek() {
21532                return self.expect_ident_like().map(Some);
21533            }
21534            return Err(self.err(alloc::format!(
21535                "expected an alias after AS, got {:?}",
21536                self.peek()
21537            )));
21538        }
21539        // v7.17.0 Phase 1.3 — implicit alias (no `AS`). PG's
21540        // grammar reserves a long list of follow-keywords from the
21541        // alias slot. SPG's bareword approximation: skip a small
21542        // set of idents that would otherwise be swallowed as the
21543        // table alias and break trailing clauses like CREATE
21544        // MATERIALIZED VIEW … WITH [NO] DATA or future ON
21545        // CONFLICT WHERE shapes.
21546        if let Token::Ident(s) | Token::QuotedIdent(s) = self.peek() {
21547            if is_alias_stopword(s) {
21548                return Ok(None);
21549            }
21550            return Ok(self.expect_ident_like().ok());
21551        }
21552        Ok(None)
21553    }
21554
21555    /// Pratt loop. `min_prec` is the minimum binary-op precedence we'll accept.
21556    fn parse_expr(&mut self, min_prec: u8) -> Result<Expr, ParseError> {
21557        // v7.30.2 (mailrs round-25 ask 2) — nesting budget: a parse
21558        // error beats a stack overflow (an overflow aborts the
21559        // embedding host process).
21560        self.enter_nested()?;
21561        let r = self.parse_expr_inner(min_prec);
21562        self.nest_depth -= 1;
21563        r
21564    }
21565
21566    /// `OPERATOR([schema.]<op>)` — PG's explicit-operator spelling.
21567    /// When the upcoming tokens form one, return the underlying
21568    /// operator token and the position just past the closing paren
21569    /// so the binary loop can dispatch on the plain operator.
21570    fn peek_explicit_operator(&self) -> Option<(usize, Token)> {
21571        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("operator")) {
21572            return None;
21573        }
21574        if !matches!(self.tokens.get(self.pos + 1), Some(Token::LParen)) {
21575            return None;
21576        }
21577        let mut i = self.pos + 2;
21578        // Optional schema qualifier (pg_catalog.<op> etc.).
21579        if matches!(self.tokens.get(i), Some(Token::Ident(_)))
21580            && matches!(self.tokens.get(i + 1), Some(Token::Dot))
21581        {
21582            i += 2;
21583        }
21584        let op_tok = self.tokens.get(i)?.clone();
21585        if !matches!(self.tokens.get(i + 1), Some(Token::RParen)) {
21586            return None;
21587        }
21588        Some((i + 2, op_tok))
21589    }
21590
21591    /// PG operator symbols that lower onto function calls in
21592    /// binary position: `~` / `~*` / `!~` / `!~*` (regex match
21593    /// family → regexp_like, comparison rung), `^@` (starts_with,
21594    /// comparison rung), `^` (power, tighter than `*`), `#`
21595    /// (integer XOR via `(a|b) - (a&b)` — the AND bits are a
21596    /// subset of the OR bits so the subtraction never borrows).
21597    fn try_symbol_operator(
21598        &mut self,
21599        lhs: &Expr,
21600        min_prec: u8,
21601    ) -> Result<Option<Expr>, ParseError> {
21602        enum Sym {
21603            Regex { ci: bool, negated: bool },
21604            Like { ci: bool, negated: bool },
21605            StartsWith,
21606            Power,
21607            Xor,
21608            RangeAdjacent,
21609        }
21610        // v7.39 (IS-precedence knife) — the low-precedence postfix
21611        // predicates ride this existing leaf call (zero new frame slots
21612        // on the nesting chain).
21613        if let Some(e) = self.parse_postfix_predicate(lhs, min_prec)? {
21614            return Ok(Some(e));
21615        }
21616        let (sym, prec): (Sym, u8) = match self.peek() {
21617            Token::Tilde => (
21618                Sym::Regex {
21619                    ci: false,
21620                    negated: false,
21621                },
21622                5,
21623            ),
21624            Token::TildeStar => (
21625                Sym::Regex {
21626                    ci: true,
21627                    negated: false,
21628                },
21629                5,
21630            ),
21631            Token::NotTilde => (
21632                Sym::Regex {
21633                    ci: false,
21634                    negated: true,
21635                },
21636                5,
21637            ),
21638            Token::NotTildeStar => (
21639                Sym::Regex {
21640                    ci: true,
21641                    negated: true,
21642                },
21643                5,
21644            ),
21645            // v7.37 D.25 — PG operator spellings of LIKE/ILIKE.
21646            Token::DoubleTilde => (
21647                Sym::Like {
21648                    ci: false,
21649                    negated: false,
21650                },
21651                5,
21652            ),
21653            Token::DoubleTildeStar => (
21654                Sym::Like {
21655                    ci: true,
21656                    negated: false,
21657                },
21658                5,
21659            ),
21660            Token::NotDoubleTilde => (
21661                Sym::Like {
21662                    ci: false,
21663                    negated: true,
21664                },
21665                5,
21666            ),
21667            Token::NotDoubleTildeStar => (
21668                Sym::Like {
21669                    ci: true,
21670                    negated: true,
21671                },
21672                5,
21673            ),
21674            Token::CaretAt => (Sym::StartsWith, 5),
21675            // PG `^` is exponentiation; MySQL `^` is bitwise XOR (and binds
21676            // tighter than `* / & |`, which the prec-9 rung preserves —
21677            // v7.39 round 407: +1 from the pre-XOR ladder's rung 8).
21678            Token::Caret if self.mysql_dialect => (Sym::Xor, 9),
21679            Token::Caret => (Sym::Power, 9),
21680            // v7.39 (round 760, F31-B1) — `#` is a generic operator too:
21681            // PG answers `5 # 3 + 1` as `5 # 4` = 1 (additive first).
21682            Token::Hash => (Sym::Xor, 6),
21683            Token::Adjacent => (Sym::RangeAdjacent, 5),
21684            _ => return Ok(None),
21685        };
21686        if prec < min_prec {
21687            return Ok(None);
21688        }
21689        self.advance();
21690        let rhs = self.parse_expr(prec + 1)?;
21691        let out = match sym {
21692            Sym::Regex { ci, negated } => {
21693                let mut args = alloc::vec![lhs.clone(), rhs];
21694                if ci {
21695                    args.push(Expr::Literal(Literal::String(String::from("i"))));
21696                }
21697                maybe_not(
21698                    Expr::FunctionCall {
21699                        name: String::from("regexp_like"),
21700                        args,
21701                    },
21702                    negated,
21703                )
21704            }
21705            Sym::Like { ci, negated } => Expr::Like {
21706                expr: alloc::boxed::Box::new(lhs.clone()),
21707                pattern: alloc::boxed::Box::new(rhs),
21708                negated,
21709                case_insensitive: ci,
21710            },
21711            Sym::StartsWith => Expr::FunctionCall {
21712                name: String::from("starts_with"),
21713                args: alloc::vec![lhs.clone(), rhs],
21714            },
21715            Sym::Power => Expr::FunctionCall {
21716                name: String::from("power"),
21717                args: alloc::vec![lhs.clone(), rhs],
21718            },
21719            // `#` bitwise XOR — a real operator now (was desugared to
21720            // `(a|b)-(a&b)`, algebraically identical for integers but
21721            // undefined for bit strings; the direct op handles both).
21722            Sym::Xor => Expr::Binary {
21723                lhs: Box::new(lhs.clone()),
21724                op: BinOp::BitXor,
21725                rhs: Box::new(rhs),
21726            },
21727            // range `-|-` "is adjacent to" — lowered to a catalog function.
21728            Sym::RangeAdjacent => Expr::FunctionCall {
21729                name: String::from("range_adjacent"),
21730                args: alloc::vec![lhs.clone(), rhs],
21731            },
21732        };
21733        Ok(Some(out))
21734    }
21735
21736    /// v7.39 (IS-precedence knife) — the LOW-precedence postfix
21737    /// predicates, moved out of the tight postfix-cast loop: PG binds
21738    /// `IS [NOT] NULL/TRUE/FALSE/UNKNOWN/DISTINCT FROM/JSON/NORMALIZED`
21739    /// looser than EVERY binary operator (only NOT/AND/OR are looser),
21740    /// and BETWEEN/IN/LIKE/ILIKE/SIMILAR at the comparison rung — so
21741    /// `1 + 1 IS NULL` is `(1+1) IS NULL`, not `1 + (1 IS NULL)`.
21742    /// Returns Ok(consumed expr) when a predicate fired, Err(expr back)
21743    /// when nothing at this position belongs to the family. Out-of-line
21744    /// (`inline(never)`): the caller sits on the per-nesting-level frame
21745    /// chain that MAX_NEST_DEPTH is tuned against.
21746    #[inline(never)]
21747    fn parse_postfix_predicate(
21748        &mut self,
21749        lhs: &Expr,
21750        min_prec: u8,
21751    ) -> Result<Option<Expr>, ParseError> {
21752        // Reached through try_symbol_operator (an existing leaf call of
21753        // the binary loop) so NO new stack slots land on the per-nesting
21754        // frame chain; the lhs clones only when a predicate actually
21755        // consumes it.
21756        match self.peek() {
21757            // v7.39 (round 407) — IS is rung 4, the BETWEEN/IN/LIKE
21758            // comparison family rung 5 (each +1 from the pre-XOR ladder).
21759            Token::Is if min_prec <= 4 => {}
21760            Token::Between | Token::In | Token::Like if min_prec <= 5 => {}
21761            Token::Not
21762                if min_prec <= 5
21763                    && matches!(
21764                        self.tokens.get(self.pos + 1),
21765                        Some(Token::Between | Token::In | Token::Like)
21766                    ) => {}
21767            Token::Not | Token::Ident(_)
21768                if min_prec <= 5
21769                    && (matches!(self.peek(), Token::Ident(s)
21770                            if s.eq_ignore_ascii_case("ilike")
21771                                || (self.mysql_dialect
21772                                    && (s.eq_ignore_ascii_case("regexp")
21773                                        || s.eq_ignore_ascii_case("rlike")))
21774                                || (s.eq_ignore_ascii_case("similar")
21775                                    && matches!(self.tokens.get(self.pos + 1), Some(Token::To))))
21776                        || (matches!(self.peek(), Token::Not)
21777                            && matches!(self.tokens.get(self.pos + 1),
21778                                Some(Token::Ident(s)) if s.eq_ignore_ascii_case("ilike")
21779                                    || (self.mysql_dialect
21780                                        && (s.eq_ignore_ascii_case("regexp")
21781                                            || s.eq_ignore_ascii_case("rlike")))
21782                                    || s.eq_ignore_ascii_case("similar")))) => {}
21783            _ => return Ok(None),
21784        }
21785        let mut expr = lhs.clone();
21786        // IS family: rung 4 (NOT's operand parses at 4, so `NOT x IS NULL`
21787        // still groups as NOT (x IS NULL); OR/XOR/AND at 1-3 stay outside).
21788        if min_prec <= 4 {
21789            if matches!(self.peek(), Token::Is) {
21790                self.advance();
21791                let negated = if matches!(self.peek(), Token::Not) {
21792                    self.advance();
21793                    true
21794                } else {
21795                    false
21796                };
21797                // v7.9.27b — `IS [NOT] DISTINCT FROM <rhs>`.
21798                // mailrs pg_dump.
21799                if matches!(self.peek(), Token::Distinct) {
21800                    self.advance();
21801                    if !matches!(self.peek(), Token::From) {
21802                        return Err(self.err(format!(
21803                            "expected FROM after IS{} DISTINCT, got {:?}",
21804                            if negated { " NOT" } else { "" },
21805                            self.peek()
21806                        )));
21807                    }
21808                    self.advance();
21809                    // Right-hand side: parse at the same precedence
21810                    // tier as comparison (rung 5) so `x IS DISTINCT FROM a + b`
21811                    // groups as `x IS DISTINCT FROM (a + b)`.
21812                    let rhs = self.parse_expr(5)?;
21813                    let op = if negated {
21814                        BinOp::IsNotDistinctFrom
21815                    } else {
21816                        BinOp::IsDistinctFrom
21817                    };
21818                    expr = Expr::Binary {
21819                        op,
21820                        lhs: Box::new(expr),
21821                        rhs: Box::new(rhs),
21822                    };
21823                    {
21824                        return Ok(Some(expr));
21825                    }
21826                }
21827                // v7.37.17 (17.6 siblings) — SQL:2016 / PG 16
21828                // `IS [NOT] JSON [VALUE|OBJECT|ARRAY|SCALAR]`.
21829                // Lowers onto pg_is_json(x, kind); NOT wraps the
21830                // call in a logical negation.
21831                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
21832                if s.eq_ignore_ascii_case("json"))
21833                {
21834                    self.advance(); // JSON
21835                    let kind = match self.peek() {
21836                        Token::Ident(s) | Token::QuotedIdent(s)
21837                            if matches!(
21838                                s.to_ascii_lowercase().as_str(),
21839                                "value" | "object" | "array" | "scalar"
21840                            ) =>
21841                        {
21842                            let k = s.to_ascii_lowercase();
21843                            self.advance();
21844                            k
21845                        }
21846                        _ => "value".to_string(),
21847                    };
21848                    let call = Expr::FunctionCall {
21849                        name: "pg_is_json".to_string(),
21850                        args: alloc::vec![expr, Expr::Literal(Literal::String(kind)),],
21851                    };
21852                    expr = if negated {
21853                        Expr::Unary {
21854                            op: UnOp::Not,
21855                            expr: Box::new(call),
21856                        }
21857                    } else {
21858                        call
21859                    };
21860                    {
21861                        return Ok(Some(expr));
21862                    }
21863                }
21864                // v7.38 (read01 sweep) — SQL:2016 `x IS [NOT] [form]
21865                // NORMALIZED` (form ∈ NFC/NFD/NFKC/NFKD, default NFC).
21866                // Lowers onto is_normalized(x [, 'FORM']); NOT negates.
21867                {
21868                    let form_kw = match self.peek() {
21869                        Token::Ident(s) | Token::QuotedIdent(s)
21870                            if matches!(
21871                                s.to_ascii_uppercase().as_str(),
21872                                "NFC" | "NFD" | "NFKC" | "NFKD"
21873                            ) && matches!(
21874                                self.tokens.get(self.pos + 1),
21875                                Some(Token::Ident(n) | Token::QuotedIdent(n))
21876                                    if n.eq_ignore_ascii_case("normalized")
21877                            ) =>
21878                        {
21879                            Some(s.to_ascii_uppercase())
21880                        }
21881                        _ => None,
21882                    };
21883                    let bare_normalized = form_kw.is_none()
21884                        && matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
21885                        if s.eq_ignore_ascii_case("normalized"));
21886                    if form_kw.is_some() || bare_normalized {
21887                        if form_kw.is_some() {
21888                            self.advance(); // form keyword
21889                        }
21890                        self.advance(); // NORMALIZED
21891                        let mut args = alloc::vec![expr];
21892                        if let Some(f) = form_kw {
21893                            args.push(Expr::Literal(Literal::String(f)));
21894                        }
21895                        let call = Expr::FunctionCall {
21896                            name: "is_normalized".to_string(),
21897                            args,
21898                        };
21899                        expr = if negated {
21900                            Expr::Unary {
21901                                op: UnOp::Not,
21902                                expr: Box::new(call),
21903                            }
21904                        } else {
21905                            call
21906                        };
21907                        {
21908                            return Ok(Some(expr));
21909                        }
21910                    }
21911                }
21912                // `x IS [NOT] TRUE | FALSE | UNKNOWN` — the
21913                // three-valued boolean tests. IS TRUE/FALSE never
21914                // return NULL, so they lower to CASE forms whose
21915                // ELSE catches the NULL branch; IS UNKNOWN on a
21916                // boolean is exactly IS NULL.
21917                if matches!(self.peek(), Token::True | Token::False)
21918                    || matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("unknown"))
21919                {
21920                    let tok = self.advance();
21921                    let test = match tok {
21922                        Token::True => Some(true),
21923                        Token::False => Some(false),
21924                        _ => None, // UNKNOWN
21925                    };
21926                    // v7.39 (round 328, V45) — kept as what the user
21927                    // wrote. These used to be lowered here into `CASE` /
21928                    // `IS NULL`; the semantics were right but the AST no
21929                    // longer knew the form, so `CHECK ((a > 1) IS TRUE)`
21930                    // was echoed back as
21931                    // `CHECK ((CASE WHEN (a > 1) THEN TRUE ELSE FALSE END))`.
21932                    expr = Expr::BoolTest {
21933                        expr: Box::new(expr),
21934                        value: test,
21935                        negated,
21936                    };
21937                    {
21938                        return Ok(Some(expr));
21939                    }
21940                }
21941                if !matches!(self.peek(), Token::Null) {
21942                    return Err(self.err(format!(
21943                    "expected NULL, DISTINCT, JSON, TRUE, FALSE or UNKNOWN after IS{}, got {:?}",
21944                    if negated { " NOT" } else { "" },
21945                    self.peek()
21946                )));
21947                }
21948                self.advance();
21949                expr = Expr::IsNull {
21950                    expr: Box::new(expr),
21951                    negated,
21952                };
21953                {
21954                    return Ok(Some(expr));
21955                }
21956            }
21957        }
21958        // BETWEEN / IN / LIKE / ILIKE / SIMILAR: comparison rung (5).
21959        if min_prec <= 5 {
21960            // `x [NOT] BETWEEN a AND b`, `x [NOT] IN (...)`, `x [NOT] LIKE p`.
21961            // Look one token ahead so a stray `NOT` not followed by any of
21962            // these flows through to the early return below untouched.
21963            let negated = if matches!(self.peek(), Token::Not) {
21964                let next = self.tokens.get(self.pos + 1);
21965                matches!(next, Some(Token::Between | Token::In | Token::Like))
21966                    || matches!(next, Some(Token::Ident(s)) if s.eq_ignore_ascii_case("ilike")
21967                    || (self.mysql_dialect
21968                        && (s.eq_ignore_ascii_case("regexp") || s.eq_ignore_ascii_case("rlike")))
21969                    || s.eq_ignore_ascii_case("similar"))
21970            } else {
21971                false
21972            };
21973            if negated {
21974                self.advance();
21975            }
21976            if matches!(self.peek(), Token::Between) {
21977                expr = self.parse_between_tail(expr, negated)?;
21978                {
21979                    return Ok(Some(expr));
21980                }
21981            }
21982            if matches!(self.peek(), Token::In) {
21983                if self.suppress_in_tail && !negated {
21984                    // POSITION(sub IN str) — IN belongs to the
21985                    // enclosing function syntax; stop here.
21986                    {
21987                        return Ok(None);
21988                    }
21989                }
21990                expr = self.parse_in_tail(expr, negated)?;
21991                {
21992                    return Ok(Some(expr));
21993                }
21994            }
21995            // v7.39 (read01 regexp.c) — `x [NOT] SIMILAR TO p [ESCAPE e]`
21996            // lowers onto the internal __similar_to(expr, pat[, esc]) call
21997            // (the SQL→regex transform runs inside, in the backtracking-
21998            // friendly shape SPG's matcher needs).
21999            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("similar"))
22000                && matches!(self.tokens.get(self.pos + 1), Some(Token::To))
22001            {
22002                self.advance(); // SIMILAR
22003                self.advance(); // TO
22004                let pattern = self.parse_expr(6)?;
22005                let mut args = alloc::vec![expr, pattern];
22006                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("escape")) {
22007                    self.advance();
22008                    args.push(self.parse_expr(6)?);
22009                }
22010                let call = Expr::FunctionCall {
22011                    name: "__similar_to".to_string(),
22012                    args,
22013                };
22014                expr = maybe_not(call, negated);
22015                {
22016                    return Ok(Some(expr));
22017                }
22018            }
22019            if matches!(self.peek(), Token::Like) {
22020                self.advance();
22021                // `x [NOT] LIKE ANY/ALL (ARRAY[...])` — quantified LIKE.
22022                if let Some(q) = self.try_like_any_all(&expr, negated, false)? {
22023                    expr = q;
22024                    {
22025                        return Ok(Some(expr));
22026                    }
22027                }
22028                // Pattern at the same precedence as other comparison RHSes —
22029                // 5 leaves AND/OR alone so `a LIKE 'x%' AND b` parses right.
22030                let mut pattern = self.parse_expr(6)?;
22031                // `ESCAPE 'c'` — rewrite a literal pattern to the
22032                // default backslash escape at parse time. Custom
22033                // escapes on non-literal patterns would need
22034                // matcher support; error honestly.
22035                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("escape")) {
22036                    self.advance();
22037                    let esc = self.parse_expr(6)?;
22038                    pattern = Self::rewrite_like_escape(pattern, esc).map_err(|m| self.err(m))?;
22039                }
22040                expr = Expr::Like {
22041                    expr: Box::new(expr),
22042                    pattern: Box::new(pattern),
22043                    negated,
22044                    case_insensitive: false,
22045                };
22046                {
22047                    return Ok(Some(expr));
22048                }
22049            }
22050            // v7.25 (round-17) — ILIKE: case-insensitive LIKE. The
22051            // keyword reaches us as a plain identifier.
22052            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("ilike")) {
22053                self.advance();
22054                if let Some(q) = self.try_like_any_all(&expr, negated, true)? {
22055                    expr = q;
22056                    {
22057                        return Ok(Some(expr));
22058                    }
22059                }
22060                let pattern = self.parse_expr(6)?;
22061                expr = Expr::Like {
22062                    expr: Box::new(expr),
22063                    pattern: Box::new(pattern),
22064                    negated,
22065                    case_insensitive: true,
22066                };
22067                {
22068                    return Ok(Some(expr));
22069                }
22070            }
22071            // v7.39 (round 380) — MySQL's REGEXP / RLIKE regex-match
22072            // operator (RLIKE is the alias). It is a keyword, not `~`, and
22073            // matches case-insensitively under the default collation, so it
22074            // lowers onto the same `regexp_like(expr, pattern, 'i')` the
22075            // `~*` operator uses, wrapped in NOT when negated.
22076            if self.mysql_dialect
22077                && matches!(self.peek(), Token::Ident(s)
22078                    if s.eq_ignore_ascii_case("regexp") || s.eq_ignore_ascii_case("rlike"))
22079            {
22080                self.advance();
22081                let pattern = self.parse_expr(6)?;
22082                let call = Expr::FunctionCall {
22083                    name: String::from("regexp_like"),
22084                    args: alloc::vec![
22085                        expr,
22086                        pattern,
22087                        Expr::Literal(Literal::String(String::from("i"))),
22088                    ],
22089                };
22090                return Ok(Some(maybe_not(call, negated)));
22091            }
22092        }
22093        let _ = expr;
22094        Ok(None)
22095    }
22096
22097    fn parse_expr_inner(&mut self, min_prec: u8) -> Result<Expr, ParseError> {
22098        let mut lhs = self.parse_unary()?;
22099        let mut chain_len = 0usize;
22100        loop {
22101            // OPERATOR([schema.]op) reduces to its underlying
22102            // operator token before the normal dispatch.
22103            let explicit = self.peek_explicit_operator();
22104            let dispatch = match &explicit {
22105                Some((_, tok)) => self.binop_here(tok),
22106                None => self.binop_here(self.peek()),
22107            };
22108            let Some((op, prec)) = dispatch else {
22109                // v7.39 (round 539) — `OPERATOR(pg_catalog.~)` and the rest
22110                // of the symbol family. `binop_here` answers None for them
22111                // because they lower onto function calls rather than a
22112                // BinOp, and the fallback below reads `self.peek()` — the
22113                // word OPERATOR, not the operator. `pg_dump` writes every
22114                // catalog predicate this way, so its first query failed
22115                // and no dump ran:
22116                //
22117                //   AND c.relname OPERATOR(pg_catalog.~) '^(t)$'
22118                //
22119                // Collapsing the wrapper to the operator it names puts the
22120                // token where the fallback already looks.
22121                if let Some((next, op_tok)) = explicit {
22122                    self.tokens.splice(self.pos..next, [op_tok]);
22123                }
22124                if let Some(e) = self.try_symbol_operator(&lhs, min_prec)? {
22125                    lhs = e;
22126                    chain_len += 1;
22127                    if chain_len > MAX_BINARY_CHAIN {
22128                        return Err(self.err(alloc::format!(
22129                            "more than {MAX_BINARY_CHAIN} chained binary operators"
22130                        )));
22131                    }
22132                    continue;
22133                }
22134                break;
22135            };
22136            if prec < min_prec {
22137                break;
22138            }
22139            // v7.30.2 (mailrs round-25 ask 2) — the chain builds
22140            // iteratively but evaluates and drops recursively;
22141            // depth beyond the budget overflows worker stacks.
22142            chain_len += 1;
22143            if chain_len > MAX_BINARY_CHAIN {
22144                return Err(self.err(alloc::format!(
22145                    "more than {MAX_BINARY_CHAIN} chained binary operators; rewrite long OR-equality chains as IN (…)"
22146                )));
22147            }
22148            match explicit {
22149                Some((end_pos, _)) => self.pos = end_pos,
22150                None => {
22151                    self.advance();
22152                }
22153            }
22154            // v7.10.12 — `x <op> ANY(arr)` / `x <op> ALL(arr)`.
22155            // ANY is a bare ident; ALL is a reserved Token. Both
22156            // require an immediate `(` to disambiguate from
22157            // identifier columns named `any` / `all`.
22158            let any_kind = match self.peek() {
22159                Token::All if matches!(self.tokens.get(self.pos + 1), Some(Token::LParen)) => {
22160                    Some(false)
22161                }
22162                Token::Ident(s) | Token::QuotedIdent(s)
22163                    if (s.eq_ignore_ascii_case("any")
22164                        || s.eq_ignore_ascii_case("some")
22165                        || s.eq_ignore_ascii_case("all"))
22166                        && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen)) =>
22167                {
22168                    Some(!s.eq_ignore_ascii_case("all"))
22169                }
22170                _ => None,
22171            };
22172            if let Some(is_any) = any_kind {
22173                lhs = self.parse_any_all_rhs(lhs, op, is_any)?;
22174                continue;
22175            }
22176            let rhs = self.parse_expr(prec + 1)?;
22177            lhs = Expr::Binary {
22178                lhs: Box::new(lhs),
22179                op,
22180                rhs: Box::new(rhs),
22181            };
22182        }
22183        Ok(lhs)
22184    }
22185
22186    /// `x <op> ANY (…)` / `ALL (…)`, both the quantified-subquery form
22187    /// and the array form.
22188    ///
22189    /// `#[inline(never)]` and out of `parse_expr_inner`, which sits on the
22190    /// frame chain `MAX_NEST_DEPTH` is tuned against: a debug build gives
22191    /// this block's `Expr` temporaries and four `format!` sites slots in
22192    /// that frame on every level of `((((1))))`, which never reaches it.
22193    #[inline(never)]
22194    fn parse_any_all_rhs(
22195        &mut self,
22196        lhs: Expr,
22197        op: BinOp,
22198        is_any: bool,
22199    ) -> Result<Expr, ParseError> {
22200        self.advance(); // ident
22201        self.advance(); // (
22202        // `x op ANY (SELECT …)` — the quantified-subquery
22203        // form. `= ANY` is exactly IN; the other operators
22204        // lower onto EXISTS over the subquery as a derived
22205        // table, comparing against its single projection
22206        // aliased __v (x's columns resolve correlated).
22207        // ALL is the negated-EXISTS complement; a NULL
22208        // element makes PG return NULL where this lowering
22209        // returns true — the NOT NULL column case (the
22210        // practical one) is exact.
22211        if matches!(self.peek(), Token::Select) || self.peek_is_with_kw() {
22212            // v7.39 (round 153) — `ANY (WITH … SELECT …)` is
22213            // legal PG too (round-151 sibling). Out-of-line
22214            // (#[inline(never)] helper) — this sits on
22215            // parse_expr's recursive frame and the two-armed
22216            // SELECT temporary blew the nesting-budget stack.
22217            let mut sub = self.parse_any_all_select_body()?;
22218            if !matches!(self.peek(), Token::RParen) {
22219                return Err(self.err(alloc::format!(
22220                    "expected ')' after ANY/ALL subquery, got {:?}",
22221                    self.peek()
22222                )));
22223            }
22224            self.advance();
22225            if sub.items.len() != 1 {
22226                return Err(self.err(alloc::format!(
22227                    "ANY/ALL subquery must return one column, got {}",
22228                    sub.items.len()
22229                )));
22230            }
22231            if is_any && matches!(op, BinOp::Eq) {
22232                return Ok(Expr::InSubquery {
22233                    expr: Box::new(lhs),
22234                    subquery: Box::new(sub),
22235                    negated: false,
22236                });
22237            }
22238            // The engine's subquery resolvers materialise
22239            // the single-column result into an ARRAY the
22240            // existing AnyAll three-valued eval consumes.
22241            return Ok(Expr::AnyAll {
22242                expr: Box::new(lhs),
22243                op,
22244                array: Box::new(Expr::ScalarSubquery(Box::new(sub))),
22245                is_any,
22246            });
22247        }
22248        let arr = self.parse_expr(0)?;
22249        if !matches!(self.peek(), Token::RParen) {
22250            return Err(self.err(alloc::format!(
22251                "expected ')' after ANY/ALL argument, got {:?}",
22252                self.peek()
22253            )));
22254        }
22255        self.advance();
22256        Ok(Expr::AnyAll {
22257            expr: Box::new(lhs),
22258            op,
22259            array: Box::new(arr),
22260            is_any,
22261        })
22262    }
22263
22264    /// v7.39 (read01 geo_ops.c) — prefix `@@` (center-of). Out-of-line
22265    /// from `parse_unary` (see the frame-budget note at MAX_NEST_DEPTH).
22266    #[inline(never)]
22267    fn parse_prefix_center(&mut self) -> Result<Expr, ParseError> {
22268        self.advance();
22269        let e = self.parse_expr(9)?;
22270        Ok(build_center_call(e))
22271    }
22272
22273    /// v7.39 (round 508) — a prefix operator that IS a function: `@ x` is
22274    /// `abs(x)`, `# p` is `npoints(p)`, `@-@ p` is `length(p)`. Binds like
22275    /// unary minus.
22276    ///
22277    /// `#[inline(never)]` for the same reason as its neighbours: parse_unary
22278    /// sits on the recursive frame chain MAX_NEST_DEPTH is tuned against, so
22279    /// the Expr-sized local stays out of that frame.
22280    #[inline(never)]
22281    fn parse_prefix_call(&mut self, name: &str) -> Result<Expr, ParseError> {
22282        self.advance();
22283        let e = self.parse_expr(9)?;
22284        Ok(Expr::FunctionCall {
22285            name: alloc::string::String::from(name),
22286            args: alloc::vec![e],
22287        })
22288    }
22289
22290    /// v7.39 (read01 geo_ops.c) — prefix `?|` (vertical) / `?-`
22291    /// (horizontal). Out-of-line from `parse_unary` (frame budget).
22292    #[inline(never)]
22293    fn parse_prefix_geom_axis(&mut self, vertical: bool) -> Result<Expr, ParseError> {
22294        self.advance();
22295        let e = self.parse_expr(9)?;
22296        Ok(Expr::FunctionCall {
22297            name: alloc::string::String::from(if vertical {
22298                "isvertical"
22299            } else {
22300                "ishorizontal"
22301            }),
22302            args: alloc::vec![e],
22303        })
22304    }
22305
22306    /// v7.39 (round 355, M13) — `BINARY <expr>`, lowered onto the same
22307    /// cast the `CAST(x AS BINARY)` spelling produces. It binds tightly:
22308    /// MariaDB reads `BINARY 1 + 1` as `(BINARY 1) + 1` = 2.
22309    #[inline(never)]
22310    fn parse_binary_prefix(&mut self) -> Result<Expr, ParseError> {
22311        self.advance();
22312        let e = self.parse_expr(9)?;
22313        Ok(Expr::Cast {
22314            expr: Box::new(e),
22315            target: CastTarget::Named("binary".to_string()),
22316        })
22317    }
22318
22319    /// The prefix operators that share one shape: take the token, parse
22320    /// an operand at `prec`, wrap it.
22321    ///
22322    /// `#[inline(never)]`, and one function instead of five arms, for the
22323    /// reason the neighbouring `parse_prefix_*` helpers give: `parse_unary`
22324    /// sits on the frame chain `MAX_NEST_DEPTH` is tuned against, and a
22325    /// debug build gives EVERY arm's locals a slot in the frame, whichever
22326    /// arm runs. `((((1))))` reaches none of these arms and was carrying
22327    /// five `Expr`-sized locals per level for them anyway.
22328    #[inline(never)]
22329    fn parse_unary_op(&mut self, op: UnOp, prec: u8) -> Result<Expr, ParseError> {
22330        self.advance();
22331        let e = self.parse_expr(prec)?;
22332        Ok(Expr::Unary {
22333            op,
22334            expr: Box::new(e),
22335        })
22336    }
22337
22338    /// Unary minus. Out-of-line for the frame reason on `parse_unary_op`,
22339    /// and separate from it because of the literal folding below and the
22340    /// `format!` temporaries that folding needs.
22341    #[inline(never)]
22342    fn parse_prefix_minus(&mut self) -> Result<Expr, ParseError> {
22343        self.advance();
22344        // v7.39 (round 549) — fold the sign into an integer literal that
22345        // only fits once it is negative.
22346        //
22347        // `9223372036854775808` is one past i64::MAX, so the lexer hands
22348        // it over as a NUMERIC and `-` on a numeric stays numeric. PG
22349        // folds the sign first, so `-9223372036854775808` is a bigint
22350        // there — and `-9223372036854775808 - 1` raises "bigint out of
22351        // range" where SPG quietly answered -9223372036854775809, a value
22352        // no bigint can hold. The arithmetic itself was already checked;
22353        // only the literal's type was wrong.
22354        if let Token::Numeric(lit) = self.peek()
22355            && let Ok(folded) = alloc::format!("-{lit}").parse::<i64>()
22356        {
22357            self.advance();
22358            return Ok(Expr::Literal(Literal::Integer(folded)));
22359        }
22360        // Unary minus binds tighter than `*`/`/` (now at prec 7 after
22361        // `<->` slotted into 5 and arithmetic shifted up).
22362        let e = self.parse_expr(9)?;
22363        Ok(Expr::Unary {
22364            op: UnOp::Neg,
22365            expr: Box::new(e),
22366        })
22367    }
22368
22369    /// tsquery `!!` prefix negation, lowered to the catalog function.
22370    /// Binds like unary minus. Out-of-line for the frame reason on
22371    /// `parse_unary_op`.
22372    #[inline(never)]
22373    fn parse_prefix_tsquery_not(&mut self) -> Result<Expr, ParseError> {
22374        self.advance();
22375        let e = self.parse_expr(9)?;
22376        Ok(Expr::FunctionCall {
22377            name: String::from("tsquery_not"),
22378            args: alloc::vec![e],
22379        })
22380    }
22381
22382    fn parse_unary(&mut self) -> Result<Expr, ParseError> {
22383        match self.peek() {
22384            // NOT binds tighter than AND / XOR / OR but looser than
22385            // comparisons — its operand takes everything ≥ the comparison
22386            // rung (4), leaving AND (3) / XOR (2) / OR (1) outside so
22387            // `NOT a AND b` groups as `(NOT a) AND b`. (v7.39 round 407:
22388            // was rung 3, behaviour-identical when 3 was unused; AND now
22389            // occupies 3, so this must be 4 to keep NOT tighter than AND.)
22390            Token::Not => self.parse_unary_op(UnOp::Not, 4),
22391            // v7.39 (round 355, M13) — MySQL's `BINARY <expr>` prefix.
22392            // The body is out-of-line: `parse_unary` is one of the three
22393            // frames the parser's MAX_NEST_DEPTH is tuned against, and an
22394            // inline arm here overflowed the native stack in
22395            // `nesting_budget_errors_cleanly` — the guard test caught it,
22396            // exactly as the eval-side cliff did in rounds 346 and 351.
22397            Token::Ident(w) if self.mysql_dialect && w.eq_ignore_ascii_case("binary") => {
22398                self.parse_binary_prefix()
22399            }
22400            // v7.39 (round 353, M10) — MySQL's `!`. It binds TIGHTER than
22401            // arithmetic, unlike NOT: MariaDB answers 1 for `!1 + 1`
22402            // (`(!1)+1`) and 0 for `NOT 1 + 1` (`NOT (1+1)`), measured.
22403            Token::Bang => self.parse_unary_op(UnOp::Not, 9),
22404            Token::Minus => self.parse_prefix_minus(),
22405            // v7.39 (round 507) — unary `+`, which SPG did not have. `+1`
22406            // worked only because the lexer reads it as one signed literal;
22407            // `+ 1`, `+a`, `+(1)` and `1 + +1` were syntax errors, and both
22408            // PG18 and MariaDB take all of them. Binds like unary minus.
22409            Token::Plus => self.parse_unary_op(UnOp::Plus, 9),
22410            // Bitwise NOT binds like unary minus.
22411            Token::Tilde => self.parse_unary_op(UnOp::BitNot, 9),
22412            // v7.39 (read01 geo_ops.c) — prefix `@@` is PG's geometric
22413            // "center of" operator; desugars to center(x). The whole arm
22414            // is out-of-line: parse_unary sits on the per-nesting-level
22415            // frame chain that MAX_NEST_DEPTH is tuned against, so no
22416            // Expr-sized local may live in this frame.
22417            Token::TsMatch => self.parse_prefix_center(),
22418            // v7.39 (round 508) — the prefix operators that are named
22419            // functions in disguise: `@ x` is abs, `# p` is npoints, `@-@ p`
22420            // is length. Out-of-line for the same nesting-frame reason as
22421            // parse_prefix_center — parse_unary sits on the recursive cycle
22422            // MAX_NEST_DEPTH is tuned against, so no Expr-sized local may
22423            // live in this frame.
22424            Token::At => self.parse_prefix_call("abs"),
22425            Token::Hash => self.parse_prefix_call("npoints"),
22426            Token::AtMinusAt => self.parse_prefix_call("length"),
22427            // v7.39 (read01 geo_ops.c) — prefix `?|` / `?-`: "is vertical" /
22428            // "is horizontal" (lseg / line); desugars to the existing
22429            // isvertical()/ishorizontal() functions. Out-of-line for the
22430            // same nesting-frame reason as parse_prefix_center.
22431            Token::JsonKeysAny => self.parse_prefix_geom_axis(true),
22432            Token::GeomHoriz => self.parse_prefix_geom_axis(false),
22433            Token::DoubleBang => self.parse_prefix_tsquery_not(),
22434            _ => self.parse_atom(),
22435        }
22436    }
22437
22438    /// Parse a parenthesised scalar subquery body after the caller has consumed
22439    /// `(` and confirmed the next token is SELECT (or WITH, when `is_with`).
22440    /// v7.37 D.43 — `#[inline(never)]` keeps the large `Statement` local and the
22441    /// SELECT/WITH parse machinery off `parse_atom`'s stack frame; parse_atom sits
22442    /// on the recursive `((…))` cycle whose depth budget is tuned to that frame.
22443    /// v7.39 (read01 round 105) — is the current position `( <subquery-start>`,
22444    /// i.e. an `ARRAY(<subquery>)` and not `ARRAY[...]`? A subquery starts with
22445    /// SELECT, VALUES, or WITH (WITH lexes as a bare ident).
22446    /// `#[inline(never)]`: keeps this guard's locals off parse_atom's frame,
22447    /// which sits on the recursive nesting-budget cycle (a few extra bytes there
22448    /// tips the deep-nesting test into a stack overflow).
22449    #[inline(never)]
22450    fn array_subquery_ahead(&self) -> bool {
22451        if !matches!(self.peek(), Token::LParen) {
22452            return false;
22453        }
22454        matches!(
22455            self.tokens.get(self.pos + 1),
22456            Some(Token::Select | Token::Values)
22457        ) || matches!(
22458            self.tokens.get(self.pos + 1),
22459            Some(Token::Ident(w) | Token::QuotedIdent(w)) if w.eq_ignore_ascii_case("with")
22460        )
22461    }
22462
22463    /// v7.10.10 — `ARRAY[expr, …]` literal body. The `array` ident is consumed
22464    /// and the current token is `[`. `#[inline(never)]` so its `Vec`/loop
22465    /// locals stay off parse_atom's recursive frame (round 105).
22466    #[inline(never)]
22467    fn parse_array_literal_body(&mut self) -> Result<Expr, ParseError> {
22468        self.advance(); // consume `[`
22469        let mut items: Vec<Expr> = Vec::new();
22470        if !matches!(self.peek(), Token::RBracket) {
22471            loop {
22472                // Inside `ARRAY[...]`, a nested `[...]` is a sub-array
22473                // (`ARRAY[[1,2],[3,4]]`), not a pgvector literal.
22474                if matches!(self.peek(), Token::LBracket) {
22475                    items.push(self.parse_array_bracket_body()?);
22476                } else {
22477                    items.push(self.parse_expr(0)?);
22478                }
22479                match self.peek() {
22480                    Token::Comma => {
22481                        self.advance();
22482                    }
22483                    Token::RBracket => break,
22484                    other => {
22485                        return Err(self.err(alloc::format!(
22486                            "expected ',' or ']' in ARRAY literal, got {other:?}"
22487                        )));
22488                    }
22489                }
22490            }
22491        }
22492        self.advance(); // consume `]`
22493        Ok(Expr::Array(items))
22494    }
22495
22496    /// v7.39 (read01 round 105) — parse `ARRAY(<subquery>)`. The `array` ident
22497    /// is already consumed; the current token is `(`. Desugars to a scalar
22498    /// subquery `SELECT array_agg(c) FROM (<subquery>) AS t(c)`, which collects
22499    /// the subquery's single-column rows in order — reusing the existing
22500    /// ScalarSubquery machinery rather than adding an AST node. `#[inline(never)]`
22501    /// keeps the large `Statement` local off parse_atom's recursive frame.
22502    #[inline(never)]
22503    fn parse_array_subquery(&mut self) -> Result<Expr, ParseError> {
22504        self.advance(); // consume `(`
22505        let is_with = matches!(self.peek(), Token::Ident(w) | Token::QuotedIdent(w)
22506            if w.eq_ignore_ascii_case("with"));
22507        let sub = if is_with {
22508            self.advance(); // WITH
22509            self.parse_with_cte_then_select()?
22510        } else {
22511            self.parse_select_stmt()?
22512        };
22513        if !matches!(self.peek(), Token::RParen) {
22514            return Err(self.err(alloc::format!(
22515                "expected ')' to close ARRAY(subquery), got {:?}",
22516                self.peek()
22517            )));
22518        }
22519        self.advance(); // consume `)`
22520        // Reuse the parser to build the array_agg wrapper from the subquery's
22521        // canonical text — avoids hand-constructing the derived-table AST.
22522        let wrapper = alloc::format!(
22523            "SELECT array_agg(\"__spg_arr_c\") FROM ({sub}) AS \"__spg_arr_t\"(\"__spg_arr_c\")"
22524        );
22525        let stmt = parse_statement(&wrapper)
22526            .map_err(|e| self.err(alloc::format!("ARRAY(subquery): {}", e.message)))?;
22527        let Statement::Select(sel) = stmt else {
22528            return Err(self.err("ARRAY(subquery) did not desugar to a SELECT".into()));
22529        };
22530        Ok(Expr::ScalarSubquery(alloc::boxed::Box::new(sel)))
22531    }
22532
22533    #[inline(never)]
22534    fn parse_paren_scalar_subquery(&mut self, is_with: bool) -> Result<Expr, ParseError> {
22535        let inner = if is_with {
22536            self.advance(); // WITH
22537            self.parse_with_cte_then_select()?
22538        } else {
22539            self.parse_select_stmt()?
22540        };
22541        match self.advance() {
22542            Token::RParen => {
22543                let Statement::Select(s) = inner else {
22544                    return Err(ParseError {
22545                        message: "scalar subquery body must be a SELECT".into(),
22546                        token_pos: self.consumed_pos(),
22547                    });
22548                };
22549                Ok(Expr::ScalarSubquery(Box::new(s)))
22550            }
22551            other => Err(ParseError {
22552                message: format!("expected ')' after scalar subquery, got {other:?}"),
22553                token_pos: self.consumed_pos(),
22554            }),
22555        }
22556    }
22557
22558    /// `B'1010'` / `X'1F'` bit-string (PG) or binary-string (MySQL)
22559    /// literals. The lexer splits them into an ident + string; recombine
22560    /// here. Out-of-line and returning `Option` so `parse_atom` — the
22561    /// recursive frame the 768 KiB stack budget is tuned against — pays no
22562    /// frame for the `body` / `bits` strings and their char loops (the
22563    /// round-367 frame cliff, M20).
22564    #[inline(never)]
22565    fn try_parse_bit_string_literal(&mut self) -> Option<Result<Expr, ParseError>> {
22566        let is_hex = match self.peek() {
22567            Token::Ident(p) if p.eq_ignore_ascii_case("x") => true,
22568            Token::Ident(p) if p.eq_ignore_ascii_case("b") => false,
22569            _ => return None,
22570        };
22571        if !matches!(self.tokens.get(self.pos + 1), Some(Token::String(_))) {
22572            return None;
22573        }
22574        // v7.39.3 — where the LITERAL starts, because the errors below
22575        // are about the literal and both engines point at it. `err`
22576        // reports the CURRENT token, which by then is the one after the
22577        // string: `SELECT x'123'` pointed at Eof, so the MySQL wire's
22578        // `near '…'` snippet — which runs from the reported position to
22579        // the end — came out empty where MySQL 9.7.2 says `near
22580        // 'x'123''`.
22581        let lit_pos = self.pos;
22582        self.advance();
22583        let Token::String(body) = self.advance() else {
22584            unreachable!("guarded above");
22585        };
22586        // v7.39 (round 367, M20) — in the MySQL dialect `X'…'` and `b'…'`
22587        // are BINARY STRINGS, not PG bit strings. `X'41'` is the byte 0x41
22588        // (hex pairs, even count required — MariaDB errors on an odd
22589        // count); `b'1010'` packs its bits big-endian, left-padded to a
22590        // byte. Lower both onto the bytea cast.
22591        if self.mysql_dialect {
22592            if is_hex {
22593                if body.len() % 2 == 1 {
22594                    return Some(Err(self.err_at(
22595                        lit_pos,
22596                        alloc::format!("invalid hex string literal X'{body}': odd digit count"),
22597                    )));
22598                }
22599                for c in body.chars() {
22600                    if !c.is_ascii_hexdigit() {
22601                        return Some(Err(self.err_at(
22602                            lit_pos,
22603                            alloc::format!("invalid hexadecimal digit {c:?} in X'…'"),
22604                        )));
22605                    }
22606                }
22607                return Some(self.finish_postfix_casts(hex_literal_to_bytea_expr(&body)));
22608            }
22609            if let Some(bad) = body.chars().find(|c| *c != '0' && *c != '1') {
22610                return Some(Err(self.err_at(
22611                    lit_pos,
22612                    alloc::format!("invalid binary digit {bad:?} in b'…'"),
22613                )));
22614            }
22615            return Some(self.finish_postfix_casts(bits_literal_to_bytea_expr(&body)));
22616        }
22617        let bits = if is_hex {
22618            let mut out = String::with_capacity(body.len() * 4);
22619            for c in body.chars() {
22620                let Some(d) = c.to_digit(16) else {
22621                    // v7.39.3 — PostgreSQL 18.6's own sentence, and its
22622                    // own quoting: `"g" is not a valid hexadecimal
22623                    // digit` (measured, with the caret on the literal).
22624                    return Some(Err(self.err_at(
22625                        lit_pos,
22626                        alloc::format!("\"{c}\" is not a valid hexadecimal digit"),
22627                    )));
22628                };
22629                out.push_str(&alloc::format!("{d:04b}"));
22630            }
22631            out
22632        } else {
22633            if let Some(bad) = body.chars().find(|c| *c != '0' && *c != '1') {
22634                return Some(Err(self.err_at(
22635                    lit_pos,
22636                    alloc::format!("\"{bad}\" is not a valid binary digit"),
22637                )));
22638            }
22639            body
22640        };
22641        // Route through the postfix-cast loop so a chained cast like
22642        // `B'1010'::int` attaches onto the implicit `::bit` cast instead
22643        // of erroring at the `::`.
22644        // v7.39 (read01 varbit.c) — a distinct internal target: a B'...'
22645        // literal keeps its exact length, while an explicit `::bit` cast is
22646        // bit(1) with pad/truncate semantics (PG).
22647        Some(self.finish_postfix_casts(Expr::Cast {
22648            expr: Box::new(Expr::Literal(Literal::String(bits))),
22649            target: CastTarget::Named("__bit_literal".to_string()),
22650        }))
22651    }
22652
22653    fn parse_atom(&mut self) -> Result<Expr, ParseError> {
22654        if let Some(res) = self.try_parse_bit_string_literal() {
22655            return res;
22656        }
22657        let tok_pos = self.pos;
22658        match self.advance() {
22659            Token::Integer(n) => Ok(Expr::Literal(Literal::Integer(n))),
22660            Token::Float(x) => Ok(Expr::Literal(Literal::Float(x))),
22661            // v7.38 (read01) — dotted / over-i64 literal → exact NUMERIC (PG),
22662            // carrying the source mantissa + scale so no precision is lost. A
22663            // literal too wide for i128 falls back to double precision.
22664            // Out-of-line (#[inline(never)]) — this arm sits on the
22665            // parse_expr recursion chain; its expansion locals must not
22666            // widen the recursive frame (debug frame-cliff discipline).
22667            Token::Numeric(s) => match numeric_token_to_literal(s) {
22668                Ok(lit) => Ok(Expr::Literal(lit)),
22669                Err(msg) => Err(self.err(msg)),
22670            },
22671            Token::String(s) => Ok(Expr::Literal(Literal::String(s))),
22672            // v7.39 (round 367, M20) — a MySQL `0x…` binary-string literal
22673            // (the lexer only emits this token in the MySQL dialect). Lower
22674            // onto the existing bytea cast; out-of-line to keep this arm off
22675            // the parse recursion frame.
22676            Token::HexBytes(s) => Ok(hex_literal_to_bytea_expr(&s)),
22677            Token::True => Ok(Expr::Literal(Literal::Bool(true))),
22678            Token::False => Ok(Expr::Literal(Literal::Bool(false))),
22679            Token::Null => Ok(Expr::Literal(Literal::Null)),
22680            // v6.1.1 — `$N` placeholder. The actual Value lookup
22681            // happens in the engine eval path against the prepared-
22682            // statement bind buffer.
22683            Token::Placeholder(n) => Ok(Expr::Placeholder(n)),
22684            Token::LParen => {
22685                // v4.10: `(SELECT ...)` in expression position is a
22686                // scalar subquery; otherwise it's a parenthesised
22687                // expression. Peek for SELECT keyword to dispatch.
22688                // v7.37 D.43 — also accept `(WITH [RECURSIVE] … SELECT …)`; WITH
22689                // lexes as Ident("with") (not a reserved token). The subquery body
22690                // is parsed in `parse_paren_scalar_subquery` (marked #[inline(never)]
22691                // so its large `Statement` local stays out of parse_atom's stack
22692                // frame — parse_atom is on the recursive `((…))` cycle and the
22693                // nesting budget is tuned to its frame size).
22694                let is_with = matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
22695                    if s.eq_ignore_ascii_case("with"));
22696                if matches!(self.peek(), Token::Select) || is_with {
22697                    self.parse_paren_scalar_subquery(is_with)
22698                } else {
22699                    let e = self.parse_expr(0)?;
22700                    // `(a, b, …)` — a row constructor. Valid only
22701                    // in front of a comparison operator or [NOT]
22702                    // IN; both expand at parse time (lexicographic
22703                    // comparison / OR'd row equalities).
22704                    if matches!(self.peek(), Token::Comma) {
22705                        let mut row = alloc::vec![e];
22706                        while matches!(self.peek(), Token::Comma) {
22707                            self.advance();
22708                            row.push(self.parse_expr(0)?);
22709                        }
22710                        if !matches!(self.peek(), Token::RParen) {
22711                            return Err(self.err(alloc::format!(
22712                                "expected ')' after row constructor, got {:?}",
22713                                self.peek()
22714                            )));
22715                        }
22716                        self.advance();
22717                        // A bare `(a, b, …)` row constructor can carry postfix
22718                        // (`::text`, `.field`) just like `ROW(a, b, …)`; the
22719                        // early return here skips parse_atom's tail postfix
22720                        // pass, so fold casts in explicitly. For the
22721                        // comparison / predicate forms nothing postfix follows,
22722                        // so this is a no-op.
22723                        return self
22724                            .parse_row_comparison_tail(row)
22725                            .and_then(|e| self.finish_postfix_casts(e));
22726                    }
22727                    match self.advance() {
22728                        Token::RParen => Ok(e),
22729                        other => Err(ParseError {
22730                            message: format!("expected ')', got {other:?}"),
22731                            token_pos: self.consumed_pos(),
22732                        }),
22733                    }
22734                }
22735            }
22736            Token::LBracket => self.parse_vector_literal_body(),
22737            Token::Extract => self.parse_extract_atom(),
22738            Token::Interval => self.parse_interval_atom(),
22739            // `LEFT` / `RIGHT` are reserved-keyword tokens because the
22740            // grammar dedicates arms for `LEFT [OUTER] JOIN` /
22741            // `RIGHT [OUTER] JOIN`. When followed by `(` we're in
22742            // expression position calling the PG `left(string, n)` /
22743            // `right(string, n)` function; rebuild the AST as a regular
22744            // function call so the engine's apply_function dispatch picks
22745            // it up. Delegated to a #[inline(never)] helper so its locals
22746            // don't bloat this recursive `parse_atom` frame (the nesting
22747            // budget in `enter_nested` is tuned to parse_atom's size).
22748            Token::Left if matches!(self.peek(), Token::LParen) => {
22749                self.parse_lr_string_function_call("left")
22750            }
22751            Token::Right if matches!(self.peek(), Token::LParen) => {
22752                self.parse_lr_string_function_call("right")
22753            }
22754            // v4.10: EXISTS / NOT EXISTS. EXISTS isn't a reserved
22755            // token; we match on the bare ident. NOT is a token
22756            // (consumed in the comparison rung), but `EXISTS (...)`
22757            // at the top of an expression starts here.
22758            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("exists") => {
22759                self.parse_exists_atom(false)
22760            }
22761            // v7.13.0 — `CASE [<operand>] WHEN <cond> THEN <val>
22762            // [WHEN ...] [ELSE <val>] END` (mailrs round-5 G9).
22763            // CASE is a bare ident; we dispatch on lowercase match.
22764            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("case") => {
22765                self.parse_case_atom()
22766            }
22767            // v7.37.17 (17.6 siblings) — PG typed datetime literals:
22768            // `DATE '2003-01-02'` / `TIMESTAMP '…'` / `TIMESTAMPTZ
22769            // '…'`. Lower onto the ::cast node so the existing
22770            // runtime text→date/timestamp paths do the parsing. The
22771            // string must follow immediately, else the ident stays a
22772            // plain column reference.
22773            Token::Ident(s)
22774                if typed_literal_cast_target(&s.to_ascii_lowercase()).is_some()
22775                    && matches!(self.peek(), Token::String(_)) =>
22776            {
22777                let target =
22778                    typed_literal_cast_target(&s.to_ascii_lowercase()).expect("guard checked");
22779                let Token::String(lit) = self.advance() else {
22780                    unreachable!("peek guaranteed a string token");
22781                };
22782                Ok(Expr::Cast {
22783                    expr: Box::new(Expr::Literal(Literal::String(lit))),
22784                    target,
22785                })
22786            }
22787            // v7.39 (round 221) — the SQL-standard long spellings:
22788            // `TIME [WITHOUT|WITH] TIME ZONE '…'` / `TIMESTAMP [WITHOUT|WITH]
22789            // TIME ZONE '…'`. Consume the modifier and lower to the same
22790            // typed-literal cast (`timetz` / `timestamptz` for WITH).
22791            Token::Ident(s)
22792                if (s.eq_ignore_ascii_case("time") || s.eq_ignore_ascii_case("timestamp"))
22793                    && matches!(self.peek(), Token::Ident(w) if w.eq_ignore_ascii_case("with")
22794                        || w.eq_ignore_ascii_case("without"))
22795                    && matches!(self.tokens.get(self.pos + 1), Some(Token::Ident(t)) if t.eq_ignore_ascii_case("time"))
22796                    && matches!(self.tokens.get(self.pos + 2), Some(Token::Ident(z)) if z.eq_ignore_ascii_case("zone"))
22797                    && matches!(self.tokens.get(self.pos + 3), Some(Token::String(_))) =>
22798            {
22799                let with_tz = matches!(self.peek(), Token::Ident(w) if w.eq_ignore_ascii_case("with"));
22800                self.advance(); // WITH / WITHOUT
22801                self.advance(); // TIME
22802                self.advance(); // ZONE
22803                let Token::String(lit) = self.advance() else {
22804                    unreachable!("guard checked a string token");
22805                };
22806                let base = s.to_ascii_lowercase();
22807                let target = match (base.as_str(), with_tz) {
22808                    ("time", true) => CastTarget::Named(alloc::string::String::from("timetz")),
22809                    ("time", false) => CastTarget::Named(alloc::string::String::from("time")),
22810                    (_, true) => CastTarget::Timestamptz,
22811                    (_, false) => CastTarget::Timestamp,
22812                };
22813                Ok(Expr::Cast {
22814                    expr: Box::new(Expr::Literal(Literal::String(lit))),
22815                    target,
22816                })
22817            }
22818            // v7.39 (read01 round 105) — `ARRAY(<subquery>)` constructor:
22819            // gathers the subquery's single-column rows (in its row order)
22820            // into an array. Desugared to `array_agg` over the subquery as a
22821            // derived table; out-of-line to keep parse_atom's frame small (it
22822            // sits on the recursive nesting-budget cycle).
22823            Token::Ident(s) | Token::QuotedIdent(s)
22824                if s.eq_ignore_ascii_case("array") && self.array_subquery_ahead() =>
22825            {
22826                self.parse_array_subquery()
22827            }
22828            // v7.10.10 — `ARRAY[expr, expr, …]` constructor. ARRAY
22829            // is not a reserved token; we match by case-insensitive
22830            // ident. The opening `[` must follow immediately. v7.39 (read01
22831            // round 105) — the body moved out-of-line so its `Vec`/loop locals
22832            // leave parse_atom's frame (which sits on the nesting-budget cycle).
22833            Token::Ident(s) | Token::QuotedIdent(s)
22834                if s.eq_ignore_ascii_case("array") && matches!(self.peek(), Token::LBracket) =>
22835            {
22836                self.parse_array_literal_body()
22837            }
22838            // v7.17.0 Phase 2.2 — MySQL `MATCH(col, ...) AGAINST
22839            // ('term' [IN BOOLEAN MODE | IN NATURAL LANGUAGE MODE])`.
22840            // We special-case before the generic ident dispatch so
22841            // the AGAINST clause never reaches the function-call
22842            // loop (which would mis-read `(cols) AGAINST` as a
22843            // call with no trailing modifier). The shape is
22844            // rewritten to a Boolean OR over per-column
22845            // `to_tsvector('simple', col) @@ plainto_tsquery('simple',
22846            // term)` so the existing FTS evaluator handles
22847            // semantics — the fulltext-GIN built at CREATE TABLE
22848            // time is currently a "real index that survives dump
22849            // round-trip"; the planner hook that actually uses
22850            // it for posting-list intersection lands in a later
22851            // sub-phase (Phase 2.2b) without touching this surface.
22852            Token::Ident(s) | Token::QuotedIdent(s)
22853                if s.eq_ignore_ascii_case("match") && matches!(self.peek(), Token::LParen) =>
22854            {
22855                self.parse_match_against_atom()
22856            }
22857            Token::Ident(s) | Token::QuotedIdent(s) => self.finish_ident_atom(s),
22858            // v7.37.43-T4 — PG-unreserved keywords are legal column /
22859            // alias names in expression context too. `release` appears
22860            // in sentori `0003_partition_events.sql` as both a column
22861            // reference (SELECT … release …) and an INSERT column list
22862            // entry. Mirrors `expect_ident_like`'s expansion of the
22863            // identifier set.
22864            other if unreserved_keyword_text(&other).is_some() => {
22865                let s = unreserved_keyword_text(&other).unwrap();
22866                self.finish_ident_atom(s)
22867            }
22868            // v7.39 (round 331, V50) — `@@var` in an EXPRESSION. It parsed
22869            // only inside `SET` before, so `SELECT @@autocommit` — which
22870            // every MySQL connector asks at handshake — was a parse error.
22871            // MariaDB accepts the bare, `@@session.` and `@@global.`
22872            // spellings alike and answers from the session's own value.
22873            Token::SessionVar(v) => {
22874                // v7.39 (round 430) — ONE `@` is a MySQL USER variable, which
22875                // has nothing to do with a `@@` engine setting: its own
22876                // per-session namespace, and an unset one reads NULL instead
22877                // of raising. Stripping every `@` (as this did) made `@x` and
22878                // `@@x` the same node, so `SELECT @x` answered "Unknown
22879                // system variable".
22880                Ok(variable_ref_atom(&v))
22881            }
22882            other => Err(ParseError {
22883                message: format!("unexpected token {other:?} in expression"),
22884                token_pos: tok_pos,
22885            }),
22886        }
22887        // After parsing the atom, fold any postfix `::vector` casts.
22888        .and_then(|atom| self.finish_postfix_casts(atom))
22889    }
22890
22891    /// Postfix operators on an atom: `::TYPE` cast and `IS [NOT] NULL`.
22892    /// Both bind tighter than any binary op.
22893    /// Shared cast-target parser for postfix `::TYPE` and the
22894    /// standard `CAST(expr AS TYPE)` form (v7.25, round-17).
22895    /// If the next tokens are `( N )`, consume them and return the canonical
22896    /// `base(N)` name so a temporal cast (`::timestamp(2)`) carries its
22897    /// fractional-seconds precision into `CastTarget::Named`; otherwise `None`.
22898    fn consume_temporal_typmod(&mut self, base: &str) -> Option<alloc::string::String> {
22899        if !matches!(self.peek(), Token::LParen) {
22900            return None;
22901        }
22902        self.advance(); // (
22903        let n = match self.advance() {
22904            Token::Integer(n) => n,
22905            _ => return Some(base.to_string()), // malformed → drop precision
22906        };
22907        if matches!(self.peek(), Token::RParen) {
22908            self.advance();
22909        }
22910        Some(alloc::format!("{base}({n})"))
22911    }
22912
22913    fn parse_cast_target(&mut self) -> Result<CastTarget, ParseError> {
22914        // r1052 — `::pg_catalog.regproc` and friends: pg_dump
22915        // schema-qualifies every cast target, and `pg_catalog.X` names
22916        // exactly the builtin type X. Consume the qualifier and let
22917        // the ordinary target parse decide.
22918        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("pg_catalog"))
22919            && matches!(self.tokens.get(self.pos + 1), Some(Token::Dot))
22920        {
22921            self.advance();
22922            self.advance();
22923        }
22924        let target = match self.advance() {
22925            Token::Ident(s) => match s.to_ascii_lowercase().as_str() {
22926                "int" | "integer" | "int4" => {
22927                    if matches!(self.peek(), Token::LBracket)
22928                        && matches!(self.tokens.get(self.pos + 1), Some(Token::RBracket))
22929                    {
22930                        self.advance();
22931                        self.advance();
22932                        CastTarget::IntArray
22933                    } else {
22934                        CastTarget::Int
22935                    }
22936                }
22937                "bigint" | "int8" => {
22938                    if matches!(self.peek(), Token::LBracket)
22939                        && matches!(self.tokens.get(self.pos + 1), Some(Token::RBracket))
22940                    {
22941                        self.advance();
22942                        self.advance();
22943                        CastTarget::BigIntArray
22944                    } else {
22945                        CastTarget::BigInt
22946                    }
22947                }
22948                "float" | "double" => CastTarget::Float,
22949                "text" => {
22950                    // v7.10.11 — `::TEXT[]` widens to TextArray.
22951                    if matches!(self.peek(), Token::LBracket)
22952                        && matches!(self.tokens.get(self.pos + 1), Some(Token::RBracket))
22953                    {
22954                        self.advance();
22955                        self.advance();
22956                        CastTarget::TextArray
22957                    } else {
22958                        CastTarget::Text
22959                    }
22960                }
22961                "bool" | "boolean" => CastTarget::Bool,
22962                "vector" => CastTarget::Vector,
22963                "date" => CastTarget::Date,
22964                // v7.38 (read01) — `::timestamp(N)` carries its fractional-
22965                // seconds precision through the Named path (the engine rounds
22966                // the sub-second field); bare `::timestamp` keeps the fast arm.
22967                "timestamp" | "datetime" => match self.consume_temporal_typmod("timestamp") {
22968                    Some(named) => CastTarget::Named(named),
22969                    None => CastTarget::Timestamp,
22970                },
22971                "timestamptz" => match self.consume_temporal_typmod("timestamptz") {
22972                    Some(named) => CastTarget::Named(named),
22973                    None => CastTarget::Timestamptz,
22974                },
22975                "interval" => CastTarget::Interval,
22976                "json" => CastTarget::Json,
22977                "jsonb" => CastTarget::Jsonb,
22978                // v7.39 (round 694) — these have dedicated CastTarget
22979                // variants, so they never reached the postfix `[]` handling
22980                // further down and `::regtype[]` was a SYNTAX error at the
22981                // `]`. PG has an array type for every scalar; take the
22982                // suffix here and hand the canonical `<ty>_array` name to
22983                // the engine, the same shape every other array cast uses.
22984                "regtype" if self.peek_postfix_array_brackets() => {
22985                    self.advance();
22986                    self.advance();
22987                    CastTarget::Named(alloc::string::String::from("regtype_array"))
22988                }
22989                "regclass" if self.peek_postfix_array_brackets() => {
22990                    self.advance();
22991                    self.advance();
22992                    CastTarget::Named(alloc::string::String::from("regclass_array"))
22993                }
22994                "regtype" => CastTarget::RegType,
22995                "regclass" => CastTarget::RegClass,
22996                // v7.12.0 — `::tsvector` / `::tsquery`.
22997                // Engine decodes the LHS text via the PG
22998                // external form parser.
22999                // v7.39 (round 352, M8) — MySQL's own cast targets.
23000                // `CAST(x AS SIGNED)` / `UNSIGNED`, with the optional
23001                // `INTEGER` / `INT` tail MariaDB also accepts. PG has no
23002                // such type, so they are taken only in that dialect and
23003                // fall through to the "type does not exist" arm otherwise.
23004                "signed" | "unsigned" if self.mysql_dialect => {
23005                    if matches!(self.peek(), Token::Ident(k)
23006                        if k.eq_ignore_ascii_case("integer") || k.eq_ignore_ascii_case("int"))
23007                    {
23008                        self.advance();
23009                    }
23010                    CastTarget::Named(s.to_ascii_lowercase())
23011                }
23012                // v7.39 (round 352, M8) — `CAST(x AS CHAR)` is UNBOUNDED
23013                // in MySQL: MariaDB answers '123' where the SQL-standard
23014                // reading (PG's, and SPG's) is `char(1)` and answers '1'.
23015                // Truncating a number to its first digit is a wrong answer
23016                // with no error, so the MySQL session gets MySQL's reading.
23017                "char" if self.mysql_dialect && !matches!(self.peek(), Token::LParen) => {
23018                    CastTarget::Text
23019                }
23020                "tsvector" => CastTarget::TsVector,
23021                "tsquery" => CastTarget::TsQuery,
23022                // v7.17.0 — `::uuid`. Engine decodes the LHS
23023                // text via `spg_storage::parse_uuid_str`.
23024                "uuid" => CastTarget::Uuid,
23025                // v7.18 — `::bytea`. Engine decodes the LHS
23026                // text via the PG hex form (`'\xdeadbeef'`)
23027                // or escape form (`'\\x05\\x00'`). Closes
23028                // mailrs D-pre #3 reverse-acceptance gap.
23029                "bytea" => CastTarget::Bytea,
23030                // v7.37.5 ship triage — generic typed-cast escape.
23031                // Anything the long-tail PG type ident table knows
23032                // about(network/bit/geometry/multirange/etc.)flows
23033                // through `CastTarget::Named(canonical)`; the engine
23034                // resolves via `column_type_to_data_type` and dispatches
23035                // through the typed `coerce_value` path. Truly
23036                // unrecognised idents still hit the error arm below
23037                // because the engine rejects them.
23038                other => {
23039                    // Optional `(N[, M])` precision args — `::numeric(10,2)`,
23040                    // `::varchar(255)`, etc. Capture into the canonical
23041                    // `name(p,s)` form so `type_name_to_data_type` can
23042                    // reconstruct the `DataType::Numeric { precision,
23043                    // scale }` (and similar param-carrying types).
23044                    let mut name = other.to_string();
23045                    // v7.39 (round 281) — `::bit varying(3)` is two
23046                    // words; fold the tail in so the typmod reaches the
23047                    // type resolver instead of tripping the parser.
23048                    if name.eq_ignore_ascii_case("bit")
23049                        && matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("varying"))
23050                    {
23051                        self.advance();
23052                        name = alloc::string::String::from("varbit");
23053                    }
23054                    // v7.39 (round 613) — `::character varying` is the same
23055                    // two-word shape and had no fold, so the `varying` was
23056                    // left behind and the cast became a bare `character`,
23057                    // which is `char(1)`: `'ab'::CHARACTER VARYING` answered
23058                    // `a` where PG answers `ab`. Silently, and for a spelling
23059                    // pg_dump writes.
23060                    if name.eq_ignore_ascii_case("character")
23061                        && matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("varying"))
23062                    {
23063                        self.advance();
23064                        name = alloc::string::String::from("varchar");
23065                    }
23066                    if matches!(self.peek(), Token::LParen) {
23067                        let mut buf = alloc::string::String::from("(");
23068                        let mut depth = 0usize;
23069                        loop {
23070                            match self.advance() {
23071                                Token::LParen => {
23072                                    depth += 1;
23073                                    if depth > 1 {
23074                                        buf.push('(');
23075                                    }
23076                                }
23077                                Token::RParen => {
23078                                    depth -= 1;
23079                                    if depth == 0 {
23080                                        buf.push(')');
23081                                        break;
23082                                    }
23083                                    buf.push(')');
23084                                }
23085                                Token::Comma => buf.push(','),
23086                                Token::Integer(n) => buf.push_str(&alloc::format!("{n}")),
23087                                // v7.39 (round 273) — a minus used to fall
23088                                // into the catch-all below and vanish, so
23089                                // `::numeric(10,-2)` reached the engine as
23090                                // the text `numeric(10,2)` and silently
23091                                // rounded to two DECIMALS instead of to
23092                                // hundreds. A dropped token is not a
23093                                // no-op when it carries a sign.
23094                                Token::Minus => buf.push('-'),
23095                                Token::Eof => break,
23096                                _ => {}
23097                            }
23098                        }
23099                        name.push_str(&buf);
23100                    }
23101                    // Optional postfix `[]` widens to the array form —
23102                    // `::BOOL[]`, `::NUMERIC[]`, `::SMALLINT[]`, etc.
23103                    // The engine's `type_name_to_data_type` recognises
23104                    // the canonical `<ty>_array` form.
23105                    if matches!(self.peek(), Token::LBracket)
23106                        && matches!(self.tokens.get(self.pos + 1), Some(Token::RBracket))
23107                    {
23108                        self.advance();
23109                        self.advance();
23110                        name.push_str("_array");
23111                    }
23112                    CastTarget::Named(name)
23113                }
23114            },
23115            Token::Interval => CastTarget::Interval,
23116            // v7.39 — a quoted type name: `::"char"` is PG's 1-byte
23117            // "char" (oid 18, SPG Char1 — distinct from bare `char`
23118            // = char(1)); other quoted names resolve like idents.
23119            Token::QuotedIdent(q) => {
23120                if q.eq_ignore_ascii_case("char") {
23121                    CastTarget::Named("char1".into())
23122                } else {
23123                    CastTarget::Named(q.to_ascii_lowercase())
23124                }
23125            }
23126            other => {
23127                return Err(ParseError {
23128                    message: format!("expected type ident after `::`, got {other:?}"),
23129                    token_pos: self.consumed_pos(),
23130                });
23131            }
23132        };
23133        // v7.37.5 ship triage — postfix `[]` widens a scalar cast
23134        // target to its array sibling. Closed-enum arms (Bool /
23135        // SmallInt / Numeric / Float / Date / …) didn't carry the
23136        // explicit widening that Text / Int / BigInt did, so
23137        // `::BOOL[]` / `::NUMERIC[]` etc. surfaced as a parse
23138        // error. The widening here mirrors the per-arm Text /
23139        // Int / BigInt logic above + folds the new ζ-A first-class
23140        // types through `CastTarget::Named("<ty>_array")`.
23141        if matches!(self.peek(), Token::LBracket)
23142            && matches!(self.tokens.get(self.pos + 1), Some(Token::RBracket))
23143        {
23144            let widened = match &target {
23145                CastTarget::Bool => Some(CastTarget::Named("bool_array".to_string())),
23146                CastTarget::Date => Some(CastTarget::Named("date_array".to_string())),
23147                // v7.39 (round 326, V43) — the two temporal types stay
23148                // distinct. Both used to widen to `timestamptz_array`, so
23149                // `::timestamp[]` named the wrong target in its own error
23150                // message and lost the zone-less identity on the way.
23151                CastTarget::Timestamp => Some(CastTarget::Named("timestamp_array".to_string())),
23152                CastTarget::Timestamptz => Some(CastTarget::Named("timestamptz_array".to_string())),
23153                CastTarget::Uuid => Some(CastTarget::Named("uuid_array".to_string())),
23154                CastTarget::Json | CastTarget::Jsonb => {
23155                    Some(CastTarget::Named("jsonb_array".to_string()))
23156                }
23157                CastTarget::Bytea => Some(CastTarget::Named("bytea_array".to_string())),
23158                CastTarget::Interval => Some(CastTarget::Named("interval_array".to_string())),
23159                CastTarget::Float => Some(CastTarget::Named("float_array".to_string())),
23160                CastTarget::Named(name) => {
23161                    let mut a = name.clone();
23162                    a.push_str("_array");
23163                    Some(CastTarget::Named(a))
23164                }
23165                // Int / BigInt / Text / Vector / TsVector / TsQuery /
23166                // RegType / RegClass / TextArray / IntArray /
23167                // BigIntArray already finalised — leave as is.
23168                _ => None,
23169            };
23170            if let Some(w) = widened {
23171                self.advance();
23172                self.advance();
23173                return Ok(w);
23174            }
23175        }
23176        Ok(target)
23177    }
23178
23179    fn finish_postfix_casts(&mut self, mut expr: Expr) -> Result<Expr, ParseError> {
23180        loop {
23181            // v7.38 (read01, T9) — composite field access `(expr).field`.
23182            // A bare `a.b` is consumed as a qualified column inside the ident
23183            // atom, so a Dot only survives to this postfix position when the
23184            // base was a parenthesised expression (`(e).id`, `(row(1,2)).f1`).
23185            // `.*` whole-row expansion is not handled here (projection-level).
23186            if matches!(self.peek(), Token::Dot)
23187                && matches!(
23188                    self.tokens.get(self.pos + 1),
23189                    Some(Token::Ident(_) | Token::QuotedIdent(_))
23190                )
23191            {
23192                self.advance(); // .
23193                let field = match self.advance() {
23194                    Token::Ident(s) | Token::QuotedIdent(s) => s,
23195                    other => {
23196                        return Err(
23197                            self.err(format!("expected a field name after '.', got {other:?}"))
23198                        );
23199                    }
23200                };
23201                expr = Expr::FieldAccess {
23202                    base: Box::new(expr),
23203                    field,
23204                };
23205                continue;
23206            }
23207            if matches!(self.peek(), Token::DoubleColon) {
23208                self.advance();
23209                // v7.9.25 / v7.9.26 — broaden the postfix `::` cast
23210                // target set to include INTERVAL (reserved Token),
23211                // TIMESTAMPTZ, and PG catalog regtype / regclass.
23212                // mailrs follow-up H3a + H3b.
23213                let target = self.parse_cast_target()?;
23214                expr = Expr::Cast {
23215                    expr: Box::new(expr),
23216                    target,
23217                };
23218                continue;
23219            }
23220            // v7.10.12 — `arr[i]` subscript. PG 1-based; engine
23221            // returns NULL for out-of-range. Multiple subscripts
23222            // chain: `a[i][j]` parses left-to-right.
23223            if matches!(self.peek(), Token::LBracket) {
23224                self.advance();
23225                // `[lo:hi]` / `[:hi]` / `[lo:]` — array slice. A
23226                // bare index stays a subscript.
23227                let lo = if matches!(self.peek(), Token::Colon) {
23228                    None
23229                } else {
23230                    Some(self.parse_expr(0)?)
23231                };
23232                if matches!(self.peek(), Token::Colon) {
23233                    self.advance();
23234                    let hi = if matches!(self.peek(), Token::RBracket) {
23235                        None
23236                    } else {
23237                        Some(Box::new(self.parse_expr(0)?))
23238                    };
23239                    if !matches!(self.peek(), Token::RBracket) {
23240                        return Err(self.err(alloc::format!(
23241                            "expected ']' after array slice, got {:?}",
23242                            self.peek()
23243                        )));
23244                    }
23245                    self.advance();
23246                    expr = Expr::ArraySlice {
23247                        target: Box::new(expr),
23248                        lo: lo.map(Box::new),
23249                        hi,
23250                    };
23251                    continue;
23252                }
23253                let index = lo.expect("non-colon branch parsed an index");
23254                if !matches!(self.peek(), Token::RBracket) {
23255                    return Err(self.err(alloc::format!(
23256                        "expected ']' after array index, got {:?}",
23257                        self.peek()
23258                    )));
23259                }
23260                self.advance();
23261                expr = Expr::ArraySubscript {
23262                    target: Box::new(expr),
23263                    index: Box::new(index),
23264                };
23265                continue;
23266            }
23267            // `expr AT TIME ZONE zone` — lowers to PG's own function
23268            // form timezone(zone, expr); the scalar implements the
23269            // offset shift (named zones error there — no tzdata).
23270            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("at"))
23271                && matches!(self.tokens.get(self.pos + 1),
23272                    Some(Token::Ident(s)) if s.eq_ignore_ascii_case("time"))
23273                && matches!(self.tokens.get(self.pos + 2),
23274                    Some(Token::Ident(s)) if s.eq_ignore_ascii_case("zone"))
23275            {
23276                self.advance(); // AT
23277                self.advance(); // TIME
23278                self.advance(); // ZONE
23279                // Zone at comparison precedence so AND/OR stay out.
23280                let zone = self.parse_expr(6)?;
23281                expr = Expr::FunctionCall {
23282                    name: "timezone".to_string(),
23283                    args: alloc::vec![zone, expr],
23284                };
23285                continue;
23286            }
23287            // `expr COLLATE "name"` — SPG's single text ordering IS
23288            // byte order, i.e. the C collation. The byte-order
23289            // spellings absorb as no-ops; a locale collation would
23290            // silently sort differently from PG, so it errors
23291            // honestly instead.
23292            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("collate")) {
23293                self.advance();
23294                let mut cname = match self.advance() {
23295                    Token::Ident(s) | Token::QuotedIdent(s) | Token::String(s) => s,
23296                    other => {
23297                        return Err(self.err(alloc::format!(
23298                            "expected collation name after COLLATE, got {other:?}"
23299                        )));
23300                    }
23301                };
23302                // v7.39 (round 539) — a SCHEMA-QUALIFIED collation, which
23303                // is how `pg_dump` writes the default one:
23304                // `… COLLATE pg_catalog.default`. Reading a single token
23305                // left the SCHEMA as the name, so the clause was refused
23306                // as an unsupported locale collation and no dump ran.
23307                if matches!(self.peek(), Token::Dot) {
23308                    // v7.39.2 — the qualifier is DROPPED (SPG is single
23309                    // schema) but it is checked first. PostgreSQL 18.6
23310                    // answers `schema "nosuch_schema" does not exist` for
23311                    // one it has never heard of, and dropping it unread
23312                    // meant `COLLATE nosuch_schema."C"` succeeded here —
23313                    // a name that names nothing, accepted.
23314                    let schema = cname.to_ascii_lowercase();
23315                    if !matches!(
23316                        schema.as_str(),
23317                        "pg_catalog" | "public" | "information_schema"
23318                    ) {
23319                        return Err(self.err(alloc::format!("schema \"{cname}\" does not exist")));
23320                    }
23321                    self.advance();
23322                    cname = match self.advance() {
23323                        Token::Ident(s) | Token::QuotedIdent(s) | Token::String(s) => s,
23324                        // `default` lexes as a KEYWORD, and it is the name
23325                        // pg_dump writes — the same trap round 535 hit with
23326                        // TABLE / INDEX / FULL.
23327                        Token::Default => alloc::string::String::from("default"),
23328                        other => {
23329                            return Err(self.err(alloc::format!(
23330                                "expected collation name after COLLATE, got {other:?}"
23331                            )));
23332                        }
23333                    };
23334                }
23335                let lc = cname.to_ascii_lowercase();
23336                // v7.39 (round 371, M4 P4b) — a per-expression MySQL
23337                // collation override. `… COLLATE utf8mb4_bin` (any `_bin`
23338                // family / `binary`) forces byte-wise, which is exactly
23339                // what `BINARY expr` does — lower onto that so every fold
23340                // site (comparison, LIKE, ORDER BY) suppresses via
23341                // `is_binary_coerced`. A `_ci` family override folds, and
23342                // under the MySQL dialect the default already folds, so it
23343                // absorbs as a no-op; likewise the C / byte-order spellings.
23344                // v7.39.2 — against MySQL's own list, not against the
23345                // shape of the name. `nosuch_bin` took this shortcut and
23346                // became a BINARY cast; `nosuch_ci` took the one below
23347                // and was absorbed as a no-op. Either way the client
23348                // named a collation that does not exist and was told
23349                // nothing. An unknown name now falls through to the
23350                // node, and the engine refuses it.
23351                let real = crate::charset::is_mysql_collation(&lc);
23352                if self.mysql_dialect && real && (lc.ends_with("_bin") || lc == "binary") {
23353                    expr = Expr::Cast {
23354                        expr: alloc::boxed::Box::new(expr),
23355                        target: CastTarget::Named("binary".to_string()),
23356                    };
23357                    continue;
23358                }
23359                let mysql_ci = self.mysql_dialect
23360                    && ((real && lc.ends_with("_ci"))
23361                        || matches!(lc.as_str(), "case_insensitive" | "nocase"));
23362                // v7.39 (round 691/692) — inside an ORDER BY key EVERY name
23363                // goes to the lowering channel, the byte-order spellings
23364                // included. Round 691 recorded only the names the old
23365                // allow-list rejected, which left `ORDER BY a COLLATE "C"`
23366                // absorbed as a no-op — and once a column could declare a
23367                // collation, absorbing the clause meant the COLUMN's
23368                // collation won where the query had asked for bytes.
23369                if self.in_order_by_key && !mysql_ci {
23370                    self.order_key_collation = Some(cname);
23371                    continue;
23372                }
23373                // v7.39.2 — the clause becomes a NODE rather than being
23374                // refused or absorbed.
23375                //
23376                // What stood here refused the locale names and SILENTLY
23377                // DROPPED the byte-order ones, so `'a' COLLATE "C" < 'B'`
23378                // answered `t` where PostgreSQL 18.6 answers `f`: the one
23379                // family it let through is the one where dropping it
23380                // changes the answer. Absorbing is only correct when the
23381                // collation asked for is the one the comparison would use
23382                // anyway, and that depends on the DATABASE — which the
23383                // parser cannot see. So it rides along and the engine,
23384                // which can, decides.
23385                //
23386                // `collate_derive` already modelled `Explicit(name)` and
23387                // had no way to be handed one.
23388                // v7.39.2 — a MySQL spelling does not exist on the
23389                // PostgreSQL wire, and THIS is where the wire is known.
23390                //
23391                // The check lived in the evaluator first and asked
23392                // `ctx.mysql_dialect`, which the INSERT path builds as a
23393                // hard-coded `false` — so `INSERT … VALUES (_utf8mb4'x')`
23394                // in a MySQL session was refused for a collation that
23395                // does not exist on a wire it was not on. Making that
23396                // context truthful would change INSERT-time evaluation
23397                // in other ways as a side effect; the parser already
23398                // gates the introducer on the same flag and is the
23399                // honest place to ask.
23400                if !self.mysql_dialect
23401                    && (lc.ends_with("_ci")
23402                        || lc.ends_with("_cs")
23403                        || lc.ends_with("_bin")
23404                        || lc == "binary"
23405                        || matches!(lc.as_str(), "case_insensitive" | "nocase"))
23406                {
23407                    return Err(self.err(alloc::format!(
23408                        "collation \"{cname}\" for encoding \"UTF8\" does not exist"
23409                    )));
23410                }
23411                // v7.39.3 — the node is built for EVERY name, `_ci`
23412                // included.
23413                //
23414                // A MySQL `_ci` spelling used to be absorbed here on the
23415                // reasoning that a MySQL session folds anyway, so the
23416                // clause asked for what it would have got. That stopped
23417                // being true when the fold learned to read the session's
23418                // collation NAME: under `SET NAMES utf8mb4 COLLATE
23419                // utf8mb4_bin`, `'AB' COLLATE utf8mb4_general_ci = 'ab'`
23420                // is 1 on MySQL 9.7.2 and was 0 here, because the clause
23421                // that would have made it 1 had been dropped in the
23422                // parser. Absorbing is only ever correct when the
23423                // collation asked for is the one the comparison would use
23424                // anyway, and the parser cannot know that — the same
23425                // reasoning already written above for the byte-order
23426                // spellings, applied to the family it had exempted.
23427                expr = Expr::Collate {
23428                    expr: alloc::boxed::Box::new(expr),
23429                    collation: cname,
23430                };
23431                continue;
23432            }
23433            return Ok(expr);
23434        }
23435    }
23436
23437    /// v7.39 (round 696) — a comma-separated list of bare names, stopping at
23438    /// the first token that is not one. Schema qualifiers collapse to the
23439    /// last part, which is what every other name path here does (SPG is
23440    /// single-schema).
23441    fn take_comma_separated_names(&mut self) -> Vec<String> {
23442        let mut out = Vec::new();
23443        while let Token::Ident(n) | Token::QuotedIdent(n) = self.peek().clone() {
23444            self.advance();
23445            let mut last = n;
23446            while matches!(self.peek(), Token::Dot) {
23447                self.advance();
23448                if let Token::Ident(t) | Token::QuotedIdent(t) = self.advance() {
23449                    last = t;
23450                }
23451            }
23452            out.push(last);
23453            if matches!(self.peek(), Token::Comma) {
23454                self.advance();
23455            } else {
23456                break;
23457            }
23458        }
23459        out
23460    }
23461
23462    /// v7.39 (round 694) — is the next token pair a postfix `[]`?
23463    ///
23464    /// The general cast-target path tests this inline; the types with their
23465    /// own `CastTarget` variant need it as a guard on their match arm,
23466    /// which is what this exists for.
23467    fn peek_postfix_array_brackets(&self) -> bool {
23468        matches!(self.peek(), Token::LBracket)
23469            && matches!(self.tokens.get(self.pos + 1), Some(Token::RBracket))
23470    }
23471
23472    /// Parse the operator tail after a `(a, b, …)` row constructor
23473    /// and expand at parse time. `=` is the conjunction of element
23474    /// equalities; `<>` its negation; the order operators expand
23475    /// lexicographically; `[NOT] IN ( (row), … )` ORs the row
23476    /// equalities. Anything else (a bare row value, a subquery
23477    /// RHS) errors honestly — SPG has no composite runtime value.
23478    fn parse_row_comparison_tail(&mut self, row: Vec<Expr>) -> Result<Expr, ParseError> {
23479        fn row_eq(lhs: &[Expr], rhs: &[Expr]) -> Expr {
23480            let mut it = lhs.iter().zip(rhs.iter()).map(|(l, r)| Expr::Binary {
23481                lhs: Box::new(l.clone()),
23482                op: BinOp::Eq,
23483                rhs: Box::new(r.clone()),
23484            });
23485            let first = it.next().expect("row has at least two elements");
23486            it.fold(first, |acc, e| Expr::Binary {
23487                lhs: Box::new(acc),
23488                op: BinOp::And,
23489                rhs: Box::new(e),
23490            })
23491        }
23492        // Lexicographic (a,b) OP (c,d):
23493        //   a STRICT c OR (a = c AND (b OP d))  — recursing right.
23494        fn row_lex(lhs: &[Expr], rhs: &[Expr], strict: BinOp, last: BinOp) -> Expr {
23495            if lhs.len() == 1 {
23496                return Expr::Binary {
23497                    lhs: Box::new(lhs[0].clone()),
23498                    op: last,
23499                    rhs: Box::new(rhs[0].clone()),
23500                };
23501            }
23502            let head_strict = Expr::Binary {
23503                lhs: Box::new(lhs[0].clone()),
23504                op: strict,
23505                rhs: Box::new(rhs[0].clone()),
23506            };
23507            let head_eq = Expr::Binary {
23508                lhs: Box::new(lhs[0].clone()),
23509                op: BinOp::Eq,
23510                rhs: Box::new(rhs[0].clone()),
23511            };
23512            Expr::Binary {
23513                lhs: Box::new(head_strict),
23514                op: BinOp::Or,
23515                rhs: Box::new(Expr::Binary {
23516                    lhs: Box::new(head_eq),
23517                    op: BinOp::And,
23518                    rhs: Box::new(row_lex(&lhs[1..], &rhs[1..], strict, last)),
23519                }),
23520            }
23521        }
23522        let negated_in = if matches!(self.peek(), Token::Not)
23523            && matches!(self.tokens.get(self.pos + 1), Some(Token::In))
23524        {
23525            self.advance();
23526            true
23527        } else {
23528            false
23529        };
23530        if matches!(self.peek(), Token::In) {
23531            self.advance();
23532            if !matches!(self.peek(), Token::LParen) {
23533                return Err(self.err(alloc::format!(
23534                    "expected '(' after row IN, got {:?}",
23535                    self.peek()
23536                )));
23537            }
23538            self.advance();
23539            // `(a, b) [NOT] IN (SELECT x, y)` — a multi-column subquery,
23540            // not a list of literal rows. Row-vs-list decomposes to
23541            // OR-of-AND above, but the subquery's rows are only known at
23542            // runtime, so keep it as a RowInSubquery node.
23543            if matches!(self.peek(), Token::Select) {
23544                let inner = self.parse_select_stmt()?;
23545                if !matches!(self.peek(), Token::RParen) {
23546                    return Err(self.err(alloc::format!(
23547                        "expected ')' after row IN-subquery, got {:?}",
23548                        self.peek()
23549                    )));
23550                }
23551                self.advance();
23552                let Statement::Select(s) = inner else {
23553                    unreachable!("parse_select_stmt always returns Statement::Select")
23554                };
23555                return Ok(Expr::RowInSubquery {
23556                    row,
23557                    subquery: Box::new(s),
23558                    negated: negated_in,
23559                });
23560            }
23561            let mut alternatives: Vec<Expr> = Vec::new();
23562            loop {
23563                // Optional ROW keyword before the paren row.
23564                if matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("row"))
23565                    && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
23566                {
23567                    self.advance();
23568                }
23569                if !matches!(self.peek(), Token::LParen) {
23570                    return Err(self.err(alloc::format!(
23571                        "expected '(' to open a row inside IN, got {:?}",
23572                        self.peek()
23573                    )));
23574                }
23575                self.advance();
23576                let mut rhs = alloc::vec![self.parse_expr(0)?];
23577                while matches!(self.peek(), Token::Comma) {
23578                    self.advance();
23579                    rhs.push(self.parse_expr(0)?);
23580                }
23581                if !matches!(self.peek(), Token::RParen) {
23582                    return Err(self.err(alloc::format!(
23583                        "expected ')' after row inside IN, got {:?}",
23584                        self.peek()
23585                    )));
23586                }
23587                self.advance();
23588                if rhs.len() != row.len() {
23589                    return Err(self.err(alloc::format!(
23590                        "row IN arity mismatch: left has {}, right has {}",
23591                        row.len(),
23592                        rhs.len()
23593                    )));
23594                }
23595                alternatives.push(row_eq(&row, &rhs));
23596                if matches!(self.peek(), Token::Comma) {
23597                    self.advance();
23598                    continue;
23599                }
23600                break;
23601            }
23602            if !matches!(self.peek(), Token::RParen) {
23603                return Err(self.err(alloc::format!(
23604                    "expected ')' to close row IN list, got {:?}",
23605                    self.peek()
23606                )));
23607            }
23608            self.advance();
23609            let mut it = alternatives.into_iter();
23610            let first = it.next().expect("IN list has at least one row");
23611            let combined = it.fold(first, |acc, e| Expr::Binary {
23612                lhs: Box::new(acc),
23613                op: BinOp::Or,
23614                rhs: Box::new(e),
23615            });
23616            return Ok(maybe_not(combined, negated_in));
23617        }
23618        // SQL-standard `(S1, E1) OVERLAPS (S2, E2)` — true when the
23619        // two periods share at least one time point. Each pair is
23620        // normalised with least/greatest (PG accepts the endpoints
23621        // in either order), then lowered to the standard
23622        // `start1 < end2 AND start2 < end1` form.
23623        if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("overlaps")) {
23624            if row.len() != 2 {
23625                return Err(self.err(alloc::format!(
23626                    "OVERLAPS needs (start, end) pairs; left side has {} elements",
23627                    row.len()
23628                )));
23629            }
23630            self.advance();
23631            if matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("row"))
23632                && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
23633            {
23634                self.advance();
23635            }
23636            if !matches!(self.peek(), Token::LParen) {
23637                return Err(self.err(alloc::format!(
23638                    "expected '(' after OVERLAPS, got {:?}",
23639                    self.peek()
23640                )));
23641            }
23642            self.advance();
23643            let r0 = self.parse_expr(0)?;
23644            if !matches!(self.peek(), Token::Comma) {
23645                return Err(self.err(alloc::format!(
23646                    "OVERLAPS needs (start, end) on the right, got {:?}",
23647                    self.peek()
23648                )));
23649            }
23650            self.advance();
23651            let r1 = self.parse_expr(0)?;
23652            if !matches!(self.peek(), Token::RParen) {
23653                return Err(self.err(alloc::format!(
23654                    "expected ')' after OVERLAPS pair, got {:?}",
23655                    self.peek()
23656                )));
23657            }
23658            self.advance();
23659            let pair_fn = |name: &str, a: &Expr, b: &Expr| Expr::FunctionCall {
23660                name: String::from(name),
23661                args: alloc::vec![a.clone(), b.clone()],
23662            };
23663            let lt = |lhs: Expr, rhs: Expr| Expr::Binary {
23664                lhs: Box::new(lhs),
23665                op: BinOp::Lt,
23666                rhs: Box::new(rhs),
23667            };
23668            return Ok(Expr::Binary {
23669                lhs: Box::new(lt(
23670                    pair_fn("least", &row[0], &row[1]),
23671                    pair_fn("greatest", &r0, &r1),
23672                )),
23673                op: BinOp::And,
23674                rhs: Box::new(lt(
23675                    pair_fn("least", &r0, &r1),
23676                    pair_fn("greatest", &row[0], &row[1]),
23677                )),
23678            });
23679        }
23680        // `(a, b, …) IS [NOT] NULL` — the SQL row null predicate. Per
23681        // PG, `IS NULL` is true only when EVERY field is NULL, and
23682        // `IS NOT NULL` is true only when every field is non-NULL — the
23683        // latter is NOT the negation of the former (a mixed row is
23684        // neither). Desugar to an AND chain of per-field `IS [NOT] NULL`,
23685        // which reproduces exactly that all-fields semantics.
23686        if matches!(self.peek(), Token::Is) {
23687            self.advance();
23688            let negated = if matches!(self.peek(), Token::Not) {
23689                self.advance();
23690                true
23691            } else {
23692                false
23693            };
23694            if !matches!(self.peek(), Token::Null) {
23695                return Err(self.err(alloc::format!(
23696                    "expected NULL after row IS [NOT], got {:?}",
23697                    self.peek()
23698                )));
23699            }
23700            self.advance();
23701            let mut it = row.iter().map(|e| Expr::IsNull {
23702                expr: Box::new(e.clone()),
23703                negated,
23704            });
23705            let first = it.next().expect("row has at least two elements");
23706            return Ok(it.fold(first, |acc, e| Expr::Binary {
23707                lhs: Box::new(acc),
23708                op: BinOp::And,
23709                rhs: Box::new(e),
23710            }));
23711        }
23712        let op = match self.peek() {
23713            Token::Eq => BinOp::Eq,
23714            Token::NotEq => BinOp::NotEq,
23715            Token::Lt => BinOp::Lt,
23716            Token::LtEq => BinOp::LtEq,
23717            Token::Gt => BinOp::Gt,
23718            Token::GtEq => BinOp::GtEq,
23719            // v7.38 (read01, composite) — a bare `(a, b, …)` not followed by a
23720            // comparison / [NOT] IN / IS [NOT] NULL / OVERLAPS is a row (record)
23721            // constructor value, identical to the `ROW(a, b, …)` keyword form:
23722            // `(1,'a')::text` → `(1,a)`, `SELECT (1,2,3)` → `(1,2,3)`. Postfix
23723            // (`::text`, `.field`) applies at the caller just as it does for the
23724            // ROW(...) node. All the comparison / predicate forms returned above.
23725            _ => {
23726                return Ok(Expr::FunctionCall {
23727                    name: String::from("row"),
23728                    args: row,
23729                });
23730            }
23731        };
23732        self.advance();
23733        // Optional ROW keyword before the paren row.
23734        if matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("row"))
23735            && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen))
23736        {
23737            self.advance();
23738        }
23739        if !matches!(self.peek(), Token::LParen) {
23740            return Err(self.err(alloc::format!(
23741                "expected '(' to open the right-hand row, got {:?}",
23742                self.peek()
23743            )));
23744        }
23745        self.advance();
23746        // `(a, b) <op> (SELECT x, y)` — compare against a single-row
23747        // subquery. Kept as a node (the subquery's row is a runtime value);
23748        // the literal-RHS form below still decomposes at parse time.
23749        if matches!(self.peek(), Token::Select) {
23750            let inner = self.parse_select_stmt()?;
23751            if !matches!(self.peek(), Token::RParen) {
23752                return Err(self.err(alloc::format!(
23753                    "expected ')' after row comparison subquery, got {:?}",
23754                    self.peek()
23755                )));
23756            }
23757            self.advance();
23758            let Statement::Select(s) = inner else {
23759                unreachable!("parse_select_stmt always returns Statement::Select")
23760            };
23761            return Ok(Expr::RowCmpSubquery {
23762                row,
23763                op,
23764                subquery: Box::new(s),
23765            });
23766        }
23767        let mut rhs = alloc::vec![self.parse_expr(0)?];
23768        while matches!(self.peek(), Token::Comma) {
23769            self.advance();
23770            rhs.push(self.parse_expr(0)?);
23771        }
23772        if !matches!(self.peek(), Token::RParen) {
23773            return Err(self.err(alloc::format!(
23774                "expected ')' after right-hand row, got {:?}",
23775                self.peek()
23776            )));
23777        }
23778        self.advance();
23779        if rhs.len() != row.len() {
23780            // v7.39 (round 239) — PG's wording (42601).
23781            return Err(self.err("unequal number of entries in row expressions".to_string()));
23782        }
23783        Ok(match op {
23784            BinOp::Eq => row_eq(&row, &rhs),
23785            BinOp::NotEq => maybe_not(row_eq(&row, &rhs), true),
23786            BinOp::Lt => row_lex(&row, &rhs, BinOp::Lt, BinOp::Lt),
23787            BinOp::LtEq => row_lex(&row, &rhs, BinOp::Lt, BinOp::LtEq),
23788            BinOp::Gt => row_lex(&row, &rhs, BinOp::Gt, BinOp::Gt),
23789            BinOp::GtEq => row_lex(&row, &rhs, BinOp::Gt, BinOp::GtEq),
23790            _ => unreachable!("op restricted above"),
23791        })
23792    }
23793
23794    /// `LIKE p ESCAPE 'c'` — rewrite the pattern so the custom
23795    /// escape character becomes the matcher's default backslash:
23796    /// `c%` (escaped wildcard) → `\%`, `cc` (literal escape char)
23797    /// → the char itself, and any pre-existing backslash escapes
23798    /// itself so it stays literal. Both operands must be string
23799    /// literals — a runtime pattern would need matcher support.
23800    fn rewrite_like_escape(pattern: Expr, esc: Expr) -> Result<Expr, String> {
23801        let (Expr::Literal(Literal::String(p)), Expr::Literal(Literal::String(e))) =
23802            (&pattern, &esc)
23803        else {
23804            return Err(
23805                "LIKE ... ESCAPE requires string-literal pattern and escape \
23806                 (runtime escape characters are not supported yet)"
23807                    .into(),
23808            );
23809        };
23810        // v7.38 (read01 P6.18) — PG accepts `ESCAPE ''` to mean "no escape
23811        // character" (every `%`/`_` is a wildcard, nothing is escaped). Only a
23812        // multi-character escape is an error.
23813        let esc_ch: Option<char> = {
23814            let mut ch_iter = e.chars();
23815            match (ch_iter.next(), ch_iter.next()) {
23816                (Some(c), None) => Some(c),
23817                (None, _) => None,
23818                (Some(_), Some(_)) => {
23819                    return Err(alloc::format!(
23820                        "ESCAPE must be a single character, got {e:?}"
23821                    ));
23822                }
23823            }
23824        };
23825        let mut out = String::with_capacity(p.len() + 4);
23826        let mut chars = p.chars();
23827        while let Some(c) = chars.next() {
23828            if Some(c) == esc_ch {
23829                match chars.next() {
23830                    // Escaped wildcard / escaped escape → keep the
23831                    // next char literal via backslash.
23832                    Some(next) => {
23833                        out.push('\\');
23834                        out.push(next);
23835                    }
23836                    None => {
23837                        return Err("LIKE pattern ends with the escape character".into());
23838                    }
23839                }
23840            } else if c == '\\' && esc_ch != Some('\\') {
23841                // A raw backslash is literal under a custom (or absent) escape
23842                // — escape it for the backslash-based matcher.
23843                out.push('\\');
23844                out.push('\\');
23845            } else {
23846                out.push(c);
23847            }
23848        }
23849        Ok(Expr::Literal(Literal::String(out)))
23850    }
23851
23852    /// `x [NOT] LIKE ANY/ALL (ARRAY[p1, p2, …])` — quantified pattern
23853    /// match. Desugars to an OR (ANY) / AND (ALL) chain of per-element
23854    /// `x [NOT] LIKE pi`, which reproduces PG's three-valued semantics
23855    /// exactly (a NULL pattern makes an element NULL; `false OR NULL` =
23856    /// NULL, `true AND NULL` = NULL, …). ANY over an empty array is
23857    /// FALSE, ALL over empty is TRUE. Returns `None` when the token after
23858    /// LIKE is not `ANY(`/`ALL(`, so the caller falls back to a plain
23859    /// pattern. Only a literal `ARRAY[...]` is accepted today — a runtime
23860    /// array expression errors honestly rather than silently mismatching.
23861    fn try_like_any_all(
23862        &mut self,
23863        base: &Expr,
23864        negated: bool,
23865        case_insensitive: bool,
23866    ) -> Result<Option<Expr>, ParseError> {
23867        let is_any = match self.peek() {
23868            Token::All if matches!(self.tokens.get(self.pos + 1), Some(Token::LParen)) => false,
23869            Token::Ident(s)
23870                if s.eq_ignore_ascii_case("any")
23871                    && matches!(self.tokens.get(self.pos + 1), Some(Token::LParen)) =>
23872            {
23873                true
23874            }
23875            _ => return Ok(None),
23876        };
23877        self.advance(); // ANY / ALL
23878        self.advance(); // '('
23879        let arr = self.parse_expr(0)?;
23880        if !matches!(self.peek(), Token::RParen) {
23881            return Err(self.err(format!(
23882                "expected ')' after LIKE {} argument, got {:?}",
23883                if is_any { "ANY" } else { "ALL" },
23884                self.peek()
23885            )));
23886        }
23887        self.advance(); // ')'
23888        let Expr::Array(items) = arr else {
23889            return Err(self.err(
23890                "LIKE ANY/ALL currently requires a literal ARRAY[...] of patterns".to_string(),
23891            ));
23892        };
23893        let mut clauses = items.into_iter().map(|p| Expr::Like {
23894            expr: Box::new(base.clone()),
23895            pattern: Box::new(p),
23896            negated,
23897            case_insensitive,
23898        });
23899        let Some(first) = clauses.next() else {
23900            // ANY(empty) = FALSE, ALL(empty) = TRUE.
23901            return Ok(Some(Expr::Literal(Literal::Bool(!is_any))));
23902        };
23903        let op = if is_any { BinOp::Or } else { BinOp::And };
23904        let combined = clauses.fold(first, |acc, c| Expr::Binary {
23905            lhs: Box::new(acc),
23906            op,
23907            rhs: Box::new(c),
23908        });
23909        Ok(Some(combined))
23910    }
23911
23912    /// `x BETWEEN low AND high`  →  `(x >= low) AND (x <= high)`, wrapped in
23913    /// `NOT` when `negated`. Bounds parse at precedence 5 so the trailing
23914    /// `AND` is not swallowed.
23915    fn parse_between_tail(&mut self, expr: Expr, negated: bool) -> Result<Expr, ParseError> {
23916        self.advance(); // BETWEEN
23917        // SYMMETRIC — the bounds may arrive in either order; both
23918        // orientations OR together. ASYMMETRIC is the default and
23919        // absorbs as noise.
23920        let symmetric = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("symmetric"))
23921        {
23922            self.advance();
23923            true
23924        } else {
23925            if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("asymmetric")) {
23926                self.advance();
23927            }
23928            false
23929        };
23930        let low = self.parse_expr(6)?;
23931        if !matches!(self.peek(), Token::And) {
23932            return Err(self.err(format!(
23933                "expected AND after BETWEEN low bound, got {:?}",
23934                self.peek()
23935            )));
23936        }
23937        self.advance();
23938        let high = self.parse_expr(6)?;
23939        let target = Box::new(expr);
23940        let range = |lo: Expr, hi: Expr| Expr::Binary {
23941            lhs: Box::new(Expr::Binary {
23942                lhs: target.clone(),
23943                op: BinOp::GtEq,
23944                rhs: Box::new(lo),
23945            }),
23946            op: BinOp::And,
23947            rhs: Box::new(Expr::Binary {
23948                lhs: target.clone(),
23949                op: BinOp::LtEq,
23950                rhs: Box::new(hi),
23951            }),
23952        };
23953        let combined = if symmetric {
23954            Expr::Binary {
23955                lhs: Box::new(range(low.clone(), high.clone())),
23956                op: BinOp::Or,
23957                rhs: Box::new(range(high, low)),
23958            }
23959        } else {
23960            range(low, high)
23961        };
23962        Ok(maybe_not(combined, negated))
23963    }
23964
23965    /// `x IN (a, b, c)`  →  chained OR of equalities. Empty list collapses
23966    /// to FALSE (TRUE under NOT IN), matching standard SQL semantics.
23967    /// v4.11: parse `WITH name AS (SELECT ...) [, ...] SELECT ...`.
23968    /// Caller already consumed the leading `WITH` ident.
23969    /// v7.38 (read01) — recursive-CTE well-formedness. PG rejects ORDER BY
23970    /// / LIMIT / OFFSET anywhere in a recursive query, and a recursive
23971    /// self-reference that appears more than once in a single term.
23972    fn validate_recursive_cte(&self, cte: &crate::ast::Cte) -> Result<(), ParseError> {
23973        use crate::ast::{CteBody, SelectStatement};
23974        if !cte.recursive {
23975            return Ok(());
23976        }
23977        let CteBody::Select(body) = &cte.body else {
23978            return Ok(());
23979        };
23980        // A recursive CTE body is `base UNION [ALL] recursive [UNION …]`;
23981        // check the anchor and every peer term.
23982        let has_order = |s: &SelectStatement| !s.order_by.is_empty();
23983        let has_limit = |s: &SelectStatement| s.limit.is_some() || s.offset.is_some();
23984        if has_order(body) || body.unions.iter().any(|(_, u)| has_order(u)) {
23985            return Err(self.err(String::from(
23986                "ORDER BY in a recursive query is not implemented",
23987            )));
23988        }
23989        if has_limit(body) || body.unions.iter().any(|(_, u)| has_limit(u)) {
23990            return Err(self.err(String::from(
23991                "LIMIT in a recursive query is not implemented",
23992            )));
23993        }
23994        let self_refs = |s: &SelectStatement| -> usize {
23995            let Some(from) = &s.from else {
23996                return 0;
23997            };
23998            let mut n = usize::from(from.primary.name.eq_ignore_ascii_case(&cte.name));
23999            for j in &from.joins {
24000                if j.table.name.eq_ignore_ascii_case(&cte.name) {
24001                    n += 1;
24002                }
24003            }
24004            n
24005        };
24006        if body.unions.iter().any(|(_, u)| self_refs(u) > 1) {
24007            return Err(self.err(alloc::format!(
24008                "recursive reference to query \"{}\" must not appear more than once",
24009                cte.name
24010            )));
24011        }
24012        // v7.39 (round 145, parse_cte.c) — the remaining well-formedness rules
24013        // apply only when the body actually references itself (a non-self-
24014        // referencing CTE under WITH RECURSIVE may use any set-op shape).
24015        let anchor_refs = self_refs(body);
24016        let union_refs = body.unions.iter().any(|(_, u)| self_refs(u) > 0);
24017        if anchor_refs > 0 || union_refs {
24018            // Shape: the top level must be UNION [ALL] arms only. A self-ref
24019            // under INTERSECT / EXCEPT (or with no set-op at all) is PG's
24020            // "does not have the form" error — SPG used to compute a value.
24021            if body.unions.is_empty()
24022                || body.unions.iter().any(|(k, _)| {
24023                    !matches!(
24024                        k,
24025                        crate::ast::UnionKind::Distinct | crate::ast::UnionKind::All
24026                    )
24027                })
24028            {
24029                return Err(self.err(alloc::format!(
24030                    "recursive query \"{}\" does not have the form non-recursive-term \
24031                     UNION [ALL] recursive-term",
24032                    cte.name
24033                )));
24034            }
24035            if anchor_refs > 0 {
24036                return Err(self.err(alloc::format!(
24037                    "recursive reference to query \"{}\" must not appear within its non-recursive term",
24038                    cte.name
24039                )));
24040            }
24041        }
24042        let is_self = |t: &crate::ast::TableRef| t.name.eq_ignore_ascii_case(&cte.name);
24043        for (_, u) in &body.unions {
24044            if self_refs(u) == 0 {
24045                continue;
24046            }
24047            // The self-reference must not sit on the nullable side of an outer
24048            // join (LEFT: right side; RIGHT: everything before it; FULL: both).
24049            if let Some(from) = &u.from {
24050                for (i, j) in from.joins.iter().enumerate() {
24051                    let left_has_self = is_self(&from.primary)
24052                        || from.joins[..i].iter().any(|pj| is_self(&pj.table));
24053                    let violated = match j.kind {
24054                        crate::ast::JoinKind::Left => is_self(&j.table),
24055                        crate::ast::JoinKind::Right => left_has_self,
24056                        crate::ast::JoinKind::FullOuter => is_self(&j.table) || left_has_self,
24057                        _ => false,
24058                    };
24059                    if violated {
24060                        return Err(self.err(alloc::format!(
24061                            "recursive reference to query \"{}\" must not appear within an outer join",
24062                            cte.name
24063                        )));
24064                    }
24065                }
24066            }
24067            // No aggregates at the top level of the recursive term (SPG used
24068            // to run them and surface a misleading downstream error).
24069            let mut items_and_having: Vec<&Expr> = Vec::new();
24070            for it in &u.items {
24071                if let crate::ast::SelectItem::Expr { expr, .. } = it {
24072                    items_and_having.push(expr);
24073                }
24074            }
24075            if let Some(h) = &u.having {
24076                items_and_having.push(h);
24077            }
24078            for e in items_and_having {
24079                if expr_has_toplevel_aggregate(e) {
24080                    return Err(self.err(String::from(
24081                        "aggregate functions are not allowed in a recursive query's recursive term",
24082                    )));
24083                }
24084            }
24085        }
24086        // A self-reference inside a sublink expression (EXISTS / IN / scalar
24087        // subquery) anywhere in the body is rejected; a plain FROM derived
24088        // table is legal in PG and untouched here.
24089        let mut all_terms: Vec<&SelectStatement> = alloc::vec![body];
24090        all_terms.extend(body.unions.iter().map(|(_, u)| u));
24091        for term in all_terms {
24092            if select_has_self_ref_in_sublink(term, &cte.name) {
24093                return Err(self.err(alloc::format!(
24094                    "recursive reference to query \"{}\" must not appear within a subquery",
24095                    cte.name
24096                )));
24097            }
24098        }
24099        Ok(())
24100    }
24101
24102    /// v7.38 (read01 U16) — desugar a CTE's SEARCH / CYCLE clause into
24103    /// extra body columns, mirroring PG's `rewriteSearchAndCycle`. Runs
24104    /// right after parse so the engine sees a plain recursive CTE with the
24105    /// tracking columns already projected. DEPTH FIRST and CYCLE are
24106    /// supported; BREADTH FIRST needs numeric-composite ordering SPG's
24107    /// text-rendered rows can't provide, and errors honestly.
24108    fn desugar_cte_search_cycle(&self, cte: &mut crate::ast::Cte) -> Result<(), ParseError> {
24109        use crate::ast::{BinOp, ColumnName, CteBody, Expr, Literal, SelectItem, UnOp};
24110        if cte.search.is_none() && cte.cycle.is_none() {
24111            return Ok(());
24112        }
24113        let cte_name = cte.name.clone();
24114        let col_names = cte.column_overrides.clone();
24115        if col_names.is_empty() {
24116            return Err(
24117                self.err("SEARCH / CYCLE requires an explicit WITH name(cols) column list".into())
24118            );
24119        }
24120        let search = cte.search.take();
24121        let cycle = cte.cycle.take();
24122        let mut extra_cols: Vec<String> = Vec::new();
24123        let col_ref = |name: &str| {
24124            Expr::Column(ColumnName {
24125                qualifier: Some(cte_name.clone()),
24126                name: name.to_string(),
24127            })
24128        };
24129        // Position of a SEARCH/CYCLE column within the CTE's column list.
24130        let pos_of = |name: &str| -> Result<usize, ParseError> {
24131            col_names
24132                .iter()
24133                .position(|c| c.eq_ignore_ascii_case(name))
24134                .ok_or_else(|| {
24135                    self.err(format!("SEARCH/CYCLE column {name:?} is not a CTE column"))
24136                })
24137        };
24138        let row_of = |items: &[SelectItem], positions: &[usize]| -> Result<Expr, ParseError> {
24139            let mut args = Vec::with_capacity(positions.len());
24140            for &p in positions {
24141                match items.get(p) {
24142                    Some(SelectItem::Expr { expr, .. }) => args.push(expr.clone()),
24143                    _ => {
24144                        return Err(self.err(
24145                            "SEARCH/CYCLE column maps to a non-expression select item".into(),
24146                        ));
24147                    }
24148                }
24149            }
24150            Ok(Expr::FunctionCall {
24151                name: "row".into(),
24152                args,
24153            })
24154        };
24155        let CteBody::Select(body) = &mut cte.body else {
24156            return Err(self.err("SEARCH / CYCLE requires a SELECT CTE body".into()));
24157        };
24158        if body.unions.is_empty() {
24159            return Err(self.err("SEARCH / CYCLE requires a recursive (UNION) CTE".into()));
24160        }
24161        let rec = body.unions.len() - 1; // recursive term = last UNION peer
24162
24163        if let Some(srch) = search {
24164            // v7.38 (T31) — SEARCH's SET column is ORDER BY'd, and PG's key is a
24165            // `record[]` (DEPTH) or `(depth, keys…)` record (BREADTH). SPG has
24166            // no typed `record[]`, but element-wise array ORDER BY is correct
24167            // (`[1,2] < [1,10] < [2]`), so a SINGLE scalar BY column maps
24168            // exactly onto a typed array: DEPTH is the root→node path
24169            // `array_append(parent, key)`, BREADTH is `[depth, key]`. This
24170            // orders numerically (multi-digit keys included), matching PG.
24171            //
24172            // A multi-column BY would need a record[] to keep the per-node key
24173            // tuple orderable, which SPG can't express — error honestly there
24174            // rather than mis-order.
24175            if srch.by_columns.len() != 1 {
24176                return Err(self.err(
24177                    "SEARCH … BY with multiple columns needs typed record[] ordering \
24178                     SPG doesn't have yet; a single BY column is supported"
24179                        .into(),
24180                ));
24181            }
24182            let key_pos = pos_of(&srch.by_columns[0])?;
24183            let base_key = match body.items.get(key_pos) {
24184                Some(SelectItem::Expr { expr, .. }) => expr.clone(),
24185                _ => {
24186                    return Err(
24187                        self.err("SEARCH BY column maps to a non-expression select item".into())
24188                    );
24189                }
24190            };
24191            let rec_key = match body.unions[rec].1.items.get(key_pos) {
24192                Some(SelectItem::Expr { expr, .. }) => expr.clone(),
24193                _ => {
24194                    return Err(
24195                        self.err("SEARCH BY column maps to a non-expression select item".into())
24196                    );
24197                }
24198            };
24199            if srch.depth_first {
24200                // base: ARRAY[key]; rec: array_append(cte.set, key).
24201                body.items.push(SelectItem::Expr {
24202                    expr: Expr::Array(alloc::vec![base_key]),
24203                    alias: Some(srch.set_column.clone()),
24204                });
24205                body.unions[rec].1.items.push(SelectItem::Expr {
24206                    expr: Expr::FunctionCall {
24207                        name: "array_append".into(),
24208                        args: alloc::vec![col_ref(&srch.set_column), rec_key],
24209                    },
24210                    alias: Some(srch.set_column.clone()),
24211                });
24212            } else {
24213                // BREADTH: [depth, key]; depth starts at 0 and increments. The
24214                // leading depth element dominates the element-wise comparison,
24215                // so shallower rows sort first, then by key — PG's (depth, key).
24216                body.items.push(SelectItem::Expr {
24217                    expr: Expr::Array(alloc::vec![Expr::Literal(Literal::Integer(0)), base_key,]),
24218                    alias: Some(srch.set_column.clone()),
24219                });
24220                // rec depth = cte.set[1] + 1.
24221                let parent_depth = Expr::ArraySubscript {
24222                    target: Box::new(col_ref(&srch.set_column)),
24223                    index: Box::new(Expr::Literal(Literal::Integer(1))),
24224                };
24225                body.unions[rec].1.items.push(SelectItem::Expr {
24226                    expr: Expr::Array(alloc::vec![
24227                        Expr::Binary {
24228                            lhs: Box::new(parent_depth),
24229                            op: BinOp::Add,
24230                            rhs: Box::new(Expr::Literal(Literal::Integer(1))),
24231                        },
24232                        rec_key,
24233                    ]),
24234                    alias: Some(srch.set_column.clone()),
24235                });
24236            }
24237            extra_cols.push(srch.set_column);
24238        }
24239
24240        if let Some(cyc) = cycle {
24241            let positions: Vec<usize> = cyc
24242                .columns
24243                .iter()
24244                .map(|c| pos_of(c))
24245                .collect::<Result<_, _>>()?;
24246            // v7.38 (read01, T9) — ROW(cols) is now a first-class composite, so
24247            // cast it to text for the cycle path: membership only needs equality,
24248            // and the record text form gives SPG a TextArray path (SPG has no
24249            // typed record[] array). Cycle detection is unaffected.
24250            let base_row = Expr::Cast {
24251                expr: Box::new(row_of(&body.items, &positions)?),
24252                target: CastTarget::Text,
24253            };
24254            let rec_row = Expr::Cast {
24255                expr: Box::new(row_of(&body.unions[rec].1.items, &positions)?),
24256                target: CastTarget::Text,
24257            };
24258            let mark = cyc.mark_value.clone().unwrap_or(Literal::Bool(true));
24259            let dflt = cyc.default_value.clone().unwrap_or(Literal::Bool(false));
24260            // base: <default> AS mark, ARRAY[ROW(cols)] AS path.
24261            body.items.push(SelectItem::Expr {
24262                expr: Expr::Literal(dflt.clone()),
24263                alias: Some(cyc.mark_column.clone()),
24264            });
24265            body.items.push(SelectItem::Expr {
24266                expr: Expr::Array(alloc::vec![base_row]),
24267                alias: Some(cyc.path_column.clone()),
24268            });
24269            // rec mark: ROW(cols) already in the path → cycle.
24270            let hit = Expr::AnyAll {
24271                expr: Box::new(rec_row.clone()),
24272                op: BinOp::Eq,
24273                array: Box::new(col_ref(&cyc.path_column)),
24274                is_any: true,
24275            };
24276            let mark_expr = if cyc.mark_value.is_some() || cyc.default_value.is_some() {
24277                Expr::Case {
24278                    operand: None,
24279                    branches: alloc::vec![(hit, Expr::Literal(mark))],
24280                    else_branch: Some(Box::new(Expr::Literal(dflt))),
24281                }
24282            } else {
24283                hit
24284            };
24285            body.unions[rec].1.items.push(SelectItem::Expr {
24286                expr: mark_expr,
24287                alias: Some(cyc.mark_column.clone()),
24288            });
24289            // rec path: array_append(cte.path, ROW(cols)).
24290            body.unions[rec].1.items.push(SelectItem::Expr {
24291                expr: Expr::FunctionCall {
24292                    name: "array_append".into(),
24293                    args: alloc::vec![col_ref(&cyc.path_column), rec_row],
24294                },
24295                alias: Some(cyc.path_column.clone()),
24296            });
24297            // rec WHERE: AND NOT cte.mark — stop expanding a cycled row.
24298            let stop = Expr::Unary {
24299                op: UnOp::Not,
24300                expr: Box::new(col_ref(&cyc.mark_column)),
24301            };
24302            let w = &mut body.unions[rec].1.where_;
24303            *w = Some(match w.take() {
24304                Some(prev) => Expr::Binary {
24305                    lhs: Box::new(prev),
24306                    op: BinOp::And,
24307                    rhs: Box::new(stop),
24308                },
24309                None => stop,
24310            });
24311            extra_cols.push(cyc.mark_column);
24312            extra_cols.push(cyc.path_column);
24313        }
24314        cte.column_overrides.extend(extra_cols);
24315        Ok(())
24316    }
24317
24318    /// v7.38 (read01 U16) — `SEARCH { DEPTH | BREADTH } FIRST BY col [,
24319    /// col…] SET seqcol`. Returns None when the next token isn't SEARCH.
24320    fn parse_cte_search_clause(&mut self) -> Result<Option<crate::ast::SearchClause>, ParseError> {
24321        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("search")) {
24322            return Ok(None);
24323        }
24324        self.advance(); // SEARCH
24325        let depth_first = match self.peek() {
24326            Token::Ident(s) if s.eq_ignore_ascii_case("depth") => true,
24327            Token::Ident(s) if s.eq_ignore_ascii_case("breadth") => false,
24328            other => {
24329                return Err(self.err(format!(
24330                    "expected DEPTH or BREADTH after SEARCH, got {other:?}"
24331                )));
24332            }
24333        };
24334        self.advance();
24335        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("first")) {
24336            return Err(self.err(format!(
24337                "expected FIRST after SEARCH mode, got {:?}",
24338                self.peek()
24339            )));
24340        }
24341        self.advance();
24342        if !self.peek_is_by() {
24343            return Err(self.err(format!(
24344                "expected BY after SEARCH … FIRST, got {:?}",
24345                self.peek()
24346            )));
24347        }
24348        self.advance();
24349        let mut by_columns = alloc::vec![self.expect_ident_like()?];
24350        while matches!(self.peek(), Token::Comma) {
24351            self.advance();
24352            by_columns.push(self.expect_ident_like()?);
24353        }
24354        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("set")) {
24355            return Err(self.err(format!(
24356                "expected SET in SEARCH clause, got {:?}",
24357                self.peek()
24358            )));
24359        }
24360        self.advance();
24361        let set_column = self.expect_ident_like()?;
24362        Ok(Some(crate::ast::SearchClause {
24363            depth_first,
24364            by_columns,
24365            set_column,
24366        }))
24367    }
24368
24369    /// v7.38 (read01 U16) — `CYCLE col [, col…] SET markcol [TO v DEFAULT w]
24370    /// USING pathcol`. Returns None when the next token isn't CYCLE.
24371    fn parse_cte_cycle_clause(&mut self) -> Result<Option<crate::ast::CycleClause>, ParseError> {
24372        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("cycle")) {
24373            return Ok(None);
24374        }
24375        self.advance(); // CYCLE
24376        let mut columns = alloc::vec![self.expect_ident_like()?];
24377        while matches!(self.peek(), Token::Comma) {
24378            self.advance();
24379            columns.push(self.expect_ident_like()?);
24380        }
24381        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("set")) {
24382            return Err(self.err(format!(
24383                "expected SET in CYCLE clause, got {:?}",
24384                self.peek()
24385            )));
24386        }
24387        self.advance();
24388        let mark_column = self.expect_ident_like()?;
24389        let mut mark_value = None;
24390        let mut default_value = None;
24391        if matches!(self.peek(), Token::To) {
24392            self.advance();
24393            mark_value = Some(self.parse_cycle_literal()?);
24394            if !matches!(self.peek(), Token::Default) {
24395                return Err(self.err(format!(
24396                    "expected DEFAULT after CYCLE … TO, got {:?}",
24397                    self.peek()
24398                )));
24399            }
24400            self.advance();
24401            default_value = Some(self.parse_cycle_literal()?);
24402        }
24403        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("using")) {
24404            return Err(self.err(format!(
24405                "expected USING in CYCLE clause, got {:?}",
24406                self.peek()
24407            )));
24408        }
24409        self.advance();
24410        let path_column = self.expect_ident_like()?;
24411        Ok(Some(crate::ast::CycleClause {
24412            columns,
24413            mark_column,
24414            mark_value,
24415            default_value,
24416            path_column,
24417        }))
24418    }
24419
24420    /// The mark / default value in a CYCLE `TO v DEFAULT w` — a bare
24421    /// literal (string / bool / number) in PG.
24422    fn parse_cycle_literal(&mut self) -> Result<crate::ast::Literal, ParseError> {
24423        match self.parse_expr(0)? {
24424            Expr::Literal(l) => Ok(l),
24425            other => Err(self.err(format!(
24426                "CYCLE mark/default value must be a literal, got {other:?}"
24427            ))),
24428        }
24429    }
24430
24431    fn parse_with_cte_then_select(&mut self) -> Result<Statement, ParseError> {
24432        // v4.22: WITH RECURSIVE — optional keyword right after WITH.
24433        // Comes through as an identifier; consume it if present and
24434        // mark every CTE in the clause as recursive (PG semantics —
24435        // the flag is per-WITH, not per-CTE).
24436        let mut recursive = false;
24437        if let Token::Ident(s) | Token::QuotedIdent(s) = self.peek()
24438            && s.eq_ignore_ascii_case("recursive")
24439        {
24440            self.advance();
24441            recursive = true;
24442        }
24443        let mut ctes = Vec::new();
24444        loop {
24445            let name = self.expect_ident_like()?;
24446            // v4.22: optional column-name list — `WITH t(a,b,c) AS ...`.
24447            // PG uses these to rename the body's output columns; we
24448            // do the same below by overriding `columns[i].name`.
24449            let column_overrides: Vec<String> = if matches!(self.peek(), Token::LParen) {
24450                self.advance();
24451                let mut names = Vec::new();
24452                loop {
24453                    names.push(self.expect_ident_like()?);
24454                    if matches!(self.peek(), Token::Comma) {
24455                        self.advance();
24456                        continue;
24457                    }
24458                    break;
24459                }
24460                if !matches!(self.peek(), Token::RParen) {
24461                    return Err(self.err(format!(
24462                        "expected ')' to close CTE column list, got {:?}",
24463                        self.peek()
24464                    )));
24465                }
24466                self.advance();
24467                names
24468            } else {
24469                Vec::new()
24470            };
24471            // AS is a reserved Token::As (used by SELECT-item / FROM
24472            // aliasing) — handle it specially rather than as a bare
24473            // ident.
24474            if !matches!(self.peek(), Token::As) {
24475                return Err(self.err(format!(
24476                    "expected AS after CTE name {name:?}, got {:?}",
24477                    self.peek()
24478                )));
24479            }
24480            self.advance();
24481            // v7.37.17 (17.6 siblings) — PG 12+ `AS [NOT]
24482            // MATERIALIZED` optimizer hints. SPG materialises every
24483            // CTE, so both spellings are accepted and absorbed.
24484            if matches!(self.peek(), Token::Not) {
24485                self.advance(); // NOT
24486                if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
24487                    if s.eq_ignore_ascii_case("materialized"))
24488                {
24489                    self.advance();
24490                } else {
24491                    return Err(self.err(format!(
24492                        "expected MATERIALIZED after AS NOT, got {:?}",
24493                        self.peek()
24494                    )));
24495                }
24496            } else if matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s)
24497                if s.eq_ignore_ascii_case("materialized"))
24498            {
24499                self.advance();
24500            }
24501            if !matches!(self.peek(), Token::LParen) {
24502                return Err(self.err(format!(
24503                    "expected '(' after AS in WITH clause, got {:?}",
24504                    self.peek()
24505                )));
24506            }
24507            self.advance();
24508            // v7.37.43-T4.4 — accept INSERT / UPDATE / DELETE (with
24509            // RETURNING) as the CTE body in addition to SELECT.
24510            // PG writable CTE semantics. UPDATE / DELETE come in as
24511            // bare Idents (lexer keeps SELECT / INSERT as reserved
24512            // tokens but treats the rest of DML as case-insensitive
24513            // idents).
24514            let is_update_kw = matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("update"));
24515            let is_delete_kw = matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("delete"));
24516            let is_merge_kw = matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("merge"));
24517            let body = match self.peek() {
24518                Token::Select => {
24519                    let inner = self.parse_select_stmt()?;
24520                    let Statement::Select(s) = inner else {
24521                        unreachable!("parse_select_stmt returns Select");
24522                    };
24523                    crate::ast::CteBody::Select(s)
24524                }
24525                // v7.39 (round 869) — `WITH x AS (TABLE t)`. PG spells
24526                // `SELECT * FROM t` this way and accepts it wherever a
24527                // SELECT goes, so the CTE body dispatch needs its own
24528                // arm: this match is keyed on the FIRST token, and
24529                // `Token::Table` fell through to a tail that then
24530                // rejected what it got. `parse_table_shorthand` has
24531                // returned a desugared SelectStatement since the
24532                // shorthand landed — only the routing was missing.
24533                // Round 868 found this by putting the shorthand in a
24534                // subquery; every earlier check used a top-level form.
24535                // v7.39 (round 869) — `WITH x AS (TABLE t)`. PG spells
24536                // `SELECT * FROM t` this way and accepts it wherever a
24537                // SELECT goes, so the CTE body dispatch needs its own
24538                // arm: this match is keyed on the FIRST token, and
24539                // `Token::Table` fell through to a tail that rejected
24540                // what it got. `parse_table_shorthand` has returned a
24541                // desugared SelectStatement since the shorthand landed —
24542                // only the routing was missing, here and in the derived
24543                // table's second-token gate. Round 868 found both by
24544                // putting the shorthand in a subquery; every earlier
24545                // check had used a top-level form.
24546                Token::Table
24547                    if matches!(
24548                        self.tokens.get(self.pos + 1),
24549                        Some(Token::Ident(_) | Token::QuotedIdent(_))
24550                    ) =>
24551                {
24552                    let mut head = self.parse_table_shorthand()?;
24553                    self.parse_setop_chain_into(&mut head)?;
24554                    self.parse_select_tail_into(&mut head)?;
24555                    crate::ast::CteBody::Select(head)
24556                }
24557                // v7.37.17 (17.6 siblings) — VALUES as a CTE body:
24558                // WITH t(a) AS (VALUES (1), (2)) … lowers through
24559                // the shared rows helper onto a Select body.
24560                Token::Values => {
24561                    self.advance(); // VALUES
24562                    let mut head = self.parse_values_rows_body()?;
24563                    // A VALUES seed can head a set-operation chain —
24564                    // WITH RECURSIVE t(n) AS (VALUES(1) UNION ALL
24565                    // SELECT n+1 FROM t …). Attach any trailing
24566                    // UNION / INTERSECT / EXCEPT peers so the
24567                    // recursive-CTE body parses like the SELECT seed.
24568                    self.parse_setop_chain_into(&mut head)?;
24569                    crate::ast::CteBody::Select(head)
24570                }
24571                Token::Insert => {
24572                    let inner = self.parse_one_statement()?;
24573                    let Statement::Insert(s) = inner else {
24574                        unreachable!("Token::Insert routes to Insert");
24575                    };
24576                    crate::ast::CteBody::Insert(alloc::boxed::Box::new(s))
24577                }
24578                _ if is_update_kw => {
24579                    let inner = self.parse_one_statement()?;
24580                    let Statement::Update(s) = inner else {
24581                        return Err(
24582                            self.err(format!("expected UPDATE inside WITH (…), got {inner:?}"))
24583                        );
24584                    };
24585                    crate::ast::CteBody::Update(alloc::boxed::Box::new(s))
24586                }
24587                _ if is_delete_kw => {
24588                    let inner = self.parse_one_statement()?;
24589                    let Statement::Delete(s) = inner else {
24590                        return Err(
24591                            self.err(format!("expected DELETE inside WITH (…), got {inner:?}"))
24592                        );
24593                    };
24594                    crate::ast::CteBody::Delete(alloc::boxed::Box::new(s))
24595                }
24596                // v7.39 (round 149) — PG 17 allows MERGE as a
24597                // data-modifying CTE body.
24598                _ if is_merge_kw => {
24599                    let inner = self.parse_one_statement()?;
24600                    let Statement::Merge(s) = inner else {
24601                        return Err(
24602                            self.err(format!("expected MERGE inside WITH (…), got {inner:?}"))
24603                        );
24604                    };
24605                    crate::ast::CteBody::Merge(alloc::boxed::Box::new(s))
24606                }
24607                // v7.39 (round 151) — a CTE body may itself be
24608                // WITH-headed (PG grammar: PreparableStmt carries its
24609                // own with_clause). The nested statement keeps its own
24610                // ctes; the modifying-CTE-at-top-level rule is enforced
24611                // at execution.
24612                Token::Ident(s) if s.eq_ignore_ascii_case("with") => {
24613                    self.advance(); // WITH
24614                    match self.parse_with_cte_then_select()? {
24615                        Statement::Select(s) => crate::ast::CteBody::Select(s),
24616                        Statement::Insert(s) => {
24617                            crate::ast::CteBody::Insert(alloc::boxed::Box::new(s))
24618                        }
24619                        Statement::Update(s) => {
24620                            crate::ast::CteBody::Update(alloc::boxed::Box::new(s))
24621                        }
24622                        Statement::Delete(s) => {
24623                            crate::ast::CteBody::Delete(alloc::boxed::Box::new(s))
24624                        }
24625                        Statement::Merge(s) => {
24626                            crate::ast::CteBody::Merge(alloc::boxed::Box::new(s))
24627                        }
24628
24629                        other => {
24630                            return Err(self.err(format!(
24631                                "WITH body must be SELECT / INSERT / UPDATE / DELETE / MERGE, got {other:?}"
24632                            )));
24633                        }
24634                    }
24635                }
24636                other => {
24637                    return Err(self.err(format!(
24638                        "WITH body must be SELECT / INSERT / UPDATE / DELETE / MERGE, got {other:?}"
24639                    )));
24640                }
24641            };
24642            if !matches!(self.peek(), Token::RParen) {
24643                return Err(self.err(format!(
24644                    "expected ')' after CTE body, got {:?}",
24645                    self.peek()
24646                )));
24647            }
24648            self.advance();
24649            // v7.38 (read01 U16) — optional SEARCH / CYCLE on a recursive
24650            // CTE, desugared into extra body columns by the engine.
24651            let search = self.parse_cte_search_clause()?;
24652            let cycle = self.parse_cte_cycle_clause()?;
24653            let mut cte = crate::ast::Cte {
24654                name,
24655                body,
24656                recursive,
24657                column_overrides,
24658                search,
24659                cycle,
24660            };
24661            self.validate_recursive_cte(&cte)?;
24662            self.desugar_cte_search_cycle(&mut cte)?;
24663            ctes.push(cte);
24664            if matches!(self.peek(), Token::Comma) {
24665                self.advance();
24666                continue;
24667            }
24668            break;
24669        }
24670        // v7.37.43-T4.4 — the outer body may be SELECT (classical),
24671        // or INSERT / UPDATE / DELETE (writable CTE outer). Attach
24672        // the parsed CTEs to whichever statement the body produces.
24673        let outer_is_update = matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("update"));
24674        let outer_is_delete = matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("delete"));
24675        let outer_is_merge = matches!(self.peek(), Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("merge"));
24676        match self.peek() {
24677            Token::Select => {
24678                let body_stmt = self.parse_select_stmt()?;
24679                let Statement::Select(mut body) = body_stmt else {
24680                    unreachable!()
24681                };
24682                body.ctes = ctes;
24683                Ok(Statement::Select(body))
24684            }
24685            Token::Insert => {
24686                let body_stmt = self.parse_one_statement()?;
24687                let Statement::Insert(mut body) = body_stmt else {
24688                    unreachable!()
24689                };
24690                body.ctes = ctes;
24691                Ok(Statement::Insert(body))
24692            }
24693            _ if outer_is_update => {
24694                let body_stmt = self.parse_one_statement()?;
24695                let Statement::Update(mut body) = body_stmt else {
24696                    return Err(self.err(format!("expected UPDATE after WITH clause")));
24697                };
24698                body.ctes = ctes;
24699                Ok(Statement::Update(body))
24700            }
24701            _ if outer_is_delete => {
24702                let body_stmt = self.parse_one_statement()?;
24703                let Statement::Delete(mut body) = body_stmt else {
24704                    return Err(self.err(format!("expected DELETE after WITH clause")));
24705                };
24706                body.ctes = ctes;
24707                Ok(Statement::Delete(body))
24708            }
24709            // v7.39 (round 149) — PG 15 allows a WITH clause on MERGE;
24710            // WITH RECURSIVE is rejected with PG's exact message
24711            // (parse analysis, transformWithClause).
24712            _ if outer_is_merge => {
24713                if recursive {
24714                    return Err(self.err(String::from(
24715                        "WITH RECURSIVE is not supported for MERGE statement",
24716                    )));
24717                }
24718                let body_stmt = self.parse_one_statement()?;
24719                let Statement::Merge(mut body) = body_stmt else {
24720                    return Err(self.err(format!("expected MERGE after WITH clause")));
24721                };
24722                body.ctes = ctes;
24723                Ok(Statement::Merge(body))
24724            }
24725            other => Err(self.err(format!(
24726                "expected SELECT / INSERT / UPDATE / DELETE / MERGE after WITH clause, got {other:?}"
24727            ))),
24728        }
24729    }
24730
24731    /// v4.10: parse `EXISTS (SELECT ...)`. Caller (`parse_atom`)
24732    /// already consumed the leading `EXISTS` ident via
24733    /// `self.advance()`.
24734    /// v7.13.0 — parse the rest of a `CASE … END` expression after
24735    /// the leading `CASE` ident has been consumed (mailrs round-5
24736    /// G9). Supports both the searched form
24737    /// (`CASE WHEN cond THEN val …`) and the simple form
24738    /// (`CASE operand WHEN val THEN val …`).
24739    fn parse_case_atom(&mut self) -> Result<Expr, ParseError> {
24740        // Disambiguate searched vs simple form: if the next token
24741        // is `WHEN`, we're in the searched form. Otherwise the
24742        // intervening expression is the operand.
24743        let operand = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("when")) {
24744            None
24745        } else {
24746            Some(Box::new(self.parse_expr(0)?))
24747        };
24748        let mut branches: Vec<(Expr, Expr)> = Vec::new();
24749        loop {
24750            match self.peek() {
24751                Token::Ident(s) if s.eq_ignore_ascii_case("when") => {
24752                    self.advance();
24753                    let cond = self.parse_expr(0)?;
24754                    match self.peek() {
24755                        Token::Ident(t) if t.eq_ignore_ascii_case("then") => {
24756                            self.advance();
24757                        }
24758                        other => {
24759                            return Err(self.err(alloc::format!(
24760                                "expected THEN after CASE WHEN <expr>, got {other:?}"
24761                            )));
24762                        }
24763                    }
24764                    let value = self.parse_expr(0)?;
24765                    branches.push((cond, value));
24766                }
24767                _ => break,
24768            }
24769        }
24770        if branches.is_empty() {
24771            return Err(self.err("CASE requires at least one WHEN … THEN … branch".into()));
24772        }
24773        let else_branch = if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("else"))
24774        {
24775            self.advance();
24776            Some(Box::new(self.parse_expr(0)?))
24777        } else {
24778            None
24779        };
24780        match self.peek() {
24781            Token::Ident(s) if s.eq_ignore_ascii_case("end") => {
24782                self.advance();
24783            }
24784            other => {
24785                return Err(self.err(alloc::format!(
24786                    "expected END to close CASE expression, got {other:?}"
24787                )));
24788            }
24789        }
24790        Ok(Expr::Case {
24791            operand,
24792            branches,
24793            else_branch,
24794        })
24795    }
24796
24797    /// v7.39 (round 151) — nested `WITH … SELECT …` in a subquery /
24798    /// query-source position (EXISTS / IN / INSERT source / CTE body /
24799    /// view body). Caller consumed the WITH keyword. Only a SELECT
24800    /// outer is grammatical here; the data-modifying-CTE-at-top-level
24801    /// rule (PG 0A000) is enforced at execution, where the SQLSTATE
24802    /// maps correctly.
24803    fn parse_nested_with_select(&mut self) -> Result<crate::ast::SelectStatement, ParseError> {
24804        let inner = self.parse_with_cte_then_select()?;
24805        match inner {
24806            Statement::Select(s) => Ok(s),
24807            other => Err(self.err(format!(
24808                "expected SELECT after WITH in a subquery, got {other:?}"
24809            ))),
24810        }
24811    }
24812
24813    /// True when the next token is the (unquoted) WITH keyword. WITH is
24814    /// reserved in PG, so a bare `with` can never be a column reference
24815    /// in these positions; a quoted `"with"` stays an identifier.
24816    fn peek_is_with_kw(&self) -> bool {
24817        matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("with"))
24818    }
24819
24820    /// v7.39 (round 153) — the `ANY / ALL ( [WITH …] SELECT … )` body.
24821    /// `#[inline(never)]` keeps the large SelectStatement temporaries
24822    /// off parse_expr's recursive frame (the nesting-budget stack
24823    /// cliff — see the round-153 gate regression).
24824    #[inline(never)]
24825    fn parse_any_all_select_body(&mut self) -> Result<crate::ast::SelectStatement, ParseError> {
24826        if self.peek_is_with_kw() {
24827            self.advance();
24828            self.parse_nested_with_select()
24829        } else {
24830            match self.parse_select_stmt()? {
24831                Statement::Select(s) => Ok(s),
24832                other => Err(self.err(alloc::format!(
24833                    "expected SELECT inside ANY/ALL, got {other:?}"
24834                ))),
24835            }
24836        }
24837    }
24838
24839    fn parse_exists_atom(&mut self, negated: bool) -> Result<Expr, ParseError> {
24840        if !matches!(self.peek(), Token::LParen) {
24841            return Err(self.err(format!("expected '(' after EXISTS, got {:?}", self.peek())));
24842        }
24843        self.advance();
24844        // v7.39 (round 151) — `EXISTS (WITH … SELECT …)` is legal PG.
24845        let s = if self.peek_is_with_kw() {
24846            self.advance();
24847            self.parse_nested_with_select()?
24848        } else {
24849            let inner = self.parse_select_stmt()?;
24850            let Statement::Select(s) = inner else {
24851                unreachable!("parse_select_stmt returns Select")
24852            };
24853            s
24854        };
24855        if !matches!(self.peek(), Token::RParen) {
24856            return Err(self.err(format!(
24857                "expected ')' after EXISTS-subquery, got {:?}",
24858                self.peek()
24859            )));
24860        }
24861        self.advance();
24862        Ok(Expr::Exists {
24863            subquery: Box::new(s),
24864            negated,
24865        })
24866    }
24867
24868    fn parse_in_tail(&mut self, expr: Expr, negated: bool) -> Result<Expr, ParseError> {
24869        self.advance(); // IN
24870        if !matches!(self.peek(), Token::LParen) {
24871            return Err(self.err(format!("expected '(' after IN, got {:?}", self.peek())));
24872        }
24873        self.advance();
24874        // v4.10: `IN (SELECT ...)` — subquery branch. v7.39 (round 151)
24875        // also accepts a WITH-headed subquery (`IN (WITH … SELECT …)`).
24876        if matches!(self.peek(), Token::Select) || self.peek_is_with_kw() {
24877            let s = if self.peek_is_with_kw() {
24878                self.advance();
24879                self.parse_nested_with_select()?
24880            } else {
24881                let inner = self.parse_select_stmt()?;
24882                let Statement::Select(s) = inner else {
24883                    unreachable!("parse_select_stmt always returns Statement::Select")
24884                };
24885                s
24886            };
24887            if !matches!(self.peek(), Token::RParen) {
24888                return Err(self.err(format!(
24889                    "expected ')' after IN-subquery, got {:?}",
24890                    self.peek()
24891                )));
24892            }
24893            self.advance();
24894            return Ok(Expr::InSubquery {
24895                expr: Box::new(expr),
24896                subquery: Box::new(s),
24897                negated,
24898            });
24899        }
24900        let mut elements = Vec::new();
24901        if !matches!(self.peek(), Token::RParen) {
24902            loop {
24903                elements.push(self.parse_expr(0)?);
24904                match self.peek() {
24905                    Token::Comma => {
24906                        self.advance();
24907                    }
24908                    Token::RParen => break,
24909                    other => {
24910                        return Err(
24911                            self.err(format!("expected ',' or ')' in IN list, got {other:?}"))
24912                        );
24913                    }
24914                }
24915            }
24916        }
24917        self.advance(); // ')'
24918        // v7.30.2 (mailrs round-25) — flat InList node instead of a
24919        // left-deep OR-Eq chain: chain depth scaled with the element
24920        // count and overflowed the stack (eval + drop are recursive).
24921        if elements.is_empty() {
24922            return Ok(maybe_not(Expr::Literal(Literal::Bool(false)), negated));
24923        }
24924        Ok(Expr::InList {
24925            expr: Box::new(expr),
24926            list: elements,
24927            negated,
24928        })
24929    }
24930
24931    /// Parse a pgvector array literal `[ x1, x2, ... ]`. The opening `[` is
24932    /// already consumed by the caller. Elements must be numeric literals
24933    /// (with optional unary `-`); any compound expression is rejected at
24934    /// parse time so the runtime never needs to evaluate inside a vector.
24935    /// `EXTRACT(<field> FROM <source>)`. The dispatching `parse_atom`
24936    /// has already consumed the `EXTRACT` token before calling us —
24937    /// we pick up at the opening `(`.
24938    /// v7.17.0 Phase 2.2 — MySQL `MATCH(col [, col ...]) AGAINST
24939    /// (expr [IN BOOLEAN MODE | IN NATURAL LANGUAGE MODE
24940    /// [WITH QUERY EXPANSION]])`. Rewritten in-place to a
24941    /// per-column OR-fold of
24942    /// `to_tsvector('simple', col) @@ plainto_tsquery('simple',
24943    /// term)` so the existing FTS evaluator handles semantics.
24944    ///
24945    /// The mode modifier is accepted-and-ignored at v7.17 — all
24946    /// modes map to the same `plainto_tsquery` rewrite. Boolean-
24947    /// mode operators (`+foo -bar`) would need their own parser
24948    /// (Phase 2.2c); customers who hit them today already get a
24949    /// correct lexeme-match against the bare term, only without
24950    /// the +/- precedence the customer asked for.
24951    fn parse_match_against_atom(&mut self) -> Result<Expr, ParseError> {
24952        // Already at `MATCH`-consumed position; the dispatcher
24953        // confirmed the next token is `(`.
24954        if !matches!(self.peek(), Token::LParen) {
24955            return Err(self.err(alloc::format!(
24956                "expected '(' after MATCH, got {:?}",
24957                self.peek()
24958            )));
24959        }
24960        self.advance();
24961        let mut cols: Vec<Expr> = Vec::new();
24962        loop {
24963            cols.push(self.parse_expr(0)?);
24964            match self.peek() {
24965                Token::Comma => {
24966                    self.advance();
24967                }
24968                Token::RParen => break,
24969                other => {
24970                    return Err(self.err(alloc::format!(
24971                        "expected ',' or ')' in MATCH column list, got {other:?}"
24972                    )));
24973                }
24974            }
24975        }
24976        self.advance(); // ')'
24977        // Expect AGAINST.
24978        match self.peek() {
24979            Token::Ident(s) | Token::QuotedIdent(s) if s.eq_ignore_ascii_case("against") => {
24980                self.advance();
24981            }
24982            other => {
24983                return Err(self.err(alloc::format!(
24984                    "expected AGAINST after MATCH column list, got {other:?}"
24985                )));
24986            }
24987        }
24988        if !matches!(self.peek(), Token::LParen) {
24989            return Err(self.err(alloc::format!(
24990                "expected '(' after AGAINST, got {:?}",
24991                self.peek()
24992            )));
24993        }
24994        self.advance();
24995        // Read AGAINST's argument as a single primary token —
24996        // string literal, placeholder, or column-ref ident. We
24997        // can't call `parse_expr` / `parse_unary` here because
24998        // the postfix chain inside `parse_atom` would greedily
24999        // fold a trailing `IN BOOLEAN MODE` as `expr IN (...)`
25000        // and fail at "expected '(' after IN". Customers always
25001        // write a literal or bound parameter in AGAINST, so this
25002        // restriction is non-blocking; the error path explains
25003        // the limit if a more complex expression shows up.
25004        let term = match self.advance() {
25005            Token::String(s) => Expr::Literal(crate::ast::Literal::String(s)),
25006            Token::Placeholder(n) => Expr::Placeholder(n),
25007            Token::Ident(s) | Token::QuotedIdent(s) => Expr::Column(crate::ast::ColumnName {
25008                qualifier: None,
25009                name: s,
25010            }),
25011            other => {
25012                return Err(self.err(alloc::format!(
25013                    "MATCH ... AGAINST(<term>) expects a string literal, \
25014                     bound parameter, or column ref, got {other:?}"
25015                )));
25016            }
25017        };
25018        // Optional mode tail — accept-and-ignore at v7.17:
25019        //   IN NATURAL LANGUAGE MODE [WITH QUERY EXPANSION]
25020        //   IN BOOLEAN MODE
25021        //   WITH QUERY EXPANSION
25022        loop {
25023            match self.peek() {
25024                // IN lexes as a reserved Token::In, not an ident,
25025                // so it gets its own arm.
25026                Token::In => {
25027                    self.advance();
25028                }
25029                Token::Ident(s) | Token::QuotedIdent(s)
25030                    if s.eq_ignore_ascii_case("natural")
25031                        || s.eq_ignore_ascii_case("language")
25032                        || s.eq_ignore_ascii_case("boolean")
25033                        || s.eq_ignore_ascii_case("mode")
25034                        || s.eq_ignore_ascii_case("with")
25035                        || s.eq_ignore_ascii_case("query")
25036                        || s.eq_ignore_ascii_case("expansion") =>
25037                {
25038                    self.advance();
25039                }
25040                _ => break,
25041            }
25042        }
25043        if !matches!(self.peek(), Token::RParen) {
25044            return Err(self.err(alloc::format!(
25045                "expected ')' to close AGAINST, got {:?}",
25046                self.peek()
25047            )));
25048        }
25049        self.advance();
25050        // Build per-column `to_tsvector('simple', col) @@
25051        // plainto_tsquery('simple', term)` and OR-fold.
25052        let simple_lit = || Expr::Literal(crate::ast::Literal::String(String::from("simple")));
25053        let plainto = Expr::FunctionCall {
25054            name: String::from("plainto_tsquery"),
25055            args: alloc::vec![simple_lit(), term.clone()],
25056        };
25057        let mut folded: Option<Expr> = None;
25058        for col in cols {
25059            let to_tsv = Expr::FunctionCall {
25060                name: String::from("to_tsvector"),
25061                args: alloc::vec![simple_lit(), col],
25062            };
25063            let leaf = Expr::Binary {
25064                lhs: Box::new(to_tsv),
25065                op: crate::ast::BinOp::TsMatch,
25066                rhs: Box::new(plainto.clone()),
25067            };
25068            folded = Some(match folded {
25069                None => leaf,
25070                Some(prev) => Expr::Binary {
25071                    lhs: Box::new(prev),
25072                    op: crate::ast::BinOp::Or,
25073                    rhs: Box::new(leaf),
25074                },
25075            });
25076        }
25077        match folded {
25078            Some(e) => Ok(e),
25079            None => Err(self.err(String::from(
25080                "MATCH(...) AGAINST(...) requires at least one column",
25081            ))),
25082        }
25083    }
25084
25085    fn parse_extract_atom(&mut self) -> Result<Expr, ParseError> {
25086        if !matches!(self.peek(), Token::LParen) {
25087            return Err(self.err(format!("expected '(' after EXTRACT, got {:?}", self.peek())));
25088        }
25089        self.advance();
25090        let field_name = self.expect_ident_like()?;
25091        let field = match field_name.to_ascii_lowercase().as_str() {
25092            // PG accepts the plural spellings (years/months/…/millenniums) as
25093            // aliases for the singular fields — its datetime unit table has both.
25094            // (quarter has no plural; dow/doy/isoyear/epoch/julian likewise.)
25095            "year" | "years" => ExtractField::Year,
25096            "month" | "months" => ExtractField::Month,
25097            "day" | "days" => ExtractField::Day,
25098            "hour" | "hours" => ExtractField::Hour,
25099            "minute" | "minutes" => ExtractField::Minute,
25100            "second" | "seconds" => ExtractField::Second,
25101            "microsecond" | "microseconds" => ExtractField::Microsecond,
25102            "epoch" => ExtractField::Epoch,
25103            "dow" => ExtractField::Dow,
25104            "isodow" => ExtractField::Isodow,
25105            "doy" => ExtractField::Doy,
25106            "week" | "weeks" => ExtractField::Week,
25107            "isoyear" => ExtractField::Isoyear,
25108            "quarter" => ExtractField::Quarter,
25109            "decade" | "decades" => ExtractField::Decade,
25110            "century" | "centuries" => ExtractField::Century,
25111            "millennium" | "millenniums" | "millennia" => ExtractField::Millennium,
25112            "julian" => ExtractField::Julian,
25113            "millisecond" | "milliseconds" => ExtractField::Millisecond,
25114            "timezone" => ExtractField::Timezone,
25115            "timezone_hour" => ExtractField::TimezoneHour,
25116            "timezone_minute" => ExtractField::TimezoneMinute,
25117            // v7.39 (round 253) — PG resolves EXTRACT fields at runtime and
25118            // reports an unknown one with the source type (22023); carry the
25119            // raw name so eval can word it.
25120            other => ExtractField::Other(alloc::string::String::from(other)),
25121        };
25122        if !matches!(self.peek(), Token::From) {
25123            return Err(self.err(format!(
25124                "expected FROM after EXTRACT field, got {:?}",
25125                self.peek()
25126            )));
25127        }
25128        self.advance();
25129        let source = self.parse_expr(0)?;
25130        if !matches!(self.peek(), Token::RParen) {
25131            return Err(self.err(format!(
25132                "expected ')' to close EXTRACT, got {:?}",
25133                self.peek()
25134            )));
25135        }
25136        self.advance();
25137        Ok(Expr::Extract {
25138            field,
25139            source: Box::new(source),
25140        })
25141    }
25142
25143    /// `INTERVAL '<n> <unit> [<n> <unit> ...]'` — the `INTERVAL` keyword
25144    /// is already consumed; we expect a single string literal next and
25145    /// resolve it into `Literal::Interval` at parse time so the engine
25146    /// never has to re-tokenise inside the string.
25147    /// The unquoted count of a MySQL `INTERVAL <n> <UNIT>`, when the
25148    /// tokens ahead really are one. A quoted count (`INTERVAL '2' DAY`)
25149    /// is the SQL-standard form and is left to the path below.
25150    fn peek_unquoted_interval_count(&self) -> Option<(alloc::string::String, usize)> {
25151        // A negative count lexes as `-` then the number (`INTERVAL -1 DAY`).
25152        let (offset, sign) = match self.peek() {
25153            Token::Minus => (1, "-"),
25154            _ => (0, ""),
25155        };
25156        let Some(Token::Integer(n)) = self.tokens.get(self.pos + offset) else {
25157            return None;
25158        };
25159        self.tokens
25160            .get(self.pos + offset + 1)
25161            .filter(|t| mysql_interval_unit(t).is_some())?;
25162        Some((alloc::format!("{sign}{n}"), offset + 1))
25163    }
25164
25165    /// v7.39 (round 422) — is the parenthesised group starting at the CURRENT
25166    /// `(` a single quantity followed by a time unit (`INTERVAL (1+1) DAY`),
25167    /// rather than the argument list of MySQL's `INTERVAL(N, N1, …)` function?
25168    ///
25169    /// Scans `self.tokens` by index and consumes NOTHING. Round 409 decided
25170    /// this by parsing the group and then restoring `self.pos` — which could
25171    /// never have worked, because `advance()` DESTROYS the token it returns
25172    /// (`mem::replace(.., Eof)`); the restore yielded a stream of Eof. It was
25173    /// inert only because both branches errored back then.
25174    fn interval_paren_is_quantity(&self) -> bool {
25175        let mut depth = 0usize;
25176        let mut saw_top_level_comma = false;
25177        let mut i = self.pos;
25178        while let Some(tok) = self.tokens.get(i) {
25179            match tok {
25180                Token::LParen => depth += 1,
25181                Token::RParen => {
25182                    depth = depth.saturating_sub(1);
25183                    if depth == 0 {
25184                        return !saw_top_level_comma
25185                            && mysql_interval_unit(self.tokens.get(i + 1).unwrap_or(&Token::Eof))
25186                                .is_some();
25187                    }
25188                }
25189                // A comma directly inside the outermost parens means the
25190                // argument list of the INTERVAL() function.
25191                Token::Comma if depth == 1 => saw_top_level_comma = true,
25192                Token::Eof => return false,
25193                _ => {}
25194            }
25195            i += 1;
25196        }
25197        false
25198    }
25199
25200    fn parse_interval_atom(&mut self) -> Result<Expr, ParseError> {
25201        // v7.39 (round 409) — MySQL's `INTERVAL(N, N1, N2, …)` function
25202        // (the index of the last Ni ≤ N), distinct from the interval literal.
25203        // `INTERVAL (` is ambiguous with `INTERVAL (expr) UNIT`, so the shape
25204        // is decided by a non-destructive lookahead (round 422) before either
25205        // branch consumes anything. MySQL only.
25206        if self.mysql_dialect
25207            && matches!(self.peek(), Token::LParen)
25208            && !self.interval_paren_is_quantity()
25209        {
25210            self.advance(); // (
25211            let mut args = Vec::new();
25212            if !matches!(self.peek(), Token::RParen) {
25213                loop {
25214                    args.push(self.parse_expr(0)?);
25215                    if matches!(self.peek(), Token::Comma) {
25216                        self.advance();
25217                        continue;
25218                    }
25219                    break;
25220                }
25221            }
25222            if !matches!(self.peek(), Token::RParen) {
25223                return Err(self.err(alloc::format!(
25224                    "expected ')' after INTERVAL() arguments, got {:?}",
25225                    self.peek()
25226                )));
25227            }
25228            self.advance(); // )
25229            return Ok(Expr::FunctionCall {
25230                name: alloc::string::String::from("interval"),
25231                args,
25232            });
25233        }
25234        // v7.39 (round 350, M7) — MySQL's `INTERVAL <n> <UNIT>`, with the
25235        // number UNQUOTED: `DATE_ADD(d, INTERVAL 1 MONTH)`,
25236        // `d + INTERVAL 90 MINUTE`, `INTERVAL -1 DAY`. It is how MySQL
25237        // writes every date arithmetic there is, and it did not parse at
25238        // all. PG rejects the unquoted form outright (`syntax error at or
25239        // near "1"`, measured), so it is taken only in the MySQL dialect —
25240        // PG's own `INTERVAL '1' DAY` is untouched below.
25241        if self.mysql_dialect
25242            && let Some((text, consume)) = self.peek_unquoted_interval_count()
25243        {
25244            for _ in 0..consume {
25245                self.advance(); // the optional `-` and the number
25246            }
25247            let Some(unit) = mysql_interval_unit(self.peek()) else {
25248                return Err(self.err(alloc::format!(
25249                    "expected an interval unit after INTERVAL {text}, got {:?}",
25250                    self.peek()
25251                )));
25252            };
25253            self.advance(); // the unit
25254            let (months, days, micros) = scale_mysql_interval(&text, unit)
25255                .ok_or_else(|| self.err(alloc::format!("cannot read INTERVAL {text} {unit}")))?;
25256            return Ok(Expr::Literal(Literal::Interval {
25257                months,
25258                days,
25259                micros,
25260                // The canonical rendering, so Display round-trips into a
25261                // form both dialects read back.
25262                text: alloc::format!("{text} {unit}"),
25263            }));
25264        }
25265        // v7.39 (round 422) — MySQL's interval QUANTITY may be any expression,
25266        // not just a literal: `DATE_ADD(d, INTERVAL n DAY)`,
25267        // `d + INTERVAL n*2 DAY`, `INTERVAL (1+1) DAY`, `INTERVAL ABS(-5) DAY`.
25268        // Those cannot fold into a compile-time `Literal::Interval`, so they
25269        // lower onto the existing `make_interval(y, mo, w, d, h, mi, s)`
25270        // builtin, which builds the value at run time (and yields NULL for a
25271        // NULL quantity, as MariaDB does). The literal path above still folds
25272        // the constant case — it is cheaper and round-trips through Display.
25273        //
25274        // Guarded off a String operand so PG's own `INTERVAL '1 day'` (and
25275        // MySQL's quoted spelling) keep the qualifier path below.
25276        if self.mysql_dialect && !matches!(self.peek(), Token::String(_)) {
25277            let qty = self.parse_expr(0)?;
25278            let Some(unit) = mysql_interval_unit(self.peek()) else {
25279                return Err(self.err(alloc::format!(
25280                    "expected an interval unit after INTERVAL <expr>, got {:?}",
25281                    self.peek()
25282                )));
25283            };
25284            self.advance(); // the unit
25285            return Ok(make_interval_call(qty, unit));
25286        }
25287        let tok = self.advance();
25288        let Token::String(text) = tok else {
25289            return Err(self.err(format!(
25290                "expected string literal after INTERVAL, got {tok:?}"
25291            )));
25292        };
25293        // v7.39 (read01 round 102) — SQL-standard trailing field qualifier
25294        // `<FIELD> [TO <FIELD>]` (`INTERVAL '2' YEAR`, `INTERVAL '1-6' YEAR TO
25295        // MONTH`, `INTERVAL '1 2:03:04' DAY TO SECOND`). It sets which field a
25296        // bare number means and the leading/trailing precision.
25297        let field1 = interval_field_of(self.peek());
25298        let qualifier = if let Some(f1) = field1 {
25299            self.advance();
25300            let f2 = if matches!(self.peek(), Token::To) {
25301                self.advance();
25302                let Some(f) = interval_field_of(self.peek()) else {
25303                    return Err(self.err(format!(
25304                        "expected an interval field after TO, got {:?}",
25305                        self.peek()
25306                    )));
25307                };
25308                self.advance();
25309                Some(f)
25310            } else {
25311                None
25312            };
25313            Some((f1, f2))
25314        } else {
25315            None
25316        };
25317        let (months, days, micros) = match qualifier {
25318            Some(q) => interpret_qualified_interval(&text, q),
25319            None => parse_interval_text(&text),
25320        }
25321        .ok_or_else(|| ParseError {
25322            message: format!(
25323                "cannot parse INTERVAL {text:?}; \
25324                     expected `<n> <unit> [<n> <unit> ...]` with units \
25325                     microsecond[s], millisecond[s], second[s], minute[s], \
25326                     hour[s], day[s], week[s], month[s], year[s]"
25327            ),
25328            token_pos: self.consumed_pos(),
25329        })?;
25330        Ok(Expr::Literal(Literal::Interval {
25331            months,
25332            days,
25333            micros,
25334            text,
25335        }))
25336    }
25337
25338    /// v7.38 (read01, T10) — parse a bracketed sub-array `[e, e, …]` inside an
25339    /// `ARRAY[...]` constructor, recursing on further nested `[...]` so
25340    /// `ARRAY[[1,2],[3,4]]` (and deeper) becomes nested `Expr::Array` rather
25341    /// than a pgvector literal.
25342    fn parse_array_bracket_body(&mut self) -> Result<Expr, ParseError> {
25343        self.advance(); // consume `[`
25344        let mut items: Vec<Expr> = Vec::new();
25345        if !matches!(self.peek(), Token::RBracket) {
25346            loop {
25347                if matches!(self.peek(), Token::LBracket) {
25348                    items.push(self.parse_array_bracket_body()?);
25349                } else {
25350                    items.push(self.parse_expr(0)?);
25351                }
25352                match self.peek() {
25353                    Token::Comma => {
25354                        self.advance();
25355                    }
25356                    Token::RBracket => break,
25357                    other => {
25358                        return Err(self.err(alloc::format!(
25359                            "expected ',' or ']' in array literal, got {other:?}"
25360                        )));
25361                    }
25362                }
25363            }
25364        }
25365        self.advance(); // consume `]`
25366        Ok(Expr::Array(items))
25367    }
25368
25369    fn parse_vector_literal_body(&mut self) -> Result<Expr, ParseError> {
25370        let mut elems = Vec::new();
25371        if matches!(self.peek(), Token::RBracket) {
25372            self.advance();
25373            return Ok(Expr::Literal(Literal::Vector(elems)));
25374        }
25375        loop {
25376            let e = self.parse_expr(0)?;
25377            let x = extract_numeric_literal(&e).ok_or_else(|| ParseError {
25378                message: format!("vector element must be a numeric literal, got {e:?}"),
25379                token_pos: self.pos,
25380            })?;
25381            elems.push(x);
25382            match self.peek() {
25383                Token::Comma => {
25384                    self.advance();
25385                }
25386                Token::RBracket => {
25387                    self.advance();
25388                    break;
25389                }
25390                other => {
25391                    return Err(self.err(format!("expected ',' or ']' in vector, got {other:?}")));
25392                }
25393            }
25394        }
25395        Ok(Expr::Literal(Literal::Vector(elems)))
25396    }
25397
25398    /// Atom that started with an identifier: could be `t.col`, `col`, or
25399    /// `func(arg, ...)`. Detect each shape by looking at the next token.
25400    /// v4.12: parse `(PARTITION BY expr, ... ORDER BY expr [DESC]
25401    /// [, ...])`. Caller has already consumed `OVER`. Either clause
25402    /// is optional; an empty `()` is also legal (PG semantics).
25403    /// v6.4.2 — consume an optional `IGNORE NULLS` / `RESPECT NULLS`
25404    /// modifier between `name(args)` and `OVER (...)`. Default is
25405    /// `Respect`. Unrecognised idents leave the stream unchanged.
25406    fn parse_null_treatment_modifier(&mut self) -> NullTreatment {
25407        let Token::Ident(s) = self.peek().clone() else {
25408            return NullTreatment::Respect;
25409        };
25410        let is_ignore = s.eq_ignore_ascii_case("ignore");
25411        let is_respect = s.eq_ignore_ascii_case("respect");
25412        if !is_ignore && !is_respect {
25413            return NullTreatment::Respect;
25414        }
25415        // Lookahead for NULLS — only consume both tokens together.
25416        // pos+1 must hold a "nulls" ident.
25417        if self.pos + 1 < self.tokens.len()
25418            && let Token::Ident(s2) = &self.tokens[self.pos + 1]
25419            && s2.eq_ignore_ascii_case("nulls")
25420        {
25421            self.advance();
25422            self.advance();
25423            return if is_ignore {
25424                NullTreatment::Ignore
25425            } else {
25426                NullTreatment::Respect
25427            };
25428        }
25429        NullTreatment::Respect
25430    }
25431
25432    /// v7.32 (mailrs round-29) — `agg(args) FILTER (WHERE cond)`.
25433    /// `FILTER` is an unreserved keyword, so it arrives as an `Ident`
25434    /// (same shape as the `OVER` tail). Consumes the whole clause and
25435    /// returns the predicate; returns `None` when no `FILTER` follows.
25436    fn parse_filter_clause(&mut self) -> Result<Option<Box<Expr>>, ParseError> {
25437        let (Token::Ident(s) | Token::QuotedIdent(s)) = self.peek() else {
25438            return Ok(None);
25439        };
25440        if !s.eq_ignore_ascii_case("filter") {
25441            return Ok(None);
25442        }
25443        self.advance(); // FILTER
25444        if !matches!(self.peek(), Token::LParen) {
25445            return Err(self.err(format!("expected '(' after FILTER, got {:?}", self.peek())));
25446        }
25447        self.advance(); // (
25448        if !matches!(self.peek(), Token::Where) {
25449            return Err(self.err(format!(
25450                "expected WHERE inside FILTER (...), got {:?}",
25451                self.peek()
25452            )));
25453        }
25454        self.advance(); // WHERE
25455        let cond = self.parse_expr(0)?;
25456        if !matches!(self.peek(), Token::RParen) {
25457            return Err(self.err(format!(
25458                "expected ')' to close FILTER (WHERE ...), got {:?}",
25459                self.peek()
25460            )));
25461        }
25462        self.advance(); // )
25463        Ok(Some(Box::new(cond)))
25464    }
25465
25466    /// v7.39 (round 354, M12) — consume a `SEPARATOR '<s>'` tail and push
25467    /// the separator as the aggregate's second argument, which is the
25468    /// shape `string_agg` already takes. Returns whether one was there.
25469    fn consume_group_concat_separator(&mut self, args: &mut Vec<Expr>) -> Result<bool, ParseError> {
25470        if !matches!(self.peek(), Token::Ident(k) if k.eq_ignore_ascii_case("separator")) {
25471            return Ok(false);
25472        }
25473        self.advance();
25474        let Token::String(sep) = self.peek().clone() else {
25475            return Err(self.err(alloc::format!(
25476                "expected a string literal after SEPARATOR, got {:?}",
25477                self.peek()
25478            )));
25479        };
25480        self.advance();
25481        args.push(Expr::Literal(Literal::String(sep)));
25482        Ok(true)
25483    }
25484
25485    /// v7.32 (round-29) — `WITHIN GROUP ( ORDER BY <sort_spec> )` tail
25486    /// for ordered-set aggregates. `WITHIN` is unreserved (arrives as an
25487    /// `Ident`); `GROUP` and `ORDER`/`BY` are keywords. Returns the sort
25488    /// keys, or an empty vec when no `WITHIN GROUP` follows.
25489    fn parse_within_group_clause(&mut self) -> Result<Vec<OrderBy>, ParseError> {
25490        let (Token::Ident(s) | Token::QuotedIdent(s)) = self.peek() else {
25491            return Ok(Vec::new());
25492        };
25493        if !s.eq_ignore_ascii_case("within") {
25494            return Ok(Vec::new());
25495        }
25496        self.advance(); // WITHIN
25497        if !matches!(self.peek(), Token::Group) {
25498            return Err(self.err(format!(
25499                "expected GROUP after WITHIN, got {:?}",
25500                self.peek()
25501            )));
25502        }
25503        self.advance(); // GROUP
25504        if !matches!(self.peek(), Token::LParen) {
25505            return Err(self.err(format!(
25506                "expected '(' after WITHIN GROUP, got {:?}",
25507                self.peek()
25508            )));
25509        }
25510        self.advance(); // (
25511        if !matches!(self.peek(), Token::Order) {
25512            return Err(self.err(format!(
25513                "expected ORDER BY inside WITHIN GROUP (...), got {:?}",
25514                self.peek()
25515            )));
25516        }
25517        self.advance(); // ORDER
25518        if !self.peek_is_by() {
25519            return Err(self.err(format!("expected BY after ORDER, got {:?}", self.peek())));
25520        }
25521        self.advance(); // BY
25522        let mut keys: Vec<OrderBy> = Vec::new();
25523        loop {
25524            // v7.39 (round 691) — save/restore, the discipline this parser
25525            // already uses around `pending_sample_preds`, so a subquery inside
25526            // a key neither inherits nor leaks the channel.
25527            let saved_flag = core::mem::replace(&mut self.in_order_by_key, true);
25528            let saved_coll = self.order_key_collation.take();
25529            let parsed = self.parse_expr(0);
25530            self.in_order_by_key = saved_flag;
25531            let collation = core::mem::replace(&mut self.order_key_collation, saved_coll);
25532            let expr = parsed?;
25533            let desc = if matches!(self.peek(), Token::Desc) {
25534                self.advance();
25535                true
25536            } else if matches!(self.peek(), Token::Asc) {
25537                self.advance();
25538                false
25539            } else {
25540                false
25541            };
25542            let nulls_first = self.parse_optional_nulls_placement()?;
25543            keys.push(OrderBy {
25544                expr,
25545                desc,
25546                nulls_first,
25547                collation,
25548            });
25549            if matches!(self.peek(), Token::Comma) {
25550                self.advance();
25551            } else {
25552                break;
25553            }
25554        }
25555        if !matches!(self.peek(), Token::RParen) {
25556            return Err(self.err(format!(
25557                "expected ')' to close WITHIN GROUP (ORDER BY ...), got {:?}",
25558                self.peek()
25559            )));
25560        }
25561        self.advance(); // )
25562        Ok(keys)
25563    }
25564
25565    /// No frame clause is supported.
25566    #[allow(clippy::type_complexity)] // (partitions, ordered-keys-with-desc) is the natural shape
25567    fn parse_over_clause(
25568        &mut self,
25569    ) -> Result<
25570        (
25571            Vec<Expr>,
25572            Vec<(Expr, bool, Option<bool>)>,
25573            Option<WindowFrame>,
25574        ),
25575        ParseError,
25576    > {
25577        // `OVER w` — a named-window reference. The WINDOW clause
25578        // parses after the select list, so the name rides out as a
25579        // marker in partition_by; parse_bare_select substitutes the
25580        // definition once the clause is known.
25581        if let Token::Ident(w) | Token::QuotedIdent(w) = self.peek() {
25582            let name = w.clone();
25583            self.advance();
25584            return Ok((
25585                alloc::vec![Expr::Column(crate::ast::ColumnName {
25586                    qualifier: Some("__named_window__".to_string()),
25587                    name,
25588                })],
25589                Vec::new(),
25590                None,
25591            ));
25592        }
25593        if !matches!(self.peek(), Token::LParen) {
25594            return Err(self.err(format!("expected '(' after OVER, got {:?}", self.peek())));
25595        }
25596        self.advance();
25597        let mut partition_by = Vec::new();
25598        let mut order_by = Vec::new();
25599        // v7.39 (round 229) — `OVER (w1 …)`: a *copy* of an existing named
25600        // window, refined in place. PG's rules (probed against 18.4) differ
25601        // from the bare `OVER w1` form, so the reference rides out under its
25602        // own marker and `substitute_named_windows` applies them. The base
25603        // name is any leading identifier that isn't a window-spec keyword.
25604        let base_window = match self.peek() {
25605            Token::Ident(s) | Token::QuotedIdent(s)
25606                if !s.eq_ignore_ascii_case("partition")
25607                    && !s.eq_ignore_ascii_case("rows")
25608                    && !s.eq_ignore_ascii_case("range")
25609                    && !s.eq_ignore_ascii_case("groups") =>
25610            {
25611                let n = s.clone();
25612                self.advance();
25613                Some(n)
25614            }
25615            _ => None,
25616        };
25617        // PARTITION BY ?
25618        // v7.37.6-B promoted PARTITION to a reserved keyword
25619        // (Token::Partition); pre-7.37.6-B catalogs lexed it as
25620        // `Token::Ident("partition")`. Accept both so older sources
25621        // and the new lexer surface land on the same path.
25622        let is_partition_kw = match self.peek() {
25623            Token::Partition => true,
25624            Token::Ident(s) | Token::QuotedIdent(s) => s.eq_ignore_ascii_case("partition"),
25625            _ => false,
25626        };
25627        if is_partition_kw {
25628            self.advance();
25629            if !self.peek_is_by() {
25630                return Err(self.err(format!(
25631                    "expected BY after PARTITION, got {:?}",
25632                    self.peek()
25633                )));
25634            }
25635            self.advance();
25636            loop {
25637                partition_by.push(self.parse_expr(0)?);
25638                if matches!(self.peek(), Token::Comma) {
25639                    self.advance();
25640                    continue;
25641                }
25642                break;
25643            }
25644        }
25645        // ORDER BY ?
25646        if matches!(self.peek(), Token::Order) {
25647            self.advance();
25648            if !self.peek_is_by() {
25649                return Err(self.err(format!("expected BY after ORDER, got {:?}", self.peek())));
25650            }
25651            self.advance();
25652            loop {
25653                let e = self.parse_expr(0)?;
25654                let desc = if matches!(self.peek(), Token::Desc) {
25655                    self.advance();
25656                    true
25657                } else if matches!(self.peek(), Token::Asc) {
25658                    self.advance();
25659                    false
25660                } else {
25661                    false
25662                };
25663                // v7.24.1 — NULLS FIRST/LAST inside OVER (…).
25664                let nulls_first = self.parse_optional_nulls_placement()?;
25665                order_by.push((e, desc, nulls_first));
25666                if matches!(self.peek(), Token::Comma) {
25667                    self.advance();
25668                    continue;
25669                }
25670                break;
25671            }
25672        }
25673        // v4.20: optional explicit frame, `ROWS ...` / `RANGE ...`.
25674        // Both keywords come through the lexer as identifiers; match
25675        // case-insensitively.
25676        let mut frame: Option<WindowFrame> = None;
25677        if let Token::Ident(s) | Token::QuotedIdent(s) = self.peek() {
25678            let kind = if s.eq_ignore_ascii_case("rows") {
25679                Some(FrameKind::Rows)
25680            } else if s.eq_ignore_ascii_case("range") {
25681                Some(FrameKind::Range)
25682            } else if s.eq_ignore_ascii_case("groups") {
25683                // v7.37.19 (19.11) — PG 11+ GROUPS frame mode.
25684                Some(FrameKind::Groups)
25685            } else {
25686                None
25687            };
25688            if let Some(kind) = kind {
25689                self.advance();
25690                frame = Some(self.parse_frame_tail(kind)?);
25691            }
25692        }
25693        if !matches!(self.peek(), Token::RParen) {
25694            return Err(self.err(format!(
25695                "expected ')' to close OVER clause, got {:?}",
25696                self.peek()
25697            )));
25698        }
25699        self.advance();
25700        if let Some(base) = base_window {
25701            // A copy may refine but never override the base's partitioning
25702            // (PG rejects it outright, before looking the name up).
25703            if !partition_by.is_empty() {
25704                return Err(self.err(alloc::format!(
25705                    "cannot override PARTITION BY clause of window \"{base}\""
25706                )));
25707            }
25708            partition_by = alloc::vec![Expr::Column(crate::ast::ColumnName {
25709                qualifier: Some("__named_window_ref__".to_string()),
25710                name: base,
25711            })];
25712        }
25713        Ok((partition_by, order_by, frame))
25714    }
25715
25716    /// v4.20: parse the tail of an explicit frame, given the `ROWS`
25717    /// or `RANGE` keyword was just consumed. Accepts both
25718    /// `BETWEEN <bound> AND <bound>` and the single-bound shorthand
25719    /// (`ROWS UNBOUNDED PRECEDING`, `ROWS 5 PRECEDING`, etc.) which
25720    /// PG normalises to `BETWEEN <bound> AND CURRENT ROW`.
25721    fn parse_frame_tail(&mut self, kind: FrameKind) -> Result<WindowFrame, ParseError> {
25722        let (start, end) = if matches!(self.peek(), Token::Between) {
25723            self.advance();
25724            let start = self.parse_frame_bound()?;
25725            if !matches!(self.peek(), Token::And) {
25726                return Err(self.err(format!("expected AND in frame spec, got {:?}", self.peek())));
25727            }
25728            self.advance();
25729            let end = self.parse_frame_bound()?;
25730            (start, Some(end))
25731        } else {
25732            (self.parse_frame_bound()?, None)
25733        };
25734        let exclude = self.parse_frame_exclusion()?;
25735        Ok(WindowFrame {
25736            kind,
25737            start,
25738            end,
25739            exclude,
25740        })
25741    }
25742
25743    /// Optional `EXCLUDE {CURRENT ROW | GROUP | TIES | NO OTHERS}`
25744    /// after a frame spec. NO OTHERS is the default no-op.
25745    fn parse_frame_exclusion(&mut self) -> Result<FrameExclusion, ParseError> {
25746        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("exclude")) {
25747            return Ok(FrameExclusion::NoOthers);
25748        }
25749        self.advance(); // EXCLUDE
25750        match self.peek() {
25751            Token::Ident(s) if s.eq_ignore_ascii_case("current") => {
25752                self.advance();
25753                if !matches!(self.peek(), Token::Ident(r) if r.eq_ignore_ascii_case("row")) {
25754                    return Err(self.err(format!(
25755                        "expected ROW after EXCLUDE CURRENT, got {:?}",
25756                        self.peek()
25757                    )));
25758                }
25759                self.advance();
25760                Ok(FrameExclusion::CurrentRow)
25761            }
25762            // v7.39 (read01 round 109) — GROUP is a reserved keyword token, so
25763            // `EXCLUDE GROUP` arrives as `Token::Group`, not `Ident("group")`.
25764            // Without this arm it fell to the catch-all, whose message
25765            // self-contradictingly listed GROUP as expected.
25766            Token::Ident(s) if s.eq_ignore_ascii_case("group") => {
25767                self.advance();
25768                Ok(FrameExclusion::Group)
25769            }
25770            Token::Group => {
25771                self.advance();
25772                Ok(FrameExclusion::Group)
25773            }
25774            Token::Ident(s) if s.eq_ignore_ascii_case("ties") => {
25775                self.advance();
25776                Ok(FrameExclusion::Ties)
25777            }
25778            Token::Ident(s) if s.eq_ignore_ascii_case("no") => {
25779                self.advance();
25780                if !matches!(self.peek(), Token::Ident(r) if r.eq_ignore_ascii_case("others")) {
25781                    return Err(self.err(format!(
25782                        "expected OTHERS after EXCLUDE NO, got {:?}",
25783                        self.peek()
25784                    )));
25785                }
25786                self.advance();
25787                Ok(FrameExclusion::NoOthers)
25788            }
25789            other => Err(self.err(format!(
25790                "expected CURRENT ROW / GROUP / TIES / NO OTHERS after EXCLUDE, got {other:?}"
25791            ))),
25792        }
25793    }
25794
25795    /// Parse one frame bound: `UNBOUNDED PRECEDING`, `<n> PRECEDING`,
25796    /// `<interval> PRECEDING`, `CURRENT ROW`, `<n>/<interval> FOLLOWING`,
25797    /// `UNBOUNDED FOLLOWING`.
25798    fn parse_frame_bound(&mut self) -> Result<FrameBound, ParseError> {
25799        // Interval-typed offset for a value-based RANGE frame over a
25800        // DATE / TIMESTAMP ORDER BY column (PG time-series windows),
25801        // spelled `INTERVAL '1 day' PRECEDING` or `'1 day'::interval
25802        // PRECEDING`.
25803        if let Some((months, days, micros)) = self.try_take_interval_offset()? {
25804            let dir = self.expect_ident_like()?;
25805            return if dir.eq_ignore_ascii_case("preceding") {
25806                Ok(FrameBound::IntervalPreceding {
25807                    months,
25808                    days,
25809                    micros,
25810                })
25811            } else if dir.eq_ignore_ascii_case("following") {
25812                Ok(FrameBound::IntervalFollowing {
25813                    months,
25814                    days,
25815                    micros,
25816                })
25817            } else {
25818                Err(self.err(format!(
25819                    "expected PRECEDING or FOLLOWING after interval offset, got {dir:?}"
25820                )))
25821            };
25822        }
25823        // Number-led: "<n> PRECEDING" / "<n> FOLLOWING".
25824        if let Token::Integer(n) = *self.peek() {
25825            self.advance();
25826            let n: u64 = u64::try_from(n).map_err(|_| {
25827                self.err(format!(
25828                    "invalid frame offset {n} — expected non-negative integer"
25829                ))
25830            })?;
25831            let dir = self.expect_ident_like()?;
25832            return if dir.eq_ignore_ascii_case("preceding") {
25833                Ok(FrameBound::OffsetPreceding(n))
25834            } else if dir.eq_ignore_ascii_case("following") {
25835                Ok(FrameBound::OffsetFollowing(n))
25836            } else {
25837                Err(self.err(format!(
25838                    "expected PRECEDING or FOLLOWING after offset, got {dir:?}"
25839                )))
25840            };
25841        }
25842        let first = self.expect_ident_like()?;
25843        if first.eq_ignore_ascii_case("unbounded") {
25844            let dir = self.expect_ident_like()?;
25845            return if dir.eq_ignore_ascii_case("preceding") {
25846                Ok(FrameBound::UnboundedPreceding)
25847            } else if dir.eq_ignore_ascii_case("following") {
25848                Ok(FrameBound::UnboundedFollowing)
25849            } else {
25850                Err(self.err(format!(
25851                    "expected PRECEDING or FOLLOWING after UNBOUNDED, got {dir:?}"
25852                )))
25853            };
25854        }
25855        if first.eq_ignore_ascii_case("current") {
25856            let row = self.expect_ident_like()?;
25857            if !row.eq_ignore_ascii_case("row") {
25858                return Err(self.err(format!("expected ROW after CURRENT, got {row:?}")));
25859            }
25860            return Ok(FrameBound::CurrentRow);
25861        }
25862        Err(self.err(format!(
25863            "expected frame bound (UNBOUNDED/CURRENT/<n>), got {first:?}"
25864        )))
25865    }
25866
25867    /// Detect and consume a leading interval offset in a frame bound —
25868    /// `INTERVAL '1 day'` or `'1 day'::interval` — returning its folded
25869    /// `(months, days, micros)`. Leaves the cursor on the trailing
25870    /// PRECEDING / FOLLOWING keyword. Returns `None` (without advancing)
25871    /// when the next tokens are not an interval offset.
25872    fn try_take_interval_offset(&mut self) -> Result<Option<(i32, i32, i64)>, ParseError> {
25873        // Shape A — `INTERVAL '1 day'`.
25874        if matches!(self.peek(), Token::Interval) {
25875            self.advance(); // INTERVAL
25876            let atom = self.parse_interval_atom()?;
25877            if let Expr::Literal(Literal::Interval {
25878                months,
25879                days,
25880                micros,
25881                ..
25882            }) = atom
25883            {
25884                return Ok(Some((months, days, micros)));
25885            }
25886            return Err(self.err("expected an interval literal in frame offset".to_string()));
25887        }
25888        // Shape B — `'1 day'::interval`. Look ahead for the exact
25889        // string / `::` / interval-target triple before committing.
25890        if let Token::String(text) = self.peek() {
25891            let target_is_interval = match self.tokens.get(self.pos + 2) {
25892                Some(Token::Interval) => true,
25893                Some(Token::Ident(s)) => s.eq_ignore_ascii_case("interval"),
25894                _ => false,
25895            };
25896            let is_cast = matches!(self.tokens.get(self.pos + 1), Some(Token::DoubleColon))
25897                && target_is_interval;
25898            if is_cast {
25899                let text = text.clone();
25900                self.advance(); // string
25901                self.advance(); // ::
25902                self.advance(); // interval
25903                let parts = parse_interval_text(&text).ok_or_else(|| {
25904                    self.err(format!("cannot parse INTERVAL {text:?} in frame offset"))
25905                })?;
25906                return Ok(Some(parts));
25907            }
25908        }
25909        Ok(None)
25910    }
25911
25912    fn finish_ident_atom(&mut self, first: String) -> Result<Expr, ParseError> {
25913        // v7.39.2 — MySQL's charset INTRODUCER: `_utf8mb4'x'`, `N'y'`,
25914        // `_binary'z'`. All three were `ERROR 1064 syntax error` here
25915        // and all three answer the literal on MySQL 9.7.2.
25916        //
25917        // It is not only syntax, which is why it waited for
25918        // `Expr::Collate`: measured, `_binary'A' = 'a'` is 0 on MySQL
25919        // because `_binary` makes the comparison byte-wise, while
25920        // `_utf8mb4'A' = _utf8mb4'a'` is 1. Accepting the syntax and
25921        // dropping the charset would have turned a hard error into a
25922        // silently wrong comparison — worse than the error it replaced.
25923        //
25924        // An UNKNOWN charset is NOT an introducer: MySQL answers
25925        // `Unknown column '_nosuch'`, because it parses as a column
25926        // reference followed by a string. So the table decides, and it
25927        // is the same table `SET NAMES` reads.
25928        //
25929        // A space is allowed between the two (`_utf8mb4 'x'`), which
25930        // falls out of asking the token stream rather than the bytes.
25931        if self.mysql_dialect
25932            && let Token::String(_) = self.peek()
25933        {
25934            let lower = first.to_ascii_lowercase();
25935            let charset = if lower == "n" {
25936                // `N'…'` is the national character set, which MySQL
25937                // documents as utf8 — utf8mb3 in 9.7.2's spelling.
25938                //
25939                // utf8mb3 and utf8mb4 both fold case in their default
25940                // collations, so nothing SPG can be asked distinguishes
25941                // the two here: an ablation swapping this to utf8mb4
25942                // reddens no pin. Recorded rather than implied — the
25943                // spelling follows MySQL's documentation, not a
25944                // measurement.
25945                Some("utf8mb3")
25946            } else {
25947                // No filter here: the lookup below IS the test for
25948                // "is this a charset". An ablation that removed a filter
25949                // in this spot reddened nothing, which is how the two
25950                // were found to be one check written twice.
25951                lower.strip_prefix('_')
25952            };
25953            if let Some(cs) = charset
25954                && let Some(collation) = crate::charset::charset_default_collation(cs)
25955            {
25956                let Token::String(body) = self.advance() else {
25957                    unreachable!("peeked a string");
25958                };
25959                return Ok(Expr::Collate {
25960                    expr: Box::new(Expr::Literal(Literal::String(body))),
25961                    collation: String::from(collation),
25962                });
25963            }
25964        }
25965        if matches!(self.peek(), Token::Dot) {
25966            self.advance();
25967            let name = self.expect_ident_like()?;
25968            // v7.14.0 — schema-qualified function call
25969            // `<schema>.<fn>(args)`. PG dumps emit
25970            // `pg_catalog.set_config(...)` in the preamble. SPG
25971            // is single-namespace: drop the schema prefix and
25972            // route the dispatch on the bare function name.
25973            if matches!(self.peek(), Token::LParen) {
25974                return self.finish_ident_atom(name);
25975            }
25976            return Ok(Expr::Column(ColumnName {
25977                qualifier: Some(first),
25978                name,
25979            }));
25980        }
25981        if matches!(self.peek(), Token::LParen) {
25982            self.advance();
25983            // `COUNT(*)` — special-cased here because `*` isn't a normal
25984            // expression token. Lower-case match on `first` since the lexer
25985            // folds identifiers.
25986            if first.eq_ignore_ascii_case("count") && matches!(self.peek(), Token::Star) {
25987                self.advance();
25988                if !matches!(self.peek(), Token::RParen) {
25989                    return Err(self.err(format!(
25990                        "expected ')' after COUNT(*), got {:?}",
25991                        self.peek()
25992                    )));
25993                }
25994                self.advance();
25995                // v7.32 (round-29) — `COUNT(*) FILTER (WHERE …)`.
25996                let filter = self.parse_filter_clause()?;
25997                // v4.12: COUNT(*) OVER (...) — same window tail.
25998                let null_treatment = self.parse_null_treatment_modifier();
25999                if let Token::Ident(s) | Token::QuotedIdent(s) = self.peek()
26000                    && s.eq_ignore_ascii_case("over")
26001                {
26002                    self.advance();
26003                    let (partition_by, order_by, frame) = self.parse_over_clause()?;
26004                    return Ok(Expr::WindowFunction {
26005                        name: "count_star".into(),
26006                        args: Vec::new(),
26007                        partition_by,
26008                        order_by,
26009                        frame,
26010                        null_treatment,
26011                        filter,
26012                    });
26013                }
26014                if let Some(filter) = filter {
26015                    return Ok(Expr::AggregateOrdered {
26016                        call: Box::new(Expr::FunctionCall {
26017                            name: "count_star".into(),
26018                            args: Vec::new(),
26019                        }),
26020                        order_by: Vec::new(),
26021                        distinct: false,
26022                        filter: Some(filter),
26023                    });
26024                }
26025                return Ok(Expr::FunctionCall {
26026                    name: "count_star".into(),
26027                    args: Vec::new(),
26028                });
26029            }
26030            // Function call. PG-style: zero-or-more comma-separated args.
26031            let mut args = Vec::new();
26032            // v7.38 (read01, T14) — named-argument notation `argname => value`.
26033            // Names are collected in lock-step with `args` and resolved to
26034            // positional order after the loop (the AST stays positional).
26035            let mut arg_names: Vec<Option<String>> = Vec::new();
26036            let mut agg_order_by: Vec<OrderBy> = Vec::new();
26037            // v7.39 (round 354, M12) — whether a `SEPARATOR '<s>'` tail was
26038            // seen, so the value arguments before it can be folded.
26039            let mut saw_separator = false;
26040            // v7.25 (round-17) — `COUNT(DISTINCT x)` and friends.
26041            // v7.32 (round-29) — accept the dual `ALL` quantifier too
26042            // (the default; ORMs emit `COUNT(ALL x)` / `SUM(ALL x)`).
26043            let agg_distinct = if matches!(self.peek(), Token::Distinct) {
26044                self.advance();
26045                true
26046            } else if matches!(self.peek(), Token::All) {
26047                self.advance();
26048                false
26049            } else {
26050                false
26051            };
26052            // v7.37.17 (17.6 siblings) — MySQL TIMESTAMPADD /
26053            // TIMESTAMPDIFF take a bare unit keyword as the first
26054            // argument (MINUTE, DAY, ...), and GET_FORMAT takes a
26055            // bare type keyword (DATE / TIME / DATETIME); lower them
26056            // onto string literals so the evaluator sees plain text.
26057            if ((first.eq_ignore_ascii_case("timestampadd")
26058                || first.eq_ignore_ascii_case("timestampdiff"))
26059                && matches!(self.peek(), Token::Ident(u) if matches!(
26060                    u.to_ascii_lowercase().as_str(),
26061                    "microsecond" | "second" | "minute" | "hour" | "day"
26062                        | "week" | "month" | "quarter" | "year"
26063                )))
26064                || (first.eq_ignore_ascii_case("get_format")
26065                    && matches!(self.peek(), Token::Ident(u) if matches!(
26066                        u.to_ascii_lowercase().as_str(),
26067                        "date" | "time" | "datetime" | "timestamp"
26068                    )))
26069            {
26070                if let Token::Ident(u) = self.peek() {
26071                    args.push(Expr::Literal(Literal::String(u.to_ascii_lowercase())));
26072                }
26073                self.advance();
26074                if matches!(self.peek(), Token::Comma) {
26075                    self.advance();
26076                }
26077            }
26078            // `ROW(a, b, …)` keyword constructor. Followed by a
26079            // comparison operator or [NOT] IN it joins the paren
26080            // row-constructor machinery (fieldwise parse-time
26081            // expansion); bare, it stays a `row` call the evaluator
26082            // renders as PG record text.
26083            if first.eq_ignore_ascii_case("row") {
26084                let mut row_items = Vec::new();
26085                if !matches!(self.peek(), Token::RParen) {
26086                    loop {
26087                        row_items.push(self.parse_expr(0)?);
26088                        match self.peek() {
26089                            Token::Comma => {
26090                                self.advance();
26091                            }
26092                            Token::RParen => break,
26093                            other => {
26094                                return Err(self.err(format!(
26095                                    "expected ',' or ')' in ROW(...), got {other:?}"
26096                                )));
26097                            }
26098                        }
26099                    }
26100                }
26101                self.advance(); // ')'
26102                let comparison_follows = matches!(
26103                    self.peek(),
26104                    Token::Eq
26105                        | Token::NotEq
26106                        | Token::Lt
26107                        | Token::LtEq
26108                        | Token::Gt
26109                        | Token::GtEq
26110                        | Token::In
26111                ) || (matches!(self.peek(), Token::Not)
26112                    && matches!(self.tokens.get(self.pos + 1), Some(Token::In)))
26113                    || matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("overlaps"));
26114                if comparison_follows && !row_items.is_empty() {
26115                    return self.parse_row_comparison_tail(row_items);
26116                }
26117                return Ok(Expr::FunctionCall {
26118                    name: String::from("row"),
26119                    args: row_items,
26120                });
26121            }
26122            // v7.39 (read01 xml.c) — `XMLPARSE(DOCUMENT|CONTENT expr)`:
26123            // the parse-mode keyword introduces the source text. SPG
26124            // carries XML as text, so both modes lower to __xmlparse(expr)
26125            // which validates well-formedness and returns Value::Xml.
26126            if first.eq_ignore_ascii_case("xmlparse")
26127                && matches!(self.peek(), Token::Ident(kw)
26128                    if kw.eq_ignore_ascii_case("document")
26129                        || kw.eq_ignore_ascii_case("content"))
26130            {
26131                let mode = match self.advance() {
26132                    Token::Ident(kw) => kw.to_ascii_lowercase(),
26133                    _ => unreachable!("peeked an ident"),
26134                };
26135                let src = self.parse_expr(0)?;
26136                if !matches!(self.peek(), Token::RParen) {
26137                    return Err(self.err(format!(
26138                        "expected ')' to close XMLPARSE, got {:?}",
26139                        self.peek()
26140                    )));
26141                }
26142                self.advance();
26143                return Ok(Expr::FunctionCall {
26144                    name: String::from("__xmlparse"),
26145                    args: alloc::vec![src, Expr::Literal(Literal::String(mode))],
26146                });
26147            }
26148            // SQL/XML `XMLELEMENT(NAME ident [, content …])` — the NAME
26149            // keyword introduces the element name (a bare or quoted
26150            // identifier), then optional content expressions. Lower to a
26151            // plain `xmlelement(name_text, content …)` call.
26152            if first.eq_ignore_ascii_case("xmlelement")
26153                && matches!(self.peek(), Token::Ident(kw) if kw.eq_ignore_ascii_case("name"))
26154            {
26155                self.advance(); // consume NAME
26156                let elem_name = match self.peek().clone() {
26157                    Token::Ident(n) | Token::QuotedIdent(n) => {
26158                        self.advance();
26159                        n
26160                    }
26161                    other => {
26162                        return Err(self.err(format!(
26163                            "expected element name after XMLELEMENT NAME, got {other:?}"
26164                        )));
26165                    }
26166                };
26167                let mut args = alloc::vec![Expr::Literal(Literal::String(elem_name))];
26168                while matches!(self.peek(), Token::Comma) {
26169                    self.advance();
26170                    args.push(self.parse_expr(0)?);
26171                }
26172                if !matches!(self.peek(), Token::RParen) {
26173                    return Err(self.err(format!(
26174                        "expected ')' to close XMLELEMENT, got {:?}",
26175                        self.peek()
26176                    )));
26177                }
26178                self.advance();
26179                return Ok(Expr::FunctionCall {
26180                    name: String::from("xmlelement"),
26181                    args,
26182                });
26183            }
26184            // SQL/XML `XMLFOREST(value [AS name], …)` — each `value AS name`
26185            // becomes a `<name>value</name>` element; a bare column infers its
26186            // own name. Lower to `xmlforest(name1, val1, name2, val2, …)`.
26187            // v7.39.2 — MySQL's two CONVERT forms, neither of which parsed.
26188            // `CONVERT(expr USING cs)` was a syntax error at USING, and
26189            // `CONVERT(expr, CHAR)` was read as PostgreSQL's three-argument
26190            // `convert(bytea, src, dest)` and answered `column "char" does
26191            // not exist`. Both are casts in MySQL: measured on 9.7.2,
26192            // `CONVERT(0x41 USING utf8mb4)` and `CONVERT(0x41, CHAR)` are
26193            // both 'A', and `CONVERT(123, CHAR)` is '123'.
26194            //
26195            // The charset is checked against the same table the introducers
26196            // use, so an unknown one is refused rather than quietly ignored.
26197            if self.mysql_dialect
26198                && first.eq_ignore_ascii_case("convert")
26199                && !matches!(self.peek(), Token::RParen)
26200            {
26201                let save = self.pos;
26202                let inner = self.parse_expr(0)?;
26203                if matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("using")) {
26204                    self.advance();
26205                    let cs = match self.peek().clone() {
26206                        Token::Ident(n) | Token::QuotedIdent(n) => {
26207                            self.advance();
26208                            n
26209                        }
26210                        other => {
26211                            return Err(self.err(alloc::format!(
26212                                "expected a charset after USING, got {other:?}"
26213                            )));
26214                        }
26215                    };
26216                    let lc = cs.to_ascii_lowercase();
26217                    if lc != "binary" && crate::charset::charset_default_collation(&lc).is_none() {
26218                        return Err(self.err(alloc::format!("unknown character set: '{cs}'")));
26219                    }
26220                    if !matches!(self.peek(), Token::RParen) {
26221                        return Err(self.err(alloc::format!(
26222                            "expected ')' after CONVERT … USING, got {:?}",
26223                            self.peek()
26224                        )));
26225                    }
26226                    self.advance();
26227                    let target = if lc == "binary" {
26228                        CastTarget::Named("binary".to_string())
26229                    } else {
26230                        CastTarget::Text
26231                    };
26232                    return self.finish_postfix_casts(Expr::Cast {
26233                        expr: alloc::boxed::Box::new(inner),
26234                        target,
26235                    });
26236                }
26237                if matches!(self.peek(), Token::Comma) {
26238                    self.advance();
26239                    // A type name here is MySQL's cast form; anything else
26240                    // (three string arguments) is PostgreSQL's `convert`,
26241                    // which keeps its own path.
26242                    if let Ok(target) = self.parse_cast_target()
26243                        && matches!(self.peek(), Token::RParen)
26244                    {
26245                        self.advance();
26246                        return self.finish_postfix_casts(Expr::Cast {
26247                            expr: alloc::boxed::Box::new(inner),
26248                            target,
26249                        });
26250                    }
26251                }
26252                self.pos = save;
26253            }
26254            if first.eq_ignore_ascii_case("xmlforest") && !matches!(self.peek(), Token::RParen) {
26255                let mut args: Vec<Expr> = Vec::new();
26256                loop {
26257                    let val = self.parse_expr(0)?;
26258                    let name = if matches!(self.peek(), Token::As) {
26259                        self.advance();
26260                        match self.peek().clone() {
26261                            Token::Ident(n) | Token::QuotedIdent(n) => {
26262                                self.advance();
26263                                n
26264                            }
26265                            other => {
26266                                return Err(self.err(format!(
26267                                    "expected name after AS in XMLFOREST, got {other:?}"
26268                                )));
26269                            }
26270                        }
26271                    } else if let Expr::Column(c) = &val {
26272                        c.name.clone()
26273                    } else {
26274                        return Err(
26275                            self.err("XMLFOREST element without a column name needs AS".into())
26276                        );
26277                    };
26278                    args.push(Expr::Literal(Literal::String(name)));
26279                    args.push(val);
26280                    if matches!(self.peek(), Token::Comma) {
26281                        self.advance();
26282                    } else {
26283                        break;
26284                    }
26285                }
26286                if !matches!(self.peek(), Token::RParen) {
26287                    return Err(self.err(format!(
26288                        "expected ')' to close XMLFOREST, got {:?}",
26289                        self.peek()
26290                    )));
26291                }
26292                self.advance();
26293                return Ok(Expr::FunctionCall {
26294                    name: String::from("xmlforest"),
26295                    args,
26296                });
26297            }
26298            // SQL-standard `POSITION(sub IN str)` — lowers onto
26299            // strpos(str, sub). IN is the argument separator here,
26300            // so the needle parses with the IN-tail suppressed.
26301            if first.eq_ignore_ascii_case("position") && !matches!(self.peek(), Token::RParen) {
26302                let saved = self.suppress_in_tail;
26303                self.suppress_in_tail = true;
26304                let needle = self.parse_expr(0);
26305                self.suppress_in_tail = saved;
26306                let needle = needle?;
26307                if matches!(self.peek(), Token::In) {
26308                    self.advance();
26309                    let haystack = self.parse_expr(0)?;
26310                    if !matches!(self.peek(), Token::RParen) {
26311                        return Err(self.err(format!(
26312                            "expected ')' to close POSITION, got {:?}",
26313                            self.peek()
26314                        )));
26315                    }
26316                    self.advance();
26317                    return Ok(Expr::FunctionCall {
26318                        name: String::from("strpos"),
26319                        args: alloc::vec![haystack, needle],
26320                    });
26321                }
26322                // position(sub, str) comma form (incl. bytea) —
26323                // hand the parsed first arg to the generic list.
26324                args.push(needle);
26325                if matches!(self.peek(), Token::Comma) {
26326                    self.advance();
26327                }
26328            }
26329            // SQL-standard `TRIM([BOTH|LEADING|TRAILING] [chars]
26330            // FROM str)` — lowers onto btrim / ltrim / rtrim. The
26331            // plain comma forms TRIM(str) / TRIM(str, chars) keep
26332            // riding the generic argument list below.
26333            if first.eq_ignore_ascii_case("trim") {
26334                let mode = match self.peek() {
26335                    Token::Ident(k) if k.eq_ignore_ascii_case("both") => {
26336                        self.advance();
26337                        Some("btrim")
26338                    }
26339                    Token::Ident(k) if k.eq_ignore_ascii_case("leading") => {
26340                        self.advance();
26341                        Some("ltrim")
26342                    }
26343                    Token::Ident(k) if k.eq_ignore_ascii_case("trailing") => {
26344                        self.advance();
26345                        Some("rtrim")
26346                    }
26347                    _ => None,
26348                };
26349                if mode.is_some() || matches!(self.peek(), Token::From) {
26350                    // TRIM([mode] FROM str) — no strip-chars.
26351                    let chars = if matches!(self.peek(), Token::From) {
26352                        None
26353                    } else {
26354                        Some(self.parse_expr(0)?)
26355                    };
26356                    if !matches!(self.peek(), Token::From) {
26357                        return Err(self.err(format!(
26358                            "expected FROM in TRIM([BOTH|LEADING|TRAILING] [chars] FROM str), got {:?}",
26359                            self.peek()
26360                        )));
26361                    }
26362                    self.advance();
26363                    let target = self.parse_expr(0)?;
26364                    if !matches!(self.peek(), Token::RParen) {
26365                        return Err(
26366                            self.err(format!("expected ')' to close TRIM, got {:?}", self.peek()))
26367                        );
26368                    }
26369                    self.advance();
26370                    let mut trim_args = alloc::vec![target];
26371                    if let Some(c) = chars {
26372                        trim_args.push(c);
26373                    }
26374                    return Ok(Expr::FunctionCall {
26375                        name: String::from(mode.unwrap_or("btrim")),
26376                        args: trim_args,
26377                    });
26378                }
26379            }
26380            if !matches!(self.peek(), Token::RParen) {
26381                loop {
26382                    // v7.38 (read01, T14) — `argname => value` names this arg.
26383                    // v7.39 (read01 round 77) — `argname := value` is the same
26384                    // thing, and it is the spelling PG's own docs lead with. It
26385                    // was simply never lexed here, so every `f(x := 1)` died in
26386                    // the parser regardless of what `f` was.
26387                    let this_name = match (&self.tokens[self.pos], self.tokens.get(self.pos + 1)) {
26388                        (
26389                            Token::Ident(n) | Token::QuotedIdent(n),
26390                            Some(Token::FatArrow | Token::ColonEq),
26391                        ) => {
26392                            let name = n.clone();
26393                            self.advance(); // name
26394                            self.advance(); // => / :=
26395                            Some(name)
26396                        }
26397                        _ => None,
26398                    };
26399                    // v7.39 (read01 round 100) — `VARIADIC <array>` spreads an
26400                    // array's elements into a variadic call's trailing args
26401                    // (`concat_ws(',', VARIADIC ARRAY[…])`). VARIADIC isn't
26402                    // reserved, so it arrives as a bare ident before the arg.
26403                    let is_variadic = this_name.is_none()
26404                        && matches!(&self.tokens[self.pos], Token::Ident(s) if s.eq_ignore_ascii_case("variadic"));
26405                    if is_variadic {
26406                        self.advance();
26407                    }
26408                    let arg = self.parse_expr(0)?;
26409                    args.push(match &this_name {
26410                        // The callee's parameter names decide the slot, and a
26411                        // user function's live in the catalog. Carry the name
26412                        // to eval rather than guessing here.
26413                        Some(n) => Expr::NamedArg {
26414                            name: n.clone(),
26415                            expr: Box::new(arg),
26416                        },
26417                        None if is_variadic => Expr::Variadic(Box::new(arg)),
26418                        None => arg,
26419                    });
26420                    arg_names.push(this_name);
26421                    // v7.25 (round-17) — standard `CAST(expr AS type)`.
26422                    // The `::` cast already worked; this lowers the
26423                    // function form onto the same Expr::Cast node.
26424                    if first.eq_ignore_ascii_case("cast")
26425                        && args.len() == 1
26426                        && matches!(self.peek(), Token::As)
26427                    {
26428                        self.advance();
26429                        let target = self.parse_cast_target()?;
26430                        if !matches!(self.peek(), Token::RParen) {
26431                            return Err(self.err(format!(
26432                                "expected ')' to close CAST, got {:?}",
26433                                self.peek()
26434                            )));
26435                        }
26436                        self.advance();
26437                        return Ok(Expr::Cast {
26438                            expr: Box::new(args.pop().expect("one arg")),
26439                            target,
26440                        });
26441                    }
26442                    // v7.38 (read01 P6.-) — `normalize(text, FORM)` where FORM is
26443                    // a bare keyword NFC / NFD / NFKC / NFKD. PG parses these as
26444                    // keywords; SPG's lexer makes them plain idents (so they'd be
26445                    // read as column refs). Lower the keyword to the string form
26446                    // the evaluator already accepts.
26447                    if first.eq_ignore_ascii_case("normalize")
26448                        && args.len() == 1
26449                        && matches!(self.peek(), Token::Comma)
26450                    {
26451                        let form = match self.tokens.get(self.pos + 1) {
26452                            Some(Token::Ident(f) | Token::QuotedIdent(f)) => {
26453                                let up = f.to_ascii_uppercase();
26454                                matches!(up.as_str(), "NFC" | "NFD" | "NFKC" | "NFKD").then_some(up)
26455                            }
26456                            _ => None,
26457                        };
26458                        if let Some(up) = form {
26459                            self.advance(); // comma
26460                            self.advance(); // form keyword
26461                            args.push(Expr::Literal(Literal::String(up)));
26462                        }
26463                    }
26464                    // v7.37.7 C.1.8 — PG `substring(str FROM pos FOR len)` syntactic
26465                    // form. Desugars to the comma-list shape evaluator already
26466                    // handles. Triggered after the first arg when the function
26467                    // name is substring / substr and the next token is FROM
26468                    // (a reserved keyword in PG; SPG also reserves it).
26469                    // v7.39 (read01 regexp.c) — `substring(str SIMILAR pat
26470                    // ESCAPE esc)` (SQL:1999 three-part form) desugars to the
26471                    // internal __substring_similar(str, pat, esc) call.
26472                    if (first.eq_ignore_ascii_case("substring")
26473                        || first.eq_ignore_ascii_case("substr"))
26474                        && args.len() == 1
26475                        && matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("similar"))
26476                    {
26477                        self.advance(); // SIMILAR
26478                        let pattern = self.parse_expr(0)?;
26479                        if !matches!(self.peek(), Token::Ident(s) if s.eq_ignore_ascii_case("escape"))
26480                        {
26481                            return Err(self.err(format!(
26482                                "expected ESCAPE in substring(... SIMILAR ...), got {:?}",
26483                                self.peek()
26484                            )));
26485                        }
26486                        self.advance(); // ESCAPE
26487                        let esc = self.parse_expr(0)?;
26488                        if !matches!(self.peek(), Token::RParen) {
26489                            return Err(self.err(format!(
26490                                "expected ')' to close substring(... SIMILAR ...), got {:?}",
26491                                self.peek()
26492                            )));
26493                        }
26494                        self.advance();
26495                        args.push(pattern);
26496                        args.push(esc);
26497                        return Ok(Expr::FunctionCall {
26498                            name: "__substring_similar".to_string(),
26499                            args,
26500                        });
26501                    }
26502                    if (first.eq_ignore_ascii_case("substring")
26503                        || first.eq_ignore_ascii_case("substr"))
26504                        && args.len() == 1
26505                        && matches!(self.peek(), Token::From | Token::For)
26506                    {
26507                        // `substring(str FROM pos [FOR len])`, or the FOR-only
26508                        // `substring(str FOR len)` which PG treats as FROM 1.
26509                        if matches!(self.peek(), Token::From) {
26510                            self.advance();
26511                            let start = self.parse_expr(0)?;
26512                            args.push(start);
26513                        } else {
26514                            args.push(Expr::Literal(Literal::Integer(1)));
26515                        }
26516                        if matches!(self.peek(), Token::For) {
26517                            self.advance();
26518                            let length = self.parse_expr(0)?;
26519                            args.push(length);
26520                        }
26521                        if !matches!(self.peek(), Token::RParen) {
26522                            return Err(self.err(format!(
26523                                "expected ')' to close substring(... FROM ... [FOR ...]), got {:?}",
26524                                self.peek()
26525                            )));
26526                        }
26527                        self.advance();
26528                        return Ok(Expr::FunctionCall {
26529                            name: first.to_ascii_lowercase(),
26530                            args,
26531                        });
26532                    }
26533                    // PG `overlay(str PLACING repl FROM n [FOR len])`
26534                    // syntactic form. Desugars to the `overlay(str,
26535                    // repl, n[, len])` comma-list shape the evaluator
26536                    // already implements. `PLACING` is not a reserved
26537                    // token in SPG, so it arrives as a bare Ident.
26538                    if first.eq_ignore_ascii_case("overlay")
26539                        && args.len() == 1
26540                        && matches!(self.peek(), Token::Ident(kw) if kw == "placing")
26541                    {
26542                        self.advance(); // consume PLACING
26543                        args.push(self.parse_expr(0)?); // replacement
26544                        if !matches!(self.peek(), Token::From) {
26545                            return Err(self.err(format!(
26546                                "expected FROM in overlay(... PLACING ... FROM ...), got {:?}",
26547                                self.peek()
26548                            )));
26549                        }
26550                        self.advance();
26551                        args.push(self.parse_expr(0)?); // start position
26552                        if matches!(self.peek(), Token::For) {
26553                            self.advance();
26554                            args.push(self.parse_expr(0)?); // length
26555                        }
26556                        if !matches!(self.peek(), Token::RParen) {
26557                            return Err(self.err(format!(
26558                                "expected ')' to close overlay(... PLACING ... FROM ... [FOR ...]), got {:?}",
26559                                self.peek()
26560                            )));
26561                        }
26562                        self.advance();
26563                        return Ok(Expr::FunctionCall {
26564                            name: String::from("overlay"),
26565                            args,
26566                        });
26567                    }
26568                    // `TRIM(chars FROM str)` — the keyword-less
26569                    // spelling lands here after the chars parse
26570                    // (the keyword forms return earlier).
26571                    if first.eq_ignore_ascii_case("trim")
26572                        && args.len() == 1
26573                        && matches!(self.peek(), Token::From)
26574                    {
26575                        self.advance();
26576                        let target = self.parse_expr(0)?;
26577                        if !matches!(self.peek(), Token::RParen) {
26578                            return Err(self.err(format!(
26579                                "expected ')' to close TRIM(chars FROM str), got {:?}",
26580                                self.peek()
26581                            )));
26582                        }
26583                        self.advance();
26584                        let chars = args.pop().expect("one arg");
26585                        return Ok(Expr::FunctionCall {
26586                            name: String::from("btrim"),
26587                            args: alloc::vec![target, chars],
26588                        });
26589                    }
26590                    // v7.24 (round-16 A) — aggregate-internal
26591                    // ordering: `array_agg(x ORDER BY y DESC NULLS
26592                    // LAST)`. Keys close the argument list.
26593                    if matches!(self.peek(), Token::Order) {
26594                        self.advance();
26595                        if !self.peek_is_by() {
26596                            return Err(self.err(format!(
26597                                "expected BY after ORDER in aggregate args, got {:?}",
26598                                self.peek()
26599                            )));
26600                        }
26601                        self.advance();
26602                        loop {
26603                            // v7.39 (round 691) — save/restore, the discipline this parser
26604                            // already uses around `pending_sample_preds`, so a subquery inside
26605                            // a key neither inherits nor leaks the channel.
26606                            let saved_flag = core::mem::replace(&mut self.in_order_by_key, true);
26607                            let saved_coll = self.order_key_collation.take();
26608                            let parsed = self.parse_expr(0);
26609                            self.in_order_by_key = saved_flag;
26610                            let collation =
26611                                core::mem::replace(&mut self.order_key_collation, saved_coll);
26612                            let expr = parsed?;
26613                            let desc = if matches!(self.peek(), Token::Desc) {
26614                                self.advance();
26615                                true
26616                            } else if matches!(self.peek(), Token::Asc) {
26617                                self.advance();
26618                                false
26619                            } else {
26620                                false
26621                            };
26622                            let nulls_first = self.parse_optional_nulls_placement()?;
26623                            agg_order_by.push(OrderBy {
26624                                expr,
26625                                desc,
26626                                nulls_first,
26627                                collation,
26628                            });
26629                            if matches!(self.peek(), Token::Comma) {
26630                                self.advance();
26631                            } else {
26632                                break;
26633                            }
26634                        }
26635                        // v7.39 (round 354, M12) — `SEPARATOR '<s>'` may
26636                        // follow the ORDER BY inside GROUP_CONCAT.
26637                        if self.consume_group_concat_separator(&mut args)? {
26638                            saw_separator = true;
26639                        }
26640                        if !matches!(self.peek(), Token::RParen) {
26641                            return Err(self.err(format!(
26642                                "expected ')' after aggregate ORDER BY, got {:?}",
26643                                self.peek()
26644                            )));
26645                        }
26646                        break;
26647                    }
26648                    // v7.39 (round 354, M12) — …or directly after the
26649                    // arguments (`GROUP_CONCAT(t SEPARATOR '|')`). MySQL's
26650                    // own spelling of what PG passes as string_agg's second
26651                    // argument; it was a parse error, so every MySQL query
26652                    // that names its own separator failed outright.
26653                    if self.consume_group_concat_separator(&mut args)? {
26654                        saw_separator = true;
26655                        break;
26656                    }
26657                    match self.peek() {
26658                        Token::Comma => {
26659                            self.advance();
26660                        }
26661                        Token::RParen => break,
26662                        other => {
26663                            return Err(self.err(format!(
26664                                "expected ',' or ')' in function args, got {other:?}"
26665                            )));
26666                        }
26667                    }
26668                }
26669            }
26670            // v7.39 (round 354, M12) — MySQL's GROUP_CONCAT concatenates
26671            // its value arguments PER ROW: `GROUP_CONCAT(n, ':', t)` is
26672            // `3:c,1:a,…` (measured on MariaDB 11), NOT a second argument
26673            // meaning a separator — that is what the explicit SEPARATOR
26674            // tail is for. Fold them into one `concat(...)` so the
26675            // aggregate keeps its single value argument.
26676            if self.mysql_dialect && first.eq_ignore_ascii_case("group_concat") {
26677                let values = args.len() - usize::from(saw_separator);
26678                if values > 1 {
26679                    let sep_arg = if saw_separator { args.pop() } else { None };
26680                    let folded = Expr::FunctionCall {
26681                        name: "concat".to_string(),
26682                        args: core::mem::take(&mut args),
26683                    };
26684                    args.push(folded);
26685                    if let Some(sep) = sep_arg {
26686                        args.push(sep);
26687                    }
26688                }
26689            }
26690            self.advance(); // consume ')'
26691            // v7.39 (read01 round 77) — named arguments are NOT reordered here
26692            // any more. The parser has no catalog, so it could only ever resolve
26693            // the handful of `make_*` builtins whose parameter names were baked
26694            // into a table right here — every user function got
26695            // "does not support named arguments", though the catalog has been
26696            // storing its parameter names all along. Reordering happens in eval,
26697            // in one place, for builtins and user functions alike.
26698            // v7.32 (round-29) — ordered-set aggregate tail
26699            // `name(direct_args) WITHIN GROUP (ORDER BY …)`
26700            // (percentile_cont / percentile_disc / mode). The sort spec
26701            // lands in the same `order_by` slot a decorated aggregate
26702            // uses; the executor dispatches on the function name. WITHIN
26703            // GROUP and an intra-argument ORDER BY are mutually
26704            // exclusive (PG rejects both).
26705            let within_group_order = self.parse_within_group_clause()?;
26706            if !within_group_order.is_empty() && !agg_order_by.is_empty() {
26707                return Err(self.err(
26708                    "an aggregate may not carry both an in-argument ORDER BY and WITHIN GROUP"
26709                        .into(),
26710                ));
26711            }
26712            let within_group_seen = !within_group_order.is_empty();
26713            let agg_order_by = if within_group_order.is_empty() {
26714                agg_order_by
26715            } else {
26716                within_group_order
26717            };
26718            // v7.32 (round-29) — `name(args) FILTER (WHERE …)`.
26719            let filter = self.parse_filter_clause()?;
26720            // v4.12: window-function tail — `name(args) OVER (...)`.
26721            // Promotes the just-parsed FunctionCall into a
26722            // WindowFunction node carrying partition + order.
26723            // v6.4.2: also accepts `name(args) IGNORE NULLS OVER (...)`
26724            // / `RESPECT NULLS OVER (...)` between the closing paren
26725            // and `OVER`.
26726            let null_treatment = self.parse_null_treatment_modifier();
26727            if let Token::Ident(s) | Token::QuotedIdent(s) = self.peek()
26728                && s.eq_ignore_ascii_case("over")
26729            {
26730                self.advance();
26731                // v7.39 (round 230) — PG implements neither modifier for a
26732                // windowed call and says so (0A000). Both used to be parsed
26733                // and then silently dropped here, so `count(DISTINCT v)
26734                // OVER (…)` quietly answered the non-distinct count.
26735                if agg_distinct {
26736                    return Err(
26737                        self.err("DISTINCT is not implemented for window functions".to_string())
26738                    );
26739                }
26740                if !agg_order_by.is_empty() {
26741                    // PG separates the two shapes that land here: a
26742                    // WITHIN GROUP call is an ordered-set aggregate and gets
26743                    // its own message naming the aggregate; a plain
26744                    // `agg(x ORDER BY y)` gets the generic one.
26745                    let msg = if within_group_seen {
26746                        alloc::format!("OVER is not supported for ordered-set aggregate {first}")
26747                    } else {
26748                        "aggregate ORDER BY is not implemented for window functions".to_string()
26749                    };
26750                    return Err(self.err(msg));
26751                }
26752                let (partition_by, order_by, frame) = self.parse_over_clause()?;
26753                return Ok(Expr::WindowFunction {
26754                    name: first,
26755                    args,
26756                    partition_by,
26757                    order_by,
26758                    frame,
26759                    null_treatment,
26760                    filter,
26761                });
26762            }
26763            if !agg_order_by.is_empty() || agg_distinct || filter.is_some() {
26764                return Ok(Expr::AggregateOrdered {
26765                    call: Box::new(Expr::FunctionCall { name: first, args }),
26766                    order_by: agg_order_by,
26767                    distinct: agg_distinct,
26768                    filter,
26769                });
26770            }
26771            // v7.39 (round 522) — PG declares `date_add` / `date_subtract`
26772            // over TIMESTAMPTZ and has no timestamp overload, so a
26773            // timestamp argument is coerced on the way in and the answer
26774            // is timestamptz — measured: `pg_typeof(date_add(TIMESTAMP
26775            // '2020-01-01', INTERVAL '1 hour'))` is `timestamp with time
26776            // zone`. SPG answered `timestamp without time zone`, dropping
26777            // the offset from every rendering.
26778            //
26779            // Writing the coercion PG performs makes the existing
26780            // argument-driven typing (the one `date_trunc` uses) reach the
26781            // right answer, rather than teaching the type layer a second
26782            // rule. MySQL's DATE_ADD is a different function that returns
26783            // DATE or DATETIME, so this is PG-dialect only.
26784            //
26785            // Out-of-line because this sits on the RECURSIVE descent
26786            // frame: an inline block with locals here costs every nesting
26787            // level, and the suite's deep-nesting sentinel overflowed the
26788            // 512 KiB parser stack the moment one was added (round 430's
26789            // lesson, in the same shape).
26790            if !self.mysql_dialect {
26791                lift_date_add_arg_to_timestamptz(&first, &mut args);
26792            }
26793            return Ok(Expr::FunctionCall { name: first, args });
26794        }
26795        // v7.9.20 — SQL-standard parenless keyword expressions
26796        // (PG treats these as functions called without parens).
26797        // Resolve to a synthetic FunctionCall so the engine's
26798        // eval path reuses the existing function-call routing.
26799        // mailrs G3.
26800        let lc = first.to_ascii_lowercase();
26801        if matches!(
26802            lc.as_str(),
26803            "current_date"
26804                | "current_time"
26805                | "current_timestamp"
26806                | "localtimestamp"
26807                | "localtime"
26808                // v7.37.17 (17.6 siblings) — session-identity SQL-
26809                // standard parenless keywords. current_user /
26810                // session_user / user were already caught by the
26811                // pgwire canned-response shortcut but bare-select
26812                // in the embedded engine went through Expr::Column
26813                // and errored. Adding them here so the parser
26814                // resolves to a synthetic FunctionCall that reuses
26815                // the existing eval/functions.rs dispatch.
26816                | "current_user"
26817                | "session_user"
26818                | "current_role"
26819                | "current_catalog"
26820                | "current_schema"
26821                | "current_database"
26822                // v7.39 (read01 round 51) — PG 16's system_user is parenless too.
26823                | "system_user"
26824        ) {
26825            return Ok(Expr::FunctionCall {
26826                name: lc,
26827                args: Vec::new(),
26828            });
26829        }
26830        Ok(Expr::Column(ColumnName {
26831            qualifier: None,
26832            name: first,
26833        }))
26834    }
26835}
26836
26837/// v7.39 (round 522) — write the coercion PG's `date_add` /
26838/// `date_subtract` signature performs.
26839///
26840/// PG declares both over TIMESTAMPTZ and has no timestamp overload, so a
26841/// timestamp argument is cast on the way in and the answer is
26842/// timestamptz — measured: `pg_typeof(date_add(TIMESTAMP '2020-01-01',
26843/// INTERVAL '1 hour'))` is `timestamp with time zone`. SPG answered
26844/// `timestamp without time zone`, dropping the offset from every
26845/// rendering of the result.
26846///
26847/// Writing the cast the signature implies lets the existing
26848/// argument-driven typing (the one `date_trunc` uses) reach the right
26849/// answer instead of teaching the type layer a second rule. MySQL's
26850/// DATE_ADD is a different function returning DATE or DATETIME, so the
26851/// caller applies this in PG dialect only.
26852///
26853/// A free function, and not a block at the call site, because the caller
26854/// is on the recursive-descent frame chain.
26855#[inline(never)]
26856fn lift_date_add_arg_to_timestamptz(name: &str, args: &mut alloc::vec::Vec<Expr>) {
26857    if args.len() != 2
26858        || !(name.eq_ignore_ascii_case("date_add") || name.eq_ignore_ascii_case("date_subtract"))
26859    {
26860        return;
26861    }
26862    let base = args.remove(0);
26863    args.insert(
26864        0,
26865        Expr::Cast {
26866            expr: Box::new(base),
26867            target: CastTarget::Timestamptz,
26868        },
26869    );
26870}
26871
26872/// v6.8.2 — walk an expression tree and return the first column
26873/// reference's bare name. Used by `parse_create_index_stmt_after_create`
26874/// to derive `CreateIndexStatement.column` from an expression
26875/// key (so downstream planner code resolving a primary column
26876/// position keeps working with expression indexes). Returns
26877/// `None` when the expression has no column ref at all — caller
26878/// surfaces that as a parse error.
26879fn extract_first_column(expr: &Expr) -> Option<String> {
26880    match expr {
26881        Expr::Column(cn) => Some(cn.name.clone()),
26882        Expr::FunctionCall { args, .. } => args.iter().find_map(extract_first_column),
26883        Expr::Binary { lhs, rhs, .. } => {
26884            extract_first_column(lhs).or_else(|| extract_first_column(rhs))
26885        }
26886        Expr::Unary { expr: e, .. } => extract_first_column(e),
26887        // v7.39 (read01 round 93) — a cast wraps its operand: a common
26888        // expression-index key is `lower(col::text)`, where the column
26889        // sits under the `::text` cast inside the function arg. Without
26890        // descending here the key was rejected as "references no column".
26891        Expr::Cast { expr: e, .. } => extract_first_column(e),
26892        // v7.39.2 — and a COLLATE wraps its operand the same way.
26893        // `CREATE INDEX rc ON t (c COLLATE "C" DESC)` stopped naming a
26894        // column the moment the clause became a node instead of being
26895        // absorbed, and the key was rejected as referencing none. This
26896        // is the shape the wildcard below silently produces, which is
26897        // why it is spelled out.
26898        Expr::Collate { expr: e, .. } => extract_first_column(e),
26899        _ => None,
26900    }
26901}
26902
26903fn maybe_not(expr: Expr, negated: bool) -> Expr {
26904    if negated {
26905        Expr::Unary {
26906            op: UnOp::Not,
26907            expr: Box::new(expr),
26908        }
26909    } else {
26910        expr
26911    }
26912}
26913
26914/// v7.39 (round 353, M9/M10) — three operator TOKENS mean different
26915/// things in the two dialects, and SPG read all three PG's way:
26916///
26917/// | token | PG (and SPG) | MySQL, measured |
26918/// |---|---|---|
26919/// | `\|\|` | string concatenation | **OR** — `1 \|\| 0` is 1, not '10' |
26920/// | `&&` | inet / array overlap | **AND** |
26921/// | `<=>` | pgvector cosine distance | **NULL-safe equal** |
26922///
26923/// `1 || 0` answering the string '10' on a MySQL session is a wrong
26924/// answer with no error, which is why they are routed here rather than
26925/// left to the shared table.
26926impl Parser {
26927    fn binop_here(&self, tok: &Token) -> Option<(BinOp, u8)> {
26928        if self.mysql_dialect {
26929            // v7.39 (round 353, M9) — `DIV` is MySQL's truncating integer
26930            // division (`5 DIV 2` is 2, `-7 DIV 2` is -3 — toward zero —
26931            // and `5 DIV 0` is NULL). It is a plain ident to the lexer.
26932            if let Token::Ident(w) = tok
26933                && w.eq_ignore_ascii_case("div")
26934            {
26935                return Some((BinOp::IntDiv, 8));
26936            }
26937            // v7.39 (round 394) — `MOD` is MySQL's modulo operator, a synonym
26938            // for `%` (`10 MOD 3` is 1, `5.5 MOD 2` is 1.5). A plain ident to
26939            // the lexer; the `MOD(x, y)` function form is unaffected (MOD
26940            // there sits in operand position, not infix).
26941            if let Token::Ident(w) = tok
26942                && w.eq_ignore_ascii_case("mod")
26943            {
26944                return Some((BinOp::Mod, 8));
26945            }
26946            // v7.39 (round 407) — `XOR` is MySQL's logical exclusive-or, a
26947            // plain ident to the lexer. Its precedence sits between OR (1)
26948            // and AND (3) — hence rung 2, the slot freed by moving AND up.
26949            if let Token::Ident(w) = tok
26950                && w.eq_ignore_ascii_case("xor")
26951            {
26952                return Some((BinOp::LogicalXor, 2));
26953            }
26954            match tok {
26955                Token::Concat => return Some((BinOp::Or, 1)),
26956                // MySQL's `&&` is logical AND, sharing AND's rung (3).
26957                Token::InetOverlap => return Some((BinOp::And, 3)),
26958                // MySQL's `<=>` is NULL-safe equal, at the comparison rung (5).
26959                Token::CosineDistance => return Some((BinOp::IsNotDistinctFrom, 5)),
26960                _ => {}
26961            }
26962        }
26963        binop_from(tok)
26964    }
26965}
26966
26967// v7.39 (round 407) — precedence ladder. To open a rung for MySQL's `XOR`
26968// (which sits strictly between OR and AND), every level from AND upward was
26969// shifted +1: the ladder is now OR=1, XOR=2, AND=3, IS=4, comparison=5,
26970// distance=6, additive/concat/bitwise=7, multiplicative/JSON=8, prefix=9.
26971// XOR only exists in the MySQL dialect (binop_here); PG never sees it, and
26972// the *relative* order of every PG operator is unchanged by the shift.
26973fn binop_from(tok: &Token) -> Option<(BinOp, u8)> {
26974    let pair = match tok {
26975        Token::Or => (BinOp::Or, 1),
26976        Token::And => (BinOp::And, 3),
26977        Token::Eq => (BinOp::Eq, 5),
26978        Token::NotEq => (BinOp::NotEq, 5),
26979        Token::Lt => (BinOp::Lt, 5),
26980        Token::LtEq => (BinOp::LtEq, 5),
26981        Token::Gt => (BinOp::Gt, 5),
26982        Token::GtEq => (BinOp::GtEq, 5),
26983        // pgvector distance ops all sit on the same rung — tighter than
26984        // comparisons (5) so `col <-> v < threshold` parses correctly.
26985        Token::L2Distance => (BinOp::L2Distance, 6),
26986        // v7.39 (read01 geo_ops.c) — geometric predicates ride the
26987        // comparison rung.
26988        Token::GeomParallel => (BinOp::GeomParallel, 5),
26989        // v7.39 (read01 rangetypes.c) — range `&<` / `&>` on the
26990        // comparison rung.
26991        Token::OverLeft => (BinOp::OverLeft, 5),
26992        Token::OverRight => (BinOp::OverRight, 5),
26993        Token::GeomPerp => (BinOp::GeomPerp, 5),
26994        Token::GeomSameAs => (BinOp::GeomSameAs, 5),
26995        Token::ClosestPoint => (BinOp::ClosestPoint, 6),
26996        Token::GeomHoriz => (BinOp::GeomHoriz, 5),
26997        Token::InnerProduct => (BinOp::InnerProduct, 6),
26998        Token::CosineDistance => (BinOp::CosineDistance, 6),
26999        Token::Plus => (BinOp::Add, 7),
27000        Token::Minus => (BinOp::Sub, 7),
27001        // v7.39 (round 760, F31-B1) — the generic-operator rung. PG
27002        // binds every "other" operator (`||`, `|`, `&`, `#`, the
27003        // pgvector distances above) BETWEEN additive (7) and the
27004        // comparisons (5): `'a' || 1 + 1` is `'a' || 2` → `a2`,
27005        // `a & b + 1` is `a & (b + 1)`, and `flags & $1 = 0` stays
27006        // `(flags & $1) = 0`. They shared rung 7 with `+ -` since v1
27007        // ("matches PG conceptually" — the round-753 audit measured it
27008        // false; the old rung errored on `'a' || 1 + 1` with
27009        // `text + integer`). Same-level chains left-fold, as PG does.
27010        Token::Concat => (BinOp::Concat, 6),
27011        Token::Pipe => (BinOp::BitOr, 6),
27012        Token::Amp => (BinOp::BitAnd, 6),
27013        Token::Star => (BinOp::Mul, 8),
27014        Token::Slash => (BinOp::Div, 8),
27015        Token::Percent => (BinOp::Mod, 8),
27016        // v4.14: JSON path ops bind tighter than comparisons (5)
27017        // and additive (7) so `doc->'k' = 'v'` parses correctly.
27018        // Same rung as the multiplicative ops.
27019        Token::JsonGet => (BinOp::JsonGet, 8),
27020        Token::JsonGetText => (BinOp::JsonGetText, 8),
27021        Token::JsonGetPath => (BinOp::JsonGetPath, 8),
27022        Token::JsonGetPathText => (BinOp::JsonGetPathText, 8),
27023        Token::JsonContains => (BinOp::JsonContains, 8),
27024        Token::JsonPathExists => (BinOp::JsonPathExists, 8),
27025        Token::JsonContainedBy => (BinOp::JsonContainedBy, 8),
27026        Token::JsonKeyExists => (BinOp::JsonKeyExists, 8),
27027        Token::JsonKeysAny => (BinOp::JsonKeysAny, 8),
27028        Token::JsonKeysAll => (BinOp::JsonKeysAll, 8),
27029        Token::JsonDeletePath => (BinOp::JsonDeletePath, 8),
27030        // v7.12.2 — `@@` binds at the comparison rung (looser than
27031        // arithmetic, tighter than AND / OR). PG places `@@` at
27032        // the same precedence as `=` / `<`, so we follow.
27033        Token::TsMatch => (BinOp::TsMatch, 5),
27034        // v7.17.0 Phase 3.P0-47 — PG INET / CIDR containment + overlap.
27035        // PG places these at the comparison rung (same level as `=`),
27036        // so we follow.
27037        Token::InetContainedBy => (BinOp::InetContainedBy, 5),
27038        Token::InetContainedByEq => (BinOp::InetContainedByEq, 5),
27039        Token::InetContains => (BinOp::InetContains, 5),
27040        Token::InetContainsEq => (BinOp::InetContainsEq, 5),
27041        Token::InetOverlap => (BinOp::InetOverlap, 5),
27042        // v7.39 (round 508) — the geometric and pattern-order predicates
27043        // ride the comparison rung, as every other predicate does.
27044        Token::Intersects => (BinOp::Intersects, 5),
27045        Token::IsBelow => (BinOp::IsBelow, 5),
27046        Token::IsAbove => (BinOp::IsAbove, 5),
27047        Token::PatternLt => (BinOp::PatternLt, 5),
27048        Token::PatternLtEq => (BinOp::PatternLtEq, 5),
27049        Token::PatternGt => (BinOp::PatternGt, 5),
27050        Token::PatternGtEq => (BinOp::PatternGtEq, 5),
27051        // `@@@` is the old spelling of `@@` and means exactly it.
27052        Token::TsMatchOld => (BinOp::TsMatch, 5),
27053        _ => return None,
27054    };
27055    Some(pair)
27056}
27057
27058#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
27059// `as f32` here is intentional: vector elements widen / narrow into f32 on
27060// purpose. i64 → f32 loses precision past 2^24, f64 → f32 loses precision
27061// past ~15 decimal digits — both are acceptable for a fixed-precision
27062// pgvector column.
27063/// v7.17.0 Phase 1.3 — words that would otherwise be eaten as an
27064/// implicit table alias and break trailing clauses. WITH lands
27065/// here so `… FROM t WITH NO DATA` doesn't consume WITH as the
27066/// alias for `t`; same for ON / WHERE / HAVING / GROUP / ORDER /
27067/// LIMIT / OFFSET / UNION / EXCEPT / INTERSECT / RETURNING / SET
27068/// / VALUES / FOR / LATERAL — all of which would otherwise be
27069/// silently swallowed by `parse_optional_alias`.
27070fn is_alias_stopword(s: &str) -> bool {
27071    matches!(
27072        s.to_ascii_lowercase().as_str(),
27073        "with"
27074            | "on"
27075            | "where"
27076            | "having"
27077            | "group"
27078            | "order"
27079            | "limit"
27080            | "offset"
27081            | "union"
27082            | "except"
27083            | "intersect"
27084            | "returning"
27085            | "set"
27086            | "values"
27087            | "for"
27088            | "window"
27089            | "tablesample"
27090            | "lateral"
27091            | "left"
27092            | "right"
27093            | "inner"
27094            | "outer"
27095            | "full"
27096            | "cross"
27097            | "join"
27098            | "natural"
27099            | "using"
27100            | "fetch"
27101    )
27102}
27103
27104fn extract_numeric_literal(e: &Expr) -> Option<f32> {
27105    match e {
27106        Expr::Literal(Literal::Integer(n)) => Some(*n as f32),
27107        Expr::Literal(Literal::Float(x)) => Some(*x as f32),
27108        // v7.38 (read01) — a dotted literal is now NUMERIC, so a vector element
27109        // like `2.5` arrives as Literal::Numeric; widen it into f32. (`no_std`,
27110        // so scale the divisor by hand instead of `f32::powi`.)
27111        Expr::Literal(Literal::Numeric { unscaled, scale }) => {
27112            let mut div = 1.0f32;
27113            for _ in 0..*scale {
27114                div *= 10.0;
27115            }
27116            Some(*unscaled as f32 / div)
27117        }
27118        Expr::Unary {
27119            op: UnOp::Neg,
27120            expr,
27121        } => extract_numeric_literal(expr).map(|x| -x),
27122        _ => None,
27123    }
27124}
27125
27126/// Parse the text inside `INTERVAL '...'` into `(months, micros)`. Accepts
27127/// one or more `<n> <unit>` pairs separated by whitespace. `<n>` may be
27128/// negative. Returns `None` if any pair fails to parse or no pair is found.
27129///
27130/// Recognised units (case-insensitive, optional trailing `s`):
27131/// `microsecond`, `millisecond`, `second`, `minute`, `hour`, `day`, `week`,
27132/// `month`, `year`. `week` widens to 7 days; `year` widens to 12 months.
27133/// v7.37.5 β — returns `(months, days, micros)`. `days` is preserved
27134/// as its own dimension so `INTERVAL '1 day'` ≠ `INTERVAL '24 hours'`
27135/// (PG-canonical: DST and month-boundary semantics depend on this).
27136/// `week` rolls into `days` (× 7). Sub-day units flow into `micros`.
27137/// ISO 8601 duration input for INTERVAL: `P1Y2M3DT4H5M6S`. Before the `T`,
27138/// `M` is months; after it, `M` is minutes. Returns `(months, days, micros)`.
27139#[allow(clippy::cast_possible_truncation)]
27140fn parse_iso8601_interval(rest: &str) -> Option<(i32, i32, i64)> {
27141    let mut months: i64 = 0;
27142    let mut days: i64 = 0;
27143    let mut micros: i64 = 0;
27144    let mut in_time = false;
27145    let mut num = alloc::string::String::new();
27146    for ch in rest.chars() {
27147        if ch.is_ascii_digit() || ch == '.' || ch == '-' || ch == '+' {
27148            num.push(ch);
27149            continue;
27150        }
27151        if ch == 'T' || ch == 't' {
27152            if !num.is_empty() {
27153                return None;
27154            }
27155            in_time = true;
27156            continue;
27157        }
27158        let n: f64 = num.parse().ok()?;
27159        num.clear();
27160        match (ch, in_time) {
27161            ('Y' | 'y', false) => months += (n * 12.0) as i64,
27162            ('M', false) => months += n as i64,
27163            ('W' | 'w', false) => days += (n * 7.0) as i64,
27164            ('D' | 'd', false) => days += n as i64,
27165            ('H' | 'h', true) => micros += (n * 3_600_000_000.0) as i64,
27166            ('M', true) => micros += (n * 60_000_000.0) as i64,
27167            ('S' | 's', true) => micros += (n * 1_000_000.0) as i64,
27168            _ => return None,
27169        }
27170    }
27171    if !num.is_empty() {
27172        return None;
27173    }
27174    Some((
27175        i32::try_from(months).ok()?,
27176        i32::try_from(days).ok()?,
27177        micros,
27178    ))
27179}
27180
27181/// PG year-month shorthand for INTERVAL: `1-2` = 1 year 2 mons (an optional
27182/// leading `-` negates the whole value). Rejects date-like strings.
27183fn parse_year_month_interval(s: &str) -> Option<(i32, i32, i64)> {
27184    let (neg, body) = match s.strip_prefix('-') {
27185        Some(b) => (true, b),
27186        None => (false, s),
27187    };
27188    let (y, m) = body.split_once('-')?;
27189    let years: i32 = y.parse().ok()?;
27190    let mons: i32 = m.parse().ok()?;
27191    if years < 0 || mons < 0 {
27192        return None;
27193    }
27194    let total = years.checked_mul(12)?.checked_add(mons)?;
27195    Some((if neg { -total } else { total }, 0, 0))
27196}
27197
27198/// Parse a clock-time interval token `HH:MM[:SS[.ffffff]]` (optionally signed)
27199/// into microseconds. Used for the `3 days 14:30:45` / bare `14:30:45` forms.
27200fn parse_interval_clock(tok: &str) -> Option<i64> {
27201    let (neg, body) = match tok.strip_prefix('-') {
27202        Some(r) => (true, r),
27203        None => (false, tok.strip_prefix('+').unwrap_or(tok)),
27204    };
27205    let mut it = body.split(':');
27206    let h: i64 = it.next()?.parse().ok()?;
27207    let m: i64 = it.next()?.parse().ok()?;
27208    let s_tok = it.next().unwrap_or("0");
27209    if it.next().is_some() {
27210        return None;
27211    }
27212    let sec_us: i64 = if let Some((sec, frac)) = s_tok.split_once('.') {
27213        let sec: i64 = sec.parse().ok()?;
27214        let mut f = alloc::string::String::from(frac);
27215        while f.len() < 6 {
27216            f.push('0');
27217        }
27218        f.truncate(6);
27219        let fus: i64 = f.parse().ok()?;
27220        sec.checked_mul(1_000_000)?.checked_add(fus)?
27221    } else {
27222        s_tok.parse::<i64>().ok()?.checked_mul(1_000_000)?
27223    };
27224    let total = h
27225        .checked_mul(3_600_000_000)?
27226        .checked_add(m.checked_mul(60_000_000)?)?
27227        .checked_add(sec_us)?;
27228    Some(if neg { -total } else { total })
27229}
27230
27231/// v7.39 (read01 round 77) — one canonical name per interval unit, covering
27232/// every spelling PG accepts (measured against live PG18.4, not guessed):
27233/// `min` / `mins` / `m` are minutes, `mon` / `mons` are months, `y` is years.
27234/// Before this, the unit table matched long names only, with an ad-hoc
27235/// `strip_suffix('s')` in front of it — so `'15 min'` (and `hrs`, `secs`,
27236/// `yrs`, every abbreviation anyone actually types) was "cannot parse as
27237/// INTERVAL", and it had also grown arms for the debris that stripping leaves
27238/// behind (`centurie`, `millenniu`). Two parallel unit matches (integer and
27239/// fractional) both read from this one table now.
27240fn canonical_interval_unit(raw: &str) -> Option<&'static str> {
27241    let u = raw.to_ascii_lowercase();
27242    Some(match u.as_str() {
27243        "microsecond" | "microseconds" | "us" | "usec" | "usecs" | "usecond" | "useconds" => {
27244            "microsecond"
27245        }
27246        "millisecond" | "milliseconds" | "ms" | "msec" | "msecs" | "msecond" | "mseconds" => {
27247            "millisecond"
27248        }
27249        "second" | "seconds" | "sec" | "secs" | "s" => "second",
27250        "minute" | "minutes" | "min" | "mins" | "m" => "minute",
27251        "hour" | "hours" | "hr" | "hrs" | "h" => "hour",
27252        "day" | "days" | "d" => "day",
27253        "week" | "weeks" | "w" => "week",
27254        "month" | "months" | "mon" | "mons" => "month",
27255        "year" | "years" | "yr" | "yrs" | "y" => "year",
27256        "decade" | "decades" | "dec" | "decs" => "decade",
27257        "century" | "centuries" | "cent" | "c" => "century",
27258        "millennium" | "millenniums" | "millennia" | "mil" | "mils" => "millennium",
27259        _ => return None,
27260    })
27261}
27262
27263/// v7.39 (read01 round 102) — the six SQL-standard interval fields that can
27264/// qualify an `INTERVAL '…' <FIELD> [TO <FIELD>]` literal.
27265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27266pub(crate) enum IntervalField {
27267    Year,
27268    Month,
27269    Day,
27270    Hour,
27271    Minute,
27272    Second,
27273}
27274
27275/// Recognise an interval field keyword (bare ident, case-insensitive). Plural
27276/// spellings aren't standard for the qualifier position, so only the singular
27277/// forms are accepted.
27278/// v7.39 (round 350, M7) — MySQL's interval units, measured against
27279/// MariaDB 11. QUARTER is three months and WEEK seven days; MICROSECOND
27280/// is the finest. (The compound spellings — `DAY_HOUR` and friends, which
27281/// take a `'1 2'` style literal — are not read here; they stay a parse
27282/// error rather than being silently misread.)
27283/// v7.39 (round 430) — lower a `@name` / `@@name` reference to its call.
27284///
27285/// ONE `@` is a MySQL USER variable: its own per-session namespace, nothing
27286/// to do with a `@@` engine setting, and an unset one reads NULL rather
27287/// than raising. (The parser used to strip every `@`, so `@x` and `@@x`
27288/// were the same node and `SELECT @x` answered "Unknown system variable".)
27289/// For `@@`, the `session.` / `global.` scope is KEPT: a global read must
27290/// not see a session override — measured, after `SET autocommit=0`,
27291/// `@@global.autocommit` is still 1.
27292///
27293/// Out-of-line and NOT a method: `parse_atom` is the giant recursive frame
27294/// the parser's nesting budget is tuned against, and building these
27295/// `String` + `Vec` locals inside it overflowed the guard's stack (the same
27296/// wall `parse_left_right_atom` and friends were factored out for).
27297#[inline(never)]
27298fn variable_ref_atom(raw: &str) -> Expr {
27299    let user_var = !raw.starts_with("@@");
27300    let bare = raw.trim_start_matches('@').to_ascii_lowercase();
27301    Expr::FunctionCall {
27302        name: String::from(if user_var {
27303            "__spg_user_var"
27304        } else {
27305            "__spg_session_var"
27306        }),
27307        args: alloc::vec![Expr::Literal(Literal::String(bare))],
27308    }
27309}
27310
27311fn mysql_interval_unit(tok: &Token) -> Option<&'static str> {
27312    let Token::Ident(s) = tok else { return None };
27313    Some(match () {
27314        () if s.eq_ignore_ascii_case("microsecond") => "microsecond",
27315        () if s.eq_ignore_ascii_case("second") => "second",
27316        () if s.eq_ignore_ascii_case("minute") => "minute",
27317        () if s.eq_ignore_ascii_case("hour") => "hour",
27318        () if s.eq_ignore_ascii_case("day") => "day",
27319        () if s.eq_ignore_ascii_case("week") => "week",
27320        () if s.eq_ignore_ascii_case("month") => "month",
27321        () if s.eq_ignore_ascii_case("quarter") => "quarter",
27322        () if s.eq_ignore_ascii_case("year") => "year",
27323        () => return None,
27324    })
27325}
27326
27327/// v7.39 (round 422) — lower `INTERVAL <expr> <unit>` onto the existing
27328/// `make_interval(years, months, weeks, days, hours, mins, secs)` builtin,
27329/// which constructs the value at run time. Only the slot the unit names
27330/// carries the quantity; QUARTER and MICROSECOND scale it into the nearest
27331/// slot the builtin has (months and fractional seconds respectively).
27332fn make_interval_call(qty: Expr, unit: &str) -> Expr {
27333    let zero = || Expr::Literal(Literal::Integer(0));
27334    let scaled = |op: crate::ast::BinOp, by: Expr| Expr::Binary {
27335        lhs: alloc::boxed::Box::new(qty.clone()),
27336        op,
27337        rhs: alloc::boxed::Box::new(by),
27338    };
27339    // (years, months, weeks, days, hours, mins, secs)
27340    let mut args = alloc::vec![zero(), zero(), zero(), zero(), zero(), zero(), zero()];
27341    match unit {
27342        "year" => args[0] = qty,
27343        "quarter" => {
27344            args[1] = scaled(crate::ast::BinOp::Mul, Expr::Literal(Literal::Integer(3)));
27345        }
27346        "month" => args[1] = qty,
27347        "week" => args[2] = qty,
27348        "day" => args[3] = qty,
27349        "hour" => args[4] = qty,
27350        "minute" => args[5] = qty,
27351        "second" => args[6] = qty,
27352        // The builtin's seconds slot takes a fraction, so microseconds ride
27353        // it scaled down; the divisor is a NUMERIC literal so the division
27354        // stays exact rather than going through a float.
27355        "microsecond" => {
27356            args[6] = scaled(
27357                crate::ast::BinOp::Div,
27358                Expr::Literal(Literal::Numeric {
27359                    unscaled: 1_000_000,
27360                    scale: 0,
27361                }),
27362            );
27363        }
27364        _ => args[3] = qty,
27365    }
27366    Expr::FunctionCall {
27367        name: alloc::string::String::from("make_interval"),
27368        args,
27369    }
27370}
27371
27372/// `(count, unit)` → `(months, days, micros)`.
27373fn scale_mysql_interval(count: &str, unit: &str) -> Option<(i32, i32, i64)> {
27374    let n: i64 = count.trim().parse().ok()?;
27375    Some(match unit {
27376        "microsecond" => (0, 0, n),
27377        "second" => (0, 0, n.checked_mul(1_000_000)?),
27378        "minute" => (0, 0, n.checked_mul(60_000_000)?),
27379        "hour" => (0, 0, n.checked_mul(3_600_000_000)?),
27380        "day" => (0, i32::try_from(n).ok()?, 0),
27381        "week" => (0, i32::try_from(n.checked_mul(7)?).ok()?, 0),
27382        "month" => (i32::try_from(n).ok()?, 0, 0),
27383        "quarter" => (i32::try_from(n.checked_mul(3)?).ok()?, 0, 0),
27384        "year" => (i32::try_from(n.checked_mul(12)?).ok()?, 0, 0),
27385        _ => return None,
27386    })
27387}
27388
27389fn interval_field_of(tok: &Token) -> Option<IntervalField> {
27390    let Token::Ident(s) = tok else { return None };
27391    Some(match () {
27392        () if s.eq_ignore_ascii_case("year") => IntervalField::Year,
27393        () if s.eq_ignore_ascii_case("month") => IntervalField::Month,
27394        () if s.eq_ignore_ascii_case("day") => IntervalField::Day,
27395        () if s.eq_ignore_ascii_case("hour") => IntervalField::Hour,
27396        () if s.eq_ignore_ascii_case("minute") => IntervalField::Minute,
27397        () if s.eq_ignore_ascii_case("second") => IntervalField::Second,
27398        () => return None,
27399    })
27400}
27401
27402/// v7.39 (read01 round 102) — interpret an interval literal under a field
27403/// qualifier. Returns `(months, days, micros)`.
27404///
27405/// * A single field applied to a bare number sets which unit the number means,
27406///   truncated to that field's precision (`INTERVAL '1.5' HOUR` → `01:00:00`);
27407///   SECOND keeps its fraction (`'90.5' SECOND` → `00:01:30.5`).
27408/// * `YEAR TO MONTH` reads the `Y-M` form (`'1-6'` → 1 year 6 months).
27409/// * Every other range, and any literal a single field can't read as a plain
27410///   number (`'2 days' DAY`), falls back to the unqualified parse — SPG's
27411///   interval-text parser already reads the `D H:MM:SS` / `H:MM` forms exactly
27412///   like PG, and the qualifier there only bounds precision.
27413fn interpret_qualified_interval(
27414    text: &str,
27415    (f1, f2): (IntervalField, Option<IntervalField>),
27416) -> Option<(i32, i32, i64)> {
27417    if let Some(f2) = f2 {
27418        if f1 == IntervalField::Year && f2 == IntervalField::Month {
27419            if let Some(m) = parse_year_month_literal(text) {
27420                return Some((m, 0, 0));
27421            }
27422        }
27423        return parse_interval_text(text);
27424    }
27425    // Single field: reinterpret a bare number; otherwise the default parse.
27426    let trimmed = text.trim();
27427    if let Ok(val) = trimmed.parse::<f64>() {
27428        // no_std: f64 has no trunc/round; cast toward zero + round-half-away.
27429        #[allow(clippy::cast_possible_truncation)]
27430        let whole = val as i64;
27431        #[allow(clippy::cast_possible_truncation)]
27432        let secs_micros = {
27433            let m = val * 1_000_000.0;
27434            if m >= 0.0 {
27435                (m + 0.5) as i64
27436            } else {
27437                (m - 0.5) as i64
27438            }
27439        };
27440        return Some(match f1 {
27441            IntervalField::Year => (i32::try_from(whole).ok()?.checked_mul(12)?, 0, 0),
27442            IntervalField::Month => (i32::try_from(whole).ok()?, 0, 0),
27443            IntervalField::Day => (0, i32::try_from(whole).ok()?, 0),
27444            IntervalField::Hour => (0, 0, whole.checked_mul(3_600_000_000)?),
27445            IntervalField::Minute => (0, 0, whole.checked_mul(60_000_000)?),
27446            IntervalField::Second => (0, 0, secs_micros),
27447        });
27448    }
27449    parse_interval_text(text)
27450}
27451
27452/// Parse the `Y-M` (optionally signed) year-to-month literal into total months.
27453fn parse_year_month_literal(text: &str) -> Option<i32> {
27454    let t = text.trim();
27455    let (neg, body) = match t.strip_prefix('-') {
27456        Some(r) => (true, r),
27457        None => (false, t.strip_prefix('+').unwrap_or(t)),
27458    };
27459    let mut it = body.split('-');
27460    let years: i32 = it.next()?.trim().parse().ok()?;
27461    let months: i32 = match it.next() {
27462        Some(m) => m.trim().parse().ok()?,
27463        None => 0,
27464    };
27465    if it.next().is_some() {
27466        return None;
27467    }
27468    let total = years.checked_mul(12)?.checked_add(months)?;
27469    Some(if neg { -total } else { total })
27470}
27471
27472pub fn parse_interval_text(s: &str) -> Option<(i32, i32, i64)> {
27473    // v7.38.19 — the two infinities, answered as the three extreme
27474    // fields PostgreSQL itself puts on the wire for them:
27475    //
27476    //   COPY (SELECT 'infinity'::interval) TO STDOUT (FORMAT binary)
27477    //     … 7fffffffffffffff 7fffffff 7fffffff
27478    //
27479    // So no caller has to know the spelling — every one of them already
27480    // reads the three numbers, and `IntervalKind::from_fields` names
27481    // what they mean.
27482    //
27483    // `inf` is NOT one of them, measured: `'inf'::interval` is *invalid
27484    // input syntax* on PostgreSQL 18.4 while `'inf'::float8` is
27485    // infinity. Interval takes the full word, in any case.
27486    {
27487        let word = s.trim();
27488        let word = word.strip_prefix('@').map_or(word, str::trim);
27489        let (neg, body) = match word.strip_prefix('-') {
27490            Some(rest) => (true, rest.trim_start()),
27491            None => (false, word.strip_prefix('+').map_or(word, str::trim_start)),
27492        };
27493        if body.eq_ignore_ascii_case("infinity") {
27494            return Some(if neg {
27495                (i32::MIN, i32::MIN, i64::MIN)
27496            } else {
27497                (i32::MAX, i32::MAX, i64::MAX)
27498            });
27499        }
27500    }
27501    // v7.39 (read01 timestamp.c) — PG's postgres_verbose forms: a leading
27502    // `@` is decorative; a trailing `ago` negates the whole interval.
27503    let mut trimmed = s.trim();
27504    trimmed = trimmed.strip_prefix('@').map_or(trimmed, str::trim);
27505    let mut negate = false;
27506    if let Some(rest) = trimmed
27507        .strip_suffix("ago")
27508        .filter(|r| r.ends_with(char::is_whitespace) || r.is_empty())
27509    {
27510        negate = true;
27511        trimmed = rest.trim();
27512    }
27513    let finish = |v: Option<(i32, i32, i64)>| -> Option<(i32, i32, i64)> {
27514        let (mo, d, us) = v?;
27515        if negate {
27516            Some((mo.checked_neg()?, d.checked_neg()?, us.checked_neg()?))
27517        } else {
27518            Some((mo, d, us))
27519        }
27520    };
27521    let s = trimmed;
27522    // ISO 8601 duration (`P1Y2M3DT4H`) and PG's year-month shorthand (`1-2`)
27523    // are single tokens, not the `<n> <unit>` pair form handled below.
27524    if let Some(rest) = trimmed.strip_prefix(['P', 'p']) {
27525        return finish(parse_iso8601_interval(rest));
27526    }
27527    if !trimmed.contains(char::is_whitespace) && trimmed.contains('-') {
27528        if let Some(iv) = parse_year_month_interval(trimmed) {
27529            return finish(Some(iv));
27530        }
27531    }
27532    // v7.39 (GUC knife 3, differential) — PG accepts a bare number as
27533    // SECONDS: `INTERVAL '0'` = 00:00:00, `INTERVAL '5'` = 00:00:05,
27534    // fractions kept to the microsecond (`'1.5'` = 00:00:01.5).
27535    if !trimmed.is_empty() && !trimmed.contains(char::is_whitespace) {
27536        if let Ok(n) = trimmed.parse::<i64>() {
27537            return finish(Some((0, 0, n.checked_mul(1_000_000)?)));
27538        }
27539        if let Ok(f) = trimmed.parse::<f64>() {
27540            if f.is_finite() {
27541                #[allow(clippy::cast_possible_truncation)]
27542                return finish(Some((0, 0, (f * 1_000_000.0) as i64)));
27543            }
27544        }
27545    }
27546    // v7.39 (round 243) — PG accepts the number and unit run together
27547    // (`'15h 2m 12s'`); split each token at the digit→letter boundary so
27548    // the `<n> <unit>` pair loop below sees them as two.
27549    let raw_parts: Vec<&str> = s.split_whitespace().collect();
27550    let mut parts: Vec<&str> = Vec::with_capacity(raw_parts.len());
27551    for p in raw_parts {
27552        let boundary = p
27553            .char_indices()
27554            .find(|(i, c)| {
27555                *i > 0
27556                    && c.is_ascii_alphabetic()
27557                    && p[..*i]
27558                        .chars()
27559                        .all(|d| d.is_ascii_digit() || matches!(d, '.' | '-' | '+'))
27560                    && p[..*i].chars().any(|d| d.is_ascii_digit())
27561            })
27562            .map(|(i, _)| i);
27563        match boundary {
27564            Some(i) => {
27565                parts.push(&p[..i]);
27566                parts.push(&p[i..]);
27567            }
27568            None => parts.push(p),
27569        }
27570    }
27571    // A bare clock-time token `HH:MM[:SS[.ffffff]]` carries the time-of-day
27572    // part (PG: `3 days 14:30:45`, or `14:30:45` alone). Extract it; whatever
27573    // remains is the `<n> <unit>` pair form handled below.
27574    let mut clock_us: i64 = 0;
27575    let mut had_clock = false;
27576    if let Some(pos) = parts.iter().position(|p| p.contains(':')) {
27577        clock_us = parse_interval_clock(parts[pos])?;
27578        parts.remove(pos);
27579        had_clock = true;
27580    }
27581    // v7.39 (read01 timestamp.c) — a lone bare number alongside a clock
27582    // time is DAYS (PG: '3 4:05:06' = 3 days 04:05:06).
27583    let mut lone_days: i32 = 0;
27584    if had_clock && parts.len() == 1 {
27585        if let Ok(n) = parts[0].parse::<i64>() {
27586            lone_days = i32::try_from(n).ok()?;
27587            parts.clear();
27588        }
27589    }
27590    if !parts.len().is_multiple_of(2) || (parts.is_empty() && !had_clock && lone_days == 0) {
27591        return None;
27592    }
27593    let mut months: i32 = 0;
27594    let mut days: i32 = lone_days;
27595    let mut micros: i64 = clock_us;
27596    let mut i = 0;
27597    while i < parts.len() {
27598        let unit_stripped = canonical_interval_unit(parts[i + 1])?;
27599        if let Ok(n) = parts[i].parse::<i64>() {
27600            match unit_stripped {
27601                "microsecond" => micros = micros.checked_add(n)?,
27602                "millisecond" => micros = micros.checked_add(n.checked_mul(1_000)?)?,
27603                "second" => micros = micros.checked_add(n.checked_mul(1_000_000)?)?,
27604                "minute" => micros = micros.checked_add(n.checked_mul(60_000_000)?)?,
27605                "hour" => micros = micros.checked_add(n.checked_mul(3_600_000_000)?)?,
27606                "day" => {
27607                    let n32 = i32::try_from(n).ok()?;
27608                    days = days.checked_add(n32)?;
27609                }
27610                "week" => {
27611                    let n32 = i32::try_from(n).ok()?;
27612                    days = days.checked_add(n32.checked_mul(7)?)?;
27613                }
27614                "month" => {
27615                    let n32 = i32::try_from(n).ok()?;
27616                    months = months.checked_add(n32)?;
27617                }
27618                "year" => {
27619                    let n32 = i32::try_from(n).ok()?;
27620                    months = months.checked_add(n32.checked_mul(12)?)?;
27621                }
27622                // v7.39 (read01 timestamp.c) — the larger calendar units.
27623                "decade" => {
27624                    let n32 = i32::try_from(n).ok()?;
27625                    months = months.checked_add(n32.checked_mul(120)?)?;
27626                }
27627                "century" => {
27628                    let n32 = i32::try_from(n).ok()?;
27629                    months = months.checked_add(n32.checked_mul(1200)?)?;
27630                }
27631                "millennium" => {
27632                    let n32 = i32::try_from(n).ok()?;
27633                    months = months.checked_add(n32.checked_mul(12000)?)?;
27634                }
27635                _ => return None,
27636            }
27637        } else if let Ok(f) = parts[i].parse::<f64>() {
27638            // Fractional units cascade down to the next-finer field the way
27639            // PG does: `1.5 days` -> `1 day 12:00:00`, `1.5 months` ->
27640            // `1 mon 15 days` (30-day month), `1.5 years` -> `1 year 6 mons`.
27641            // no_std: f64 has no trunc/fract/round methods, so do them with
27642            // casts (toward-zero) + explicit round-half-away-from-zero.
27643            #[allow(clippy::cast_possible_truncation)]
27644            fn round_i64(x: f64) -> i64 {
27645                if x >= 0.0 {
27646                    (x + 0.5) as i64
27647                } else {
27648                    (x - 0.5) as i64
27649                }
27650            }
27651            #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
27652            fn add_days_frac(days: &mut i32, micros: &mut i64, d: f64) -> Option<()> {
27653                const DAY_US: f64 = 86_400_000_000.0;
27654                let whole = d as i64; // truncates toward zero
27655                let frac = d - whole as f64;
27656                *days = days.checked_add(i32::try_from(whole).ok()?)?;
27657                *micros = micros.checked_add(round_i64(frac * DAY_US))?;
27658                Some(())
27659            }
27660            #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
27661            match unit_stripped {
27662                "microsecond" => micros = micros.checked_add(round_i64(f))?,
27663                "millisecond" => micros = micros.checked_add(round_i64(f * 1_000.0))?,
27664                "second" => micros = micros.checked_add(round_i64(f * 1_000_000.0))?,
27665                "minute" => micros = micros.checked_add(round_i64(f * 60_000_000.0))?,
27666                "hour" => micros = micros.checked_add(round_i64(f * 3_600_000_000.0))?,
27667                "day" => add_days_frac(&mut days, &mut micros, f)?,
27668                "week" => add_days_frac(&mut days, &mut micros, f * 7.0)?,
27669                "month" => {
27670                    let whole = f as i64;
27671                    months = months.checked_add(i32::try_from(whole).ok()?)?;
27672                    add_days_frac(&mut days, &mut micros, (f - whole as f64) * 30.0)?;
27673                }
27674                "year" => {
27675                    let m = f * 12.0;
27676                    let whole = m as i64;
27677                    months = months.checked_add(i32::try_from(whole).ok()?)?;
27678                    add_days_frac(&mut days, &mut micros, (m - whole as f64) * 30.0)?;
27679                }
27680                _ => return None,
27681            }
27682        } else {
27683            return None;
27684        }
27685        i += 2;
27686    }
27687    finish(Some((months, days, micros)))
27688}
27689
27690/// v7.37 — map a scalar type keyword to its [`CastTarget`] for the PG
27691/// `TYPE 'literal'` typed-literal syntax (`time '10:30'` == `'10:30'::time`).
27692/// `interval` is intentionally absent (handled by its own parser arm).
27693/// Returns `None` for names that aren't sensible as a bare typed literal, so
27694/// the caller falls back to treating the ident as a column reference.
27695fn typed_literal_cast_target(ident: &str) -> Option<CastTarget> {
27696    Some(match ident {
27697        "date" => CastTarget::Date,
27698        "timestamp" | "datetime" => CastTarget::Timestamp,
27699        "timestamptz" => CastTarget::Timestamptz,
27700        "bool" | "boolean" => CastTarget::Bool,
27701        "int" | "integer" | "int4" => CastTarget::Int,
27702        "bigint" | "int8" => CastTarget::BigInt,
27703        "float8" | "double precision" => CastTarget::Float,
27704        "uuid" => CastTarget::Uuid,
27705        "bytea" => CastTarget::Bytea,
27706        "json" => CastTarget::Json,
27707        "jsonb" => CastTarget::Jsonb,
27708        // Types without a dedicated CastTarget variant flow through the
27709        // generic Named path (engine resolves via column_type_to_data_type).
27710        "time" | "timetz" | "smallint" | "int2" | "numeric" | "decimal"
27711        | "real" | "float4" | "inet" | "cidr" | "macaddr" | "macaddr8"
27712        | "money" | "bit" | "varbit"
27713        // Geometric types accept the `TYPE 'literal'` prefix spelling too.
27714        | "point" | "line" | "lseg" | "box" | "path" | "polygon" | "circle"
27715        // Range / multirange types likewise.
27716        | "int4range" | "int8range" | "numrange" | "daterange" | "tsrange"
27717        | "tstzrange" | "int4multirange" | "int8multirange" | "nummultirange"
27718        | "datemultirange" | "tsmultirange" | "tstzmultirange"
27719        // v7.39 (read01 round 18) — oid / name / jsonpath literal prefixes.
27720        | "oid" | "name" | "jsonpath" | "pg_lsn" | "varchar" | "text" | "xid" | "xid8" => {
27721            CastTarget::Named(alloc::string::String::from(ident))
27722        }
27723        _ => return None,
27724    })
27725}
27726
27727/// v7.12.4 — map a bare type-name identifier (the form that
27728/// appears in a function arg list or RETURNS clause) to a
27729/// [`ColumnTypeName`]. Returns `None` for unknown / extension
27730/// types so the caller can preserve them as
27731/// [`FunctionArgType::Raw`] / [`FunctionReturn::Other`].
27732///
27733/// Subset of the full column-type grammar — we deliberately
27734/// don't parse parameterised forms (`VARCHAR(n)`, `NUMERIC(p,s)`)
27735/// here because function-arg types in v7.12.4 are mostly the
27736/// bare form (`text`, `int`, `bytea`, …).
27737/// v7.39 (round 315, V19) — does this whole phrase name a type, rather
27738/// than being `name TYPE`?
27739///
27740/// The multi-word spellings SQL allows for a bare argument type, each
27741/// verified accepted by PG 18.4 as `CREATE FUNCTION f(<phrase>)`.
27742///
27743/// NOTE this list also exists in `spg-storage`, which computes the
27744/// signature key from the rendered argument text and has to reach the
27745/// same verdict. The two crates are siblings — neither depends on the
27746/// other — and each already carries its own table of type spellings
27747/// (`map_type_ident_to_column_type_name` here, `normalize_type_name`
27748/// there), so this follows the structure rather than inventing new
27749/// duplication. Recorded as V49.
27750pub fn is_multiword_type_phrase(phrase: &str) -> bool {
27751    let t = phrase.trim().to_ascii_lowercase();
27752    let base = t.split_once('(').map_or(t.as_str(), |(h, _)| h).trim();
27753    matches!(
27754        base,
27755        "double precision"
27756            | "character varying"
27757            | "bit varying"
27758            | "timestamp with time zone"
27759            | "timestamp without time zone"
27760            | "time with time zone"
27761            | "time without time zone"
27762            | "national character"
27763            | "national character varying"
27764    )
27765}
27766
27767fn map_type_ident_to_column_type_name(ident: &str) -> Option<ColumnTypeName> {
27768    Some(match ident.to_ascii_lowercase().as_str() {
27769        "smallint" | "tinyint" => ColumnTypeName::SmallInt,
27770        "int" | "integer" | "mediumint" => ColumnTypeName::Int,
27771        "bigint" => ColumnTypeName::BigInt,
27772        "float" | "double" => ColumnTypeName::Float,
27773        // v7.39 (round 269) — real is 32-bit.
27774        "real" | "float4" => ColumnTypeName::Real,
27775        "text" => ColumnTypeName::Text,
27776        "bool" | "boolean" => ColumnTypeName::Bool,
27777        "date" => ColumnTypeName::Date,
27778        "timestamp" | "datetime" => ColumnTypeName::Timestamp,
27779        "timestamptz" => ColumnTypeName::Timestamptz,
27780        "json" => ColumnTypeName::Json,
27781        "jsonb" => ColumnTypeName::Jsonb,
27782        "bytea" | "bytes" => ColumnTypeName::Bytes,
27783        "tsvector" => ColumnTypeName::TsVector,
27784        "tsquery" => ColumnTypeName::TsQuery,
27785        "uuid" => ColumnTypeName::Uuid,
27786        "interval" => ColumnTypeName::Interval,
27787        "time" => ColumnTypeName::Time,
27788        "year" => ColumnTypeName::Year,
27789        "timetz" => ColumnTypeName::TimeTz,
27790        "money" => ColumnTypeName::Money,
27791        _ => return None,
27792    })
27793}
27794
27795/// v7.12.4 — parse a PL/pgSQL function body (the bytes between
27796/// `$$ ... $$`). Returns the parsed `BEGIN ... END;` block.
27797///
27798/// v7.12.4 grammar (strict subset — IF / LOOP / DECLARE / RAISE
27799/// / embedded SQL land in v7.12.5+):
27800///
27801/// ```text
27802///   body          := [ws] block [ws]
27803///   block         := BEGIN stmt ( ; stmt )* [ ; ] END [ ; ]
27804///   stmt          := assign | return
27805///   assign        := assign_target := expr
27806///   assign_target := ( NEW | OLD ) . ident | ident
27807///   return        := RETURN ( NEW | OLD | NULL | expr )
27808/// ```
27809///
27810/// `expr` is parsed by recursing into the regular `Parser` — so a
27811/// PL/pgSQL `NEW.search_vector := to_tsvector('english',
27812/// NEW.subject || ' ' || NEW.sender)` body shape works without
27813/// the body parser knowing what `to_tsvector` is.
27814///
27815/// Errors here cause the caller to fall back to
27816/// `FunctionBody::Raw` — keeping the CREATE FUNCTION DDL itself
27817/// successful, but the executor will refuse to invoke the
27818/// function with an "unparseable body" error.
27819/// v7.12.4 — public alias for [`parse_plpgsql_body`] re-exported
27820/// from the crate root as `spg_sql::parse_function_body`.
27821pub fn parse_function_body(body: &str) -> Result<PlPgSqlBlock, ParseError> {
27822    parse_plpgsql_body(body)
27823}
27824
27825fn parse_plpgsql_body(body: &str) -> Result<PlPgSqlBlock, ParseError> {
27826    // Use the regular lexer on the body text. The trailing
27827    // `END;` may or may not have a semicolon; the lexer treats
27828    // both forms identically.
27829    let tokens = lexer::tokenize(body).map_err(|e| ParseError {
27830        message: alloc::format!("plpgsql body lex error: {e}"),
27831        token_pos: 0,
27832    })?;
27833    let mut parser = Parser::new(tokens);
27834    parser.parse_plpgsql_block()
27835}
27836
27837/// v7.39 (GUC) — the textual body of a SET value, for list joining.
27838fn set_value_text(v: &crate::ast::SetValue) -> alloc::string::String {
27839    match v {
27840        crate::ast::SetValue::String(s)
27841        | crate::ast::SetValue::Ident(s)
27842        | crate::ast::SetValue::Number(s) => s.clone(),
27843        crate::ast::SetValue::Default => "DEFAULT".into(),
27844    }
27845}
27846
27847/// v7.39 (round 145, parse_cte.c / parse_agg.c) — true when an expression
27848/// contains an aggregate call at ITS OWN query level (recursion stops at
27849/// sublink boundaries — a sublink's aggregates belong to the sublink).
27850/// Backs the "aggregate functions are not allowed in a recursive query's
27851/// recursive term" well-formedness check.
27852fn expr_has_toplevel_aggregate(e: &Expr) -> bool {
27853    const AGG_NAMES: &[&str] = &[
27854        "count",
27855        "sum",
27856        "min",
27857        "max",
27858        "avg",
27859        "string_agg",
27860        "array_agg",
27861        "bool_and",
27862        "bool_or",
27863        "every",
27864        "any_value",
27865        "json_agg",
27866        "jsonb_agg",
27867        "json_object_agg",
27868        "jsonb_object_agg",
27869        "bit_and",
27870        "bit_or",
27871        "bit_xor",
27872        "var_pop",
27873        "var_samp",
27874        "variance",
27875        "stddev",
27876        "stddev_pop",
27877        "stddev_samp",
27878        "range_agg",
27879        "range_intersect_agg",
27880        "percentile_cont",
27881        "percentile_disc",
27882        "mode",
27883        "corr",
27884        "covar_pop",
27885        "covar_samp",
27886    ];
27887    match e {
27888        Expr::AggregateOrdered { .. } => true,
27889        Expr::FunctionCall { name, args } => {
27890            AGG_NAMES.contains(&name.to_ascii_lowercase().as_str())
27891                || args.iter().any(expr_has_toplevel_aggregate)
27892        }
27893        Expr::NamedArg { expr, .. }
27894        | Expr::Variadic(expr)
27895        | Expr::Unary { expr, .. }
27896        | Expr::Cast { expr, .. }
27897        | Expr::IsNull { expr, .. }
27898        | Expr::FieldAccess { base: expr, .. }
27899        | Expr::Extract { source: expr, .. } => expr_has_toplevel_aggregate(expr),
27900        Expr::Binary { lhs, rhs, .. } => {
27901            expr_has_toplevel_aggregate(lhs) || expr_has_toplevel_aggregate(rhs)
27902        }
27903        Expr::Like { expr, pattern, .. } => {
27904            expr_has_toplevel_aggregate(expr) || expr_has_toplevel_aggregate(pattern)
27905        }
27906        Expr::Array(items) => items.iter().any(expr_has_toplevel_aggregate),
27907        Expr::InList { expr, list, .. } => {
27908            expr_has_toplevel_aggregate(expr) || list.iter().any(expr_has_toplevel_aggregate)
27909        }
27910        Expr::ArraySubscript { target, index } => {
27911            expr_has_toplevel_aggregate(target) || expr_has_toplevel_aggregate(index)
27912        }
27913        Expr::ArraySlice { target, lo, hi } => {
27914            expr_has_toplevel_aggregate(target)
27915                || lo.as_deref().is_some_and(expr_has_toplevel_aggregate)
27916                || hi.as_deref().is_some_and(expr_has_toplevel_aggregate)
27917        }
27918        Expr::AnyAll { expr, array, .. } => {
27919            expr_has_toplevel_aggregate(expr) || expr_has_toplevel_aggregate(array)
27920        }
27921        Expr::Case {
27922            operand,
27923            branches,
27924            else_branch,
27925        } => {
27926            operand.as_deref().is_some_and(expr_has_toplevel_aggregate)
27927                || branches
27928                    .iter()
27929                    .any(|(w, t)| expr_has_toplevel_aggregate(w) || expr_has_toplevel_aggregate(t))
27930                || else_branch
27931                    .as_deref()
27932                    .is_some_and(expr_has_toplevel_aggregate)
27933        }
27934        // The outer-level operands of a sublink can aggregate; the sublink's
27935        // own body cannot leak its aggregates up here.
27936        Expr::InSubquery { expr, .. } => expr_has_toplevel_aggregate(expr),
27937        Expr::RowInSubquery { row, .. } | Expr::RowCmpSubquery { row, .. } => {
27938            row.iter().any(expr_has_toplevel_aggregate)
27939        }
27940        _ => false,
27941    }
27942}
27943
27944/// v7.39 (round 145, parse_cte.c) — true when any sublink expression
27945/// (EXISTS / IN / scalar subquery) inside this SELECT term references the
27946/// named table anywhere in its subtree. A plain FROM derived table is NOT a
27947/// sublink and is legal in a recursive term, so it is not walked here.
27948fn select_has_self_ref_in_sublink(s: &crate::ast::SelectStatement, name: &str) -> bool {
27949    let mut exprs: Vec<&Expr> = Vec::new();
27950    for it in &s.items {
27951        if let crate::ast::SelectItem::Expr { expr, .. } = it {
27952            exprs.push(expr);
27953        }
27954    }
27955    if let Some(w) = &s.where_ {
27956        exprs.push(w);
27957    }
27958    if let Some(h) = &s.having {
27959        exprs.push(h);
27960    }
27961    if let Some(g) = &s.group_by {
27962        exprs.extend(g.iter());
27963    }
27964    if let Some(from) = &s.from {
27965        for j in &from.joins {
27966            if let Some(on) = &j.on {
27967                exprs.push(on);
27968            }
27969        }
27970    }
27971    exprs.into_iter().any(|e| expr_sublink_mentions(e, name))
27972}
27973
27974/// Does this expression contain a sublink whose subquery mentions `name`?
27975fn expr_sublink_mentions(e: &Expr, name: &str) -> bool {
27976    match e {
27977        Expr::ScalarSubquery(sub) => select_mentions_table(sub, name),
27978        Expr::Exists { subquery, .. } => select_mentions_table(subquery, name),
27979        Expr::InSubquery { expr, subquery, .. } => {
27980            expr_sublink_mentions(expr, name) || select_mentions_table(subquery, name)
27981        }
27982        Expr::RowInSubquery { row, subquery, .. } => {
27983            row.iter().any(|x| expr_sublink_mentions(x, name))
27984                || select_mentions_table(subquery, name)
27985        }
27986        Expr::RowCmpSubquery { row, subquery, .. } => {
27987            row.iter().any(|x| expr_sublink_mentions(x, name))
27988                || select_mentions_table(subquery, name)
27989        }
27990        Expr::NamedArg { expr, .. }
27991        | Expr::Variadic(expr)
27992        | Expr::Unary { expr, .. }
27993        | Expr::Cast { expr, .. }
27994        | Expr::IsNull { expr, .. }
27995        | Expr::FieldAccess { base: expr, .. }
27996        | Expr::Extract { source: expr, .. } => expr_sublink_mentions(expr, name),
27997        Expr::Binary { lhs, rhs, .. } => {
27998            expr_sublink_mentions(lhs, name) || expr_sublink_mentions(rhs, name)
27999        }
28000        Expr::Like { expr, pattern, .. } => {
28001            expr_sublink_mentions(expr, name) || expr_sublink_mentions(pattern, name)
28002        }
28003        Expr::FunctionCall { args, .. } | Expr::Array(args) => {
28004            args.iter().any(|x| expr_sublink_mentions(x, name))
28005        }
28006        Expr::InList { expr, list, .. } => {
28007            expr_sublink_mentions(expr, name) || list.iter().any(|x| expr_sublink_mentions(x, name))
28008        }
28009        Expr::ArraySubscript { target, index } => {
28010            expr_sublink_mentions(target, name) || expr_sublink_mentions(index, name)
28011        }
28012        Expr::ArraySlice { target, lo, hi } => {
28013            expr_sublink_mentions(target, name)
28014                || lo
28015                    .as_deref()
28016                    .is_some_and(|x| expr_sublink_mentions(x, name))
28017                || hi
28018                    .as_deref()
28019                    .is_some_and(|x| expr_sublink_mentions(x, name))
28020        }
28021        Expr::AnyAll { expr, array, .. } => {
28022            expr_sublink_mentions(expr, name) || expr_sublink_mentions(array, name)
28023        }
28024        Expr::Case {
28025            operand,
28026            branches,
28027            else_branch,
28028        } => {
28029            operand
28030                .as_deref()
28031                .is_some_and(|x| expr_sublink_mentions(x, name))
28032                || branches
28033                    .iter()
28034                    .any(|(w, t)| expr_sublink_mentions(w, name) || expr_sublink_mentions(t, name))
28035                || else_branch
28036                    .as_deref()
28037                    .is_some_and(|x| expr_sublink_mentions(x, name))
28038        }
28039        _ => false,
28040    }
28041}
28042
28043/// Does this SELECT (in full — FROM tables, derived tables, its own
28044/// sublinks, and union arms) mention the named table?
28045fn select_mentions_table(s: &crate::ast::SelectStatement, name: &str) -> bool {
28046    if let Some(from) = &s.from {
28047        if from.primary.name.eq_ignore_ascii_case(name) {
28048            return true;
28049        }
28050        if let Some(sub) = &from.primary.lateral_subquery
28051            && select_mentions_table(sub, name)
28052        {
28053            return true;
28054        }
28055        for j in &from.joins {
28056            if j.table.name.eq_ignore_ascii_case(name) {
28057                return true;
28058            }
28059            if let Some(sub) = &j.table.lateral_subquery
28060                && select_mentions_table(sub, name)
28061            {
28062                return true;
28063            }
28064        }
28065    }
28066    if select_has_self_ref_in_sublink(s, name) {
28067        return true;
28068    }
28069    s.unions.iter().any(|(_, u)| select_mentions_table(u, name))
28070}
28071
28072/// v7.39 (round 284) — fold a constant `LIMIT` / `OFFSET` expression to a
28073/// row count, the way PG evaluates one before applying it.
28074///
28075/// `None` = not a constant (a column, a subquery, a function call).
28076/// `Some(Err(msg))` = PG rejects it, and the message is PG's; `{L}` in the
28077/// message stands in for LIMIT / OFFSET, which the caller substitutes.
28078/// All wordings were read off live PG 18.4.
28079fn fold_limit_constant(e: &crate::ast::Expr) -> Option<Result<i128, alloc::string::String>> {
28080    use crate::ast::{BinOp, Expr, Literal, UnOp};
28081    match e {
28082        Expr::Literal(Literal::Integer(n)) => Some(Ok(i128::from(*n))),
28083        Expr::Literal(Literal::Numeric { unscaled, scale }) => {
28084            Some(Ok(round_scaled_half_away(*unscaled, *scale)))
28085        }
28086        // PG coerces a string by its CONTENT, and fails on the value.
28087        Expr::Literal(Literal::String(t)) => Some(t.trim().parse::<i64>().map_or_else(
28088            |_| {
28089                Err(alloc::format!(
28090                    "invalid input syntax for type bigint: \"{t}\""
28091                ))
28092            },
28093            |n| Ok(i128::from(n)),
28094        )),
28095        Expr::Literal(Literal::Bool(_)) => Some(Err(
28096            "argument of {L} must be type bigint, not type boolean".into(),
28097        )),
28098        Expr::Unary {
28099            op: UnOp::Neg,
28100            expr,
28101        } => match fold_limit_constant(expr)? {
28102            Ok(v) => Some(Ok(-v)),
28103            e @ Err(_) => Some(e),
28104        },
28105        Expr::Binary { lhs, op, rhs } => {
28106            let a = match fold_limit_constant(lhs)? {
28107                Ok(v) => v,
28108                e @ Err(_) => return Some(e),
28109            };
28110            let b = match fold_limit_constant(rhs)? {
28111                Ok(v) => v,
28112                e @ Err(_) => return Some(e),
28113            };
28114            let out = match op {
28115                BinOp::Add => a.checked_add(b),
28116                BinOp::Sub => a.checked_sub(b),
28117                BinOp::Mul => a.checked_mul(b),
28118                BinOp::Div if b != 0 => a.checked_div(b),
28119                BinOp::Div => return Some(Err("division by zero".into())),
28120                BinOp::Mod if b != 0 => a.checked_rem(b),
28121                BinOp::Mod => return Some(Err("division by zero".into())),
28122                _ => return None,
28123            };
28124            // PG evaluates the arithmetic in the operand's own type, so an
28125            // int-by-int product that leaves int range fails there — before
28126            // the row count is ever looked at.
28127            match out {
28128                Some(v) if v > i128::from(i32::MAX) || v < i128::from(i32::MIN) => {
28129                    Some(Err("integer out of range".into()))
28130                }
28131                Some(v) => Some(Ok(v)),
28132                None => Some(Err("integer out of range".into())),
28133            }
28134        }
28135        _ => None,
28136    }
28137}
28138
28139/// Round `unscaled / 10^scale` half away from zero — PG's numeric→bigint
28140/// cast, which is what makes `LIMIT 2.5` keep three rows.
28141fn round_scaled_half_away(unscaled: i128, scale: u16) -> i128 {
28142    if scale == 0 {
28143        return unscaled;
28144    }
28145    let Some(div) = 10i128.checked_pow(u32::from(scale)) else {
28146        return 0;
28147    };
28148    let neg = unscaled < 0;
28149    let mag = unscaled.unsigned_abs() as i128;
28150    let rounded = (mag + div / 2) / div;
28151    if neg { -rounded } else { rounded }
28152}
28153
28154#[cfg(test)]
28155mod tests {
28156    use super::*;
28157    use alloc::string::ToString;
28158
28159    fn parse(s: &str) -> Statement {
28160        parse_statement(s).expect("parse ok")
28161    }
28162
28163    // v7.37.43-T4 sentori cutover acceptance — `release`, `index`,
28164    // `tables`, `partition`, etc. are unreserved keywords per PG's
28165    // `pg_get_keywords()` and MUST be usable as column / table /
28166    // alias names. Pre-T4 every drop-in user whose schema had one
28167    // of these as a column name (sentori events.release, mailrs
28168    // messages.index in some forks) blew the parser up at CREATE
28169    // TABLE time with "expected identifier, got Release". The
28170    // generalisation lives in `unreserved_keyword_text` + the
28171    // `expect_ident_like` and `parse_atom` arms that consult it.
28172    #[test]
28173    fn release_usable_as_column_name_in_create_table() {
28174        let stmt =
28175            parse("CREATE TABLE events (id INT PRIMARY KEY, release TEXT NOT NULL, payload TEXT)");
28176        if let Statement::CreateTable(t) = stmt {
28177            let names: alloc::vec::Vec<&str> = t.columns.iter().map(|c| c.name.as_str()).collect();
28178            assert_eq!(names, alloc::vec!["id", "release", "payload"]);
28179        } else {
28180            panic!("expected CreateTable");
28181        }
28182    }
28183
28184    #[test]
28185    fn release_usable_as_column_ref_in_select_projection() {
28186        // The sentori `0003_partition_events.sql` INSERT-SELECT
28187        // walk references `release` in both column lists; the
28188        // projection-side use exercises `parse_atom`'s relaxed
28189        // identifier set.
28190        parse("SELECT id, release, payload FROM events WHERE id = 1");
28191    }
28192
28193    #[test]
28194    fn release_usable_as_column_ref_in_insert_column_list() {
28195        // INSERT INTO t (id, release, payload) VALUES (…)
28196        parse("INSERT INTO events (id, release, payload) VALUES (1, '1.0.0', 'data')");
28197    }
28198
28199    #[test]
28200    fn alter_column_drop_not_null_uses_keyword_drop_token() {
28201        // Sentori `0013_audit_tombstone.sql` issues
28202        // `ALTER TABLE … ALTER COLUMN x DROP NOT NULL`. The lexer
28203        // emits Token::Drop (not Ident("drop")); the parser must
28204        // accept both in the ALTER COLUMN sub-dispatch.
28205        parse("ALTER TABLE audit_logs ALTER COLUMN org_id DROP NOT NULL");
28206    }
28207
28208    #[test]
28209    fn create_index_accepts_parenthesised_expression_key() {
28210        // sentori `0040_events_bundle_idx.sql` shape — JSONB
28211        // expression index. Pre-T4 the parser bailed at the
28212        // inner `(` with "expected column ident or expression,
28213        // got LParen". The Token::LParen arm in CREATE INDEX
28214        // routes through the expression parser instead.
28215        parse(
28216            "CREATE INDEX IF NOT EXISTS events_bundle_id_idx \
28217             ON events ((payload->'bundle'->>'id'))",
28218        );
28219    }
28220
28221    // v7.30.2 (mailrs round-25 ask 2) — nesting / chain budgets must
28222    // surface as parse errors, never stack overflows (embed hosts
28223    // abort on overflow).
28224    /// The nesting budget is a COUNT; what it has to fit inside is a
28225    /// number of BYTES, and only one of those two is stable across
28226    /// compiler versions. Round 847 measured 30,336 bytes per level
28227    /// after a toolchain move, which puts 64 levels at 1.94 MB and
28228    /// overflows a 2 MiB thread — `nesting_budget_errors_cleanly`
28229    /// aborted instead of erroring, which is precisely the outcome it
28230    /// exists to rule out.
28231    ///
28232    /// So the budget is metered rather than assumed. The ceiling leaves
28233    /// the depth SPG advertises fitting in a default 2 MiB thread with
28234    /// room to spare, in the debug build, where frames are widest.
28235    #[test]
28236    fn nesting_frame_cost_stays_under_ceiling() {
28237        // Room for MAX_NEST_DEPTH levels inside 1.2 MB, so a 2 MiB
28238        // thread keeps a margin for whatever called the parser.
28239        const CEILING: usize = 1_200_000 / MAX_NEST_DEPTH;
28240
28241        frame_meter::reset();
28242        let depth = frame_meter::SAMPLE_HI + 8;
28243        let sql = format!("SELECT {}1{}", "(".repeat(depth), ")".repeat(depth));
28244        parse(&sql);
28245
28246        let per_level = frame_meter::bytes_per_level();
28247        {
28248            extern crate std;
28249            std::eprintln!("nesting frame: {per_level} bytes/level, ceiling {CEILING}");
28250        }
28251        assert!(
28252            per_level <= CEILING,
28253            "{per_level} bytes per nesting level exceeds {CEILING}; \
28254             {MAX_NEST_DEPTH} levels would want {} bytes. Out-line arms \
28255             in parse_expr_inner / parse_unary rather than lowering the \
28256             depth or widening the stack.",
28257            per_level * MAX_NEST_DEPTH
28258        );
28259    }
28260
28261    #[test]
28262    fn nesting_budget_errors_cleanly() {
28263        let depth = MAX_NEST_DEPTH + 50;
28264        let sql = format!("SELECT {}1{}", "(".repeat(depth), ")".repeat(depth));
28265        let err = parse_statement(&sql).expect_err("must reject");
28266        assert!(err.message.contains("nests deeper"), "{err:?}");
28267        // Within budget still parses.
28268        let sql = format!("SELECT {}1{}", "(".repeat(48), ")".repeat(48));
28269        parse(&sql);
28270    }
28271
28272    #[test]
28273    fn binary_chain_budget_errors_cleanly() {
28274        let sql = format!("SELECT 1{}", " + 1".repeat(MAX_BINARY_CHAIN + 50));
28275        let err = parse_statement(&sql).expect_err("must reject");
28276        assert!(err.message.contains("chained binary"), "{err:?}");
28277        // Within budget still parses (chain depth ≤ budget is safe
28278        // for recursive eval/drop on 2 MiB stacks).
28279        let sql = format!("SELECT 1{}", " + 1".repeat(200));
28280        parse(&sql);
28281    }
28282
28283    #[test]
28284    fn in_list_unaffected_by_chain_budget() {
28285        // Flat InList: 20k elements parse fine and stay flat.
28286        let items: alloc::vec::Vec<String> = (0..20_000).map(|k| k.to_string()).collect();
28287        let sql = format!("SELECT 1 WHERE 5 IN ({})", items.join(","));
28288        let Statement::Select(s) = parse(&sql) else {
28289            panic!("expected select")
28290        };
28291        let Some(Expr::InList { list, negated, .. }) = s.where_ else {
28292            panic!("expected flat InList, got {:?}", s.where_)
28293        };
28294        assert_eq!(list.len(), 20_000);
28295        assert!(!negated);
28296    }
28297
28298    fn lit_int(n: i64) -> Expr {
28299        Expr::Literal(Literal::Integer(n))
28300    }
28301
28302    fn col(name: &str) -> Expr {
28303        Expr::Column(ColumnName {
28304            qualifier: None,
28305            name: name.into(),
28306        })
28307    }
28308
28309    #[test]
28310    fn select_single_integer() {
28311        let s = parse("SELECT 1");
28312        let Statement::Select(s) = s else {
28313            panic!("expected SELECT")
28314        };
28315        assert_eq!(s.items.len(), 1);
28316        assert!(s.from.is_none());
28317        assert!(s.where_.is_none());
28318    }
28319
28320    #[test]
28321    fn select_multiple_literal_kinds() {
28322        let s = parse("SELECT 1, 'hi', NULL, TRUE, 1.5");
28323        let Statement::Select(s) = s else {
28324            panic!("expected SELECT")
28325        };
28326        assert_eq!(s.items.len(), 5);
28327    }
28328
28329    #[test]
28330    fn select_wildcard_from_table() {
28331        let s = parse("SELECT * FROM users");
28332        let Statement::Select(s) = s else {
28333            panic!("expected SELECT")
28334        };
28335        assert!(matches!(s.items[..], [SelectItem::Wildcard]));
28336        assert_eq!(s.from.as_ref().unwrap().primary.name, "users");
28337    }
28338
28339    #[test]
28340    fn select_with_table_alias() {
28341        let s = parse("SELECT * FROM users AS u");
28342        let Statement::Select(s) = s else {
28343            panic!("expected SELECT")
28344        };
28345        let t = &s.from.as_ref().unwrap().primary;
28346        assert_eq!(t.name, "users");
28347        assert_eq!(t.alias.as_deref(), Some("u"));
28348    }
28349
28350    #[test]
28351    fn select_with_where_eq() {
28352        let s = parse("SELECT a FROM t WHERE a = 1");
28353        let Statement::Select(s) = s else {
28354            panic!("expected SELECT")
28355        };
28356        let w = s.where_.unwrap();
28357        assert_eq!(
28358            w,
28359            Expr::Binary {
28360                lhs: Box::new(col("a")),
28361                op: BinOp::Eq,
28362                rhs: Box::new(lit_int(1)),
28363            }
28364        );
28365    }
28366
28367    #[test]
28368    fn arithmetic_precedence() {
28369        let s = parse("SELECT 1 + 2 * 3");
28370        let Statement::Select(s) = s else {
28371            panic!("expected SELECT")
28372        };
28373        let SelectItem::Expr { expr, .. } = &s.items[0] else {
28374            panic!("wildcard?")
28375        };
28376        assert_eq!(
28377            expr,
28378            &Expr::Binary {
28379                lhs: Box::new(lit_int(1)),
28380                op: BinOp::Add,
28381                rhs: Box::new(Expr::Binary {
28382                    lhs: Box::new(lit_int(2)),
28383                    op: BinOp::Mul,
28384                    rhs: Box::new(lit_int(3)),
28385                }),
28386            }
28387        );
28388    }
28389
28390    #[test]
28391    fn parentheses_override_precedence() {
28392        let s = parse("SELECT (1 + 2) * 3");
28393        let Statement::Select(s) = s else {
28394            panic!("expected SELECT")
28395        };
28396        let SelectItem::Expr { expr, .. } = &s.items[0] else {
28397            panic!()
28398        };
28399        assert_eq!(
28400            expr,
28401            &Expr::Binary {
28402                lhs: Box::new(Expr::Binary {
28403                    lhs: Box::new(lit_int(1)),
28404                    op: BinOp::Add,
28405                    rhs: Box::new(lit_int(2)),
28406                }),
28407                op: BinOp::Mul,
28408                rhs: Box::new(lit_int(3)),
28409            }
28410        );
28411    }
28412
28413    #[test]
28414    fn not_binds_below_comparison() {
28415        // `NOT a = 1` should parse as `NOT (a = 1)`.
28416        let s = parse("SELECT NOT a = 1 FROM t");
28417        let Statement::Select(s) = s else {
28418            panic!("expected SELECT")
28419        };
28420        let SelectItem::Expr { expr, .. } = &s.items[0] else {
28421            panic!()
28422        };
28423        assert_eq!(
28424            expr,
28425            &Expr::Unary {
28426                op: UnOp::Not,
28427                expr: Box::new(Expr::Binary {
28428                    lhs: Box::new(col("a")),
28429                    op: BinOp::Eq,
28430                    rhs: Box::new(lit_int(1)),
28431                }),
28432            }
28433        );
28434    }
28435
28436    #[test]
28437    fn unary_minus_binds_above_multiplication() {
28438        // `-a * 2` should be `(-a) * 2`.
28439        let s = parse("SELECT -a * 2 FROM t");
28440        let Statement::Select(s) = s else {
28441            panic!("expected SELECT")
28442        };
28443        let SelectItem::Expr { expr, .. } = &s.items[0] else {
28444            panic!()
28445        };
28446        assert_eq!(
28447            expr,
28448            &Expr::Binary {
28449                lhs: Box::new(Expr::Unary {
28450                    op: UnOp::Neg,
28451                    expr: Box::new(col("a")),
28452                }),
28453                op: BinOp::Mul,
28454                rhs: Box::new(lit_int(2)),
28455            }
28456        );
28457    }
28458
28459    #[test]
28460    fn qualified_column() {
28461        let s = parse("SELECT t.col FROM t");
28462        let Statement::Select(s) = s else {
28463            panic!("expected SELECT")
28464        };
28465        let SelectItem::Expr { expr, .. } = &s.items[0] else {
28466            panic!()
28467        };
28468        assert_eq!(
28469            expr,
28470            &Expr::Column(ColumnName {
28471                qualifier: Some("t".into()),
28472                name: "col".into()
28473            })
28474        );
28475    }
28476
28477    #[test]
28478    fn select_item_alias_with_as() {
28479        let s = parse("SELECT a AS y FROM t");
28480        let Statement::Select(s) = s else {
28481            panic!("expected SELECT")
28482        };
28483        let SelectItem::Expr { alias, .. } = &s.items[0] else {
28484            panic!()
28485        };
28486        assert_eq!(alias.as_deref(), Some("y"));
28487    }
28488
28489    #[test]
28490    fn trailing_semicolon_accepted() {
28491        let s = parse("SELECT 1;");
28492        let Statement::Select(s) = s else {
28493            panic!("expected SELECT")
28494        };
28495        assert_eq!(s.items.len(), 1);
28496    }
28497
28498    #[test]
28499    fn boolean_chain_with_and_or_not() {
28500        // (NOT a) OR (b AND (NOT c))
28501        let s = parse("SELECT NOT a OR b AND NOT c FROM t");
28502        let Statement::Select(s) = s else {
28503            panic!("expected SELECT")
28504        };
28505        let SelectItem::Expr { expr, .. } = &s.items[0] else {
28506            panic!()
28507        };
28508        let expected = Expr::Binary {
28509            lhs: Box::new(Expr::Unary {
28510                op: UnOp::Not,
28511                expr: Box::new(col("a")),
28512            }),
28513            op: BinOp::Or,
28514            rhs: Box::new(Expr::Binary {
28515                lhs: Box::new(col("b")),
28516                op: BinOp::And,
28517                rhs: Box::new(Expr::Unary {
28518                    op: UnOp::Not,
28519                    expr: Box::new(col("c")),
28520                }),
28521            }),
28522        };
28523        assert_eq!(expr, &expected);
28524    }
28525
28526    #[test]
28527    fn empty_input_errors() {
28528        // v7.14.0 — pg_dump preambles emit several comment-only
28529        // / blank-line statements that collapse to Statement::
28530        // Empty rather than a parse error. The old "SELECT in
28531        // message" assertion is stale; verify the new contract:
28532        // empty / whitespace / comment-only input parses to
28533        // Statement::Empty.
28534        assert!(matches!(parse_statement("").unwrap(), Statement::Empty));
28535        assert!(matches!(
28536            parse_statement("  \n\t ").unwrap(),
28537            Statement::Empty
28538        ));
28539        // Sanity: malformed-but-non-empty still errors.
28540        assert!(parse_statement("SELECT FROM WHERE").is_err());
28541    }
28542
28543    #[test]
28544    fn unmatched_paren_errors() {
28545        assert!(parse_statement("SELECT (1 + 2").is_err());
28546    }
28547
28548    #[test]
28549    fn display_round_trip_simple_select() {
28550        let original = parse("SELECT a + 1 FROM t WHERE a > 0");
28551        let text = original.to_string();
28552        let again = parse_statement(&text).expect("re-parse");
28553        assert_eq!(original, again);
28554    }
28555
28556    // --- CREATE TABLE & INSERT (v0.3) ---------------------------------------
28557
28558    #[test]
28559    fn create_table_single_column() {
28560        let s = parse("CREATE TABLE foo (a INT)");
28561        let Statement::CreateTable(c) = s else {
28562            panic!("expected CreateTable")
28563        };
28564        assert_eq!(c.name, "foo");
28565        assert_eq!(c.columns.len(), 1);
28566        assert_eq!(c.columns[0].name, "a");
28567        assert_eq!(c.columns[0].ty, ColumnTypeName::Int);
28568        assert!(c.columns[0].nullable);
28569    }
28570
28571    #[test]
28572    fn create_table_multi_column_with_not_null_mix() {
28573        let s = parse("CREATE TABLE u (id INT NOT NULL, name TEXT, score FLOAT NOT NULL, ok BOOL)");
28574        let Statement::CreateTable(c) = s else {
28575            panic!()
28576        };
28577        assert_eq!(c.columns.len(), 4);
28578        assert_eq!(c.columns[0].ty, ColumnTypeName::Int);
28579        assert!(!c.columns[0].nullable);
28580        assert_eq!(c.columns[1].ty, ColumnTypeName::Text);
28581        assert!(c.columns[1].nullable);
28582        assert_eq!(c.columns[2].ty, ColumnTypeName::Float);
28583        assert!(!c.columns[2].nullable);
28584        assert_eq!(c.columns[3].ty, ColumnTypeName::Bool);
28585    }
28586
28587    #[test]
28588    fn create_table_bigint_supported() {
28589        let s = parse("CREATE TABLE accounts (id BIGINT NOT NULL)");
28590        let Statement::CreateTable(c) = s else {
28591            panic!()
28592        };
28593        assert_eq!(c.columns[0].ty, ColumnTypeName::BigInt);
28594    }
28595
28596    #[test]
28597    fn create_table_vector_default_is_f32() {
28598        let s = parse("CREATE TABLE t (v VECTOR(128))");
28599        let Statement::CreateTable(c) = s else {
28600            panic!()
28601        };
28602        assert_eq!(
28603            c.columns[0].ty,
28604            ColumnTypeName::Vector {
28605                dim: 128,
28606                encoding: VecEncoding::F32,
28607            },
28608        );
28609    }
28610
28611    #[test]
28612    fn create_table_vector_using_sq8() {
28613        // v6.0.1: `USING SQ8` selects scalar-quantised encoding.
28614        // Case-insensitive on both `USING` and the encoding name.
28615        for sql in [
28616            "CREATE TABLE t (v VECTOR(128) USING SQ8)",
28617            "CREATE TABLE t (v VECTOR(128) using sq8)",
28618        ] {
28619            let s = parse(sql);
28620            let Statement::CreateTable(c) = s else {
28621                panic!()
28622            };
28623            assert_eq!(
28624                c.columns[0].ty,
28625                ColumnTypeName::Vector {
28626                    dim: 128,
28627                    encoding: VecEncoding::Sq8,
28628                },
28629                "{sql}",
28630            );
28631        }
28632    }
28633
28634    #[test]
28635    fn create_table_vector_using_unknown_errors() {
28636        // v7.16.1 — the inline `USING <encoding>` shape on
28637        // CREATE TABLE column defs was withdrawn before
28638        // v7.14.0 in favour of `CREATE INDEX … USING hnsw
28639        // (col vector_<metric>_ops)`; the parser now rejects
28640        // USING at column-list position with a clearer
28641        // "expected ',' or ')'" message. Test asserts the
28642        // current rejection, not the old "unknown vector
28643        // encoding" string.
28644        let err = parse_statement("CREATE TABLE t (v VECTOR(8) USING PQ8)").unwrap_err();
28645        assert!(
28646            err.message.contains("USING")
28647                || err.message.contains("using")
28648                || err.message.contains("')'")
28649                || err.message.contains("','"),
28650            "expected USING/column-list rejection, got: {}",
28651            err.message
28652        );
28653    }
28654
28655    #[test]
28656    fn vector_using_sq8_display_roundtrips() {
28657        // The Display impl must produce text that re-parses to the
28658        // same AST. Guard for the v6.0.1 `USING SQ8` suffix.
28659        let s = parse("CREATE TABLE t (v VECTOR(64) USING SQ8)");
28660        let Statement::CreateTable(c) = s else {
28661            panic!()
28662        };
28663        assert_eq!(c.columns[0].ty.to_string(), "VECTOR(64) USING SQ8");
28664    }
28665
28666    #[test]
28667    fn parser_recognises_placeholders() {
28668        use crate::ast::{Expr, SelectItem, Statement};
28669        // $N in expression position parses as Expr::Placeholder(N).
28670        let s = parse("SELECT $1, $2 + 1 FROM t WHERE x = $3");
28671        let Statement::Select(sel) = s else { panic!() };
28672        assert!(matches!(
28673            sel.items[0],
28674            SelectItem::Expr {
28675                expr: Expr::Placeholder(1),
28676                alias: None
28677            }
28678        ));
28679        // $2 + 1
28680        let SelectItem::Expr {
28681            expr: Expr::Binary { lhs, rhs, .. },
28682            ..
28683        } = &sel.items[1]
28684        else {
28685            panic!()
28686        };
28687        assert!(matches!(**lhs, Expr::Placeholder(2)));
28688        assert!(matches!(**rhs, Expr::Literal(Literal::Integer(1))));
28689        // WHERE x = $3
28690        let Some(Expr::Binary { rhs, .. }) = sel.where_.as_ref() else {
28691            panic!()
28692        };
28693        assert!(matches!(**rhs, Expr::Placeholder(3)));
28694    }
28695
28696    #[test]
28697    fn parser_rejects_dollar_zero() {
28698        // $0 is not valid in PG; the lexer rejects it.
28699        assert!(parse_statement("SELECT $0").is_err());
28700    }
28701
28702    #[test]
28703    fn placeholder_display_roundtrips() {
28704        // The Display impl must produce text that re-lexes to the
28705        // same Placeholder token.
28706        let s = parse("SELECT $42 FROM t");
28707        let printed = s.to_string();
28708        assert!(printed.contains("$42"));
28709        let again = parse(&printed);
28710        assert_eq!(s, again);
28711    }
28712
28713    #[test]
28714    fn alter_index_rebuild_bare() {
28715        use crate::ast::{AlterIndexTarget, Statement};
28716        let s = parse("ALTER INDEX my_idx REBUILD");
28717        let Statement::AlterIndex(a) = s else {
28718            panic!("expected AlterIndex, got {s:?}")
28719        };
28720        assert_eq!(a.name, "my_idx");
28721        assert_eq!(a.target, AlterIndexTarget::Rebuild { encoding: None });
28722    }
28723
28724    #[test]
28725    fn alter_index_rebuild_with_encoding() {
28726        use crate::ast::{AlterIndexTarget, Statement};
28727        for (sql, want) in [
28728            (
28729                "ALTER INDEX my_idx REBUILD WITH (encoding = F32)",
28730                VecEncoding::F32,
28731            ),
28732            (
28733                "ALTER INDEX my_idx REBUILD WITH (encoding = sq8)",
28734                VecEncoding::Sq8,
28735            ),
28736            (
28737                "ALTER INDEX my_idx REBUILD WITH (encoding = HALF)",
28738                VecEncoding::F16,
28739            ),
28740        ] {
28741            let s = parse(sql);
28742            let Statement::AlterIndex(a) = s else {
28743                panic!("{sql}: expected AlterIndex")
28744            };
28745            assert_eq!(a.name, "my_idx");
28746            assert_eq!(
28747                a.target,
28748                AlterIndexTarget::Rebuild {
28749                    encoding: Some(want)
28750                },
28751                "{sql}"
28752            );
28753        }
28754    }
28755
28756    #[test]
28757    fn alter_index_rebuild_unknown_encoding_errors() {
28758        let err = parse_statement("ALTER INDEX my_idx REBUILD WITH (encoding = PQ8)").unwrap_err();
28759        assert!(
28760            err.message.contains("unknown vector encoding"),
28761            "got: {}",
28762            err.message
28763        );
28764    }
28765
28766    #[test]
28767    fn alter_index_rebuild_display_roundtrips() {
28768        for (input, want) in [
28769            ("ALTER INDEX my_idx REBUILD", "ALTER INDEX my_idx REBUILD"),
28770            (
28771                "ALTER INDEX my_idx REBUILD WITH (encoding = SQ8)",
28772                "ALTER INDEX my_idx REBUILD WITH (encoding = SQ8)",
28773            ),
28774            (
28775                "ALTER INDEX my_idx REBUILD WITH (encoding = HALF)",
28776                "ALTER INDEX my_idx REBUILD WITH (encoding = HALF)",
28777            ),
28778        ] {
28779            let s = parse(input);
28780            assert_eq!(s.to_string(), want);
28781        }
28782    }
28783
28784    #[test]
28785    fn create_table_unknown_type_defers_to_engine() {
28786        // v4.9 picked XML as a parse-time "unsupported column
28787        // type" probe. v7.17.0 Phase 1.4 changed the contract:
28788        // an unknown type ident parses as Text + `user_type_ref`
28789        // so CREATE TABLE can resolve user-defined enum / domain
28790        // types — rejection of truly-unknown types moved to the
28791        // engine's catalog lookup. v7.37.5 ζ-A then promoted XML
28792        // to a first-class built-in, so this probe switched to a
28793        // synthetic name nothing in the lexer will ever recognise.
28794        let stmt = parse_statement("CREATE TABLE x (a my_user_type)").unwrap();
28795        let Statement::CreateTable(t) = stmt else {
28796            panic!("expected CreateTable");
28797        };
28798        assert_eq!(t.columns[0].user_type_ref.as_deref(), Some("my_user_type"));
28799    }
28800
28801    #[test]
28802    fn create_table_missing_table_keyword_errors() {
28803        assert!(parse_statement("CREATE x (a INT)").is_err());
28804    }
28805
28806    // v7.37.6-B(sentori Epic 2 P0)— `PARTITION BY RANGE` parent +
28807    // `PARTITION OF parent <bounds>` child parse + Display round-trip.
28808
28809    #[test]
28810    fn parse_create_table_partition_by_range() {
28811        use crate::ast::{PartitionBySpec, PartitionKindAst};
28812        let stmt = parse_statement(
28813            "CREATE TABLE events_partitioned (id BIGINT NOT NULL, ts TIMESTAMPTZ NOT NULL, \
28814             payload JSONB) PARTITION BY RANGE (ts)",
28815        )
28816        .unwrap();
28817        let Statement::CreateTable(t) = stmt else {
28818            panic!("expected CreateTable");
28819        };
28820        assert!(t.partition_of.is_none(), "parent has no partition_of");
28821        assert_eq!(t.columns.len(), 3);
28822        let by = t.partition_by.as_ref().expect("expected PARTITION BY");
28823        assert_eq!(
28824            by,
28825            &PartitionBySpec {
28826                kind: PartitionKindAst::Range,
28827                key_columns: alloc::vec!["ts".to_string()],
28828            }
28829        );
28830        // Display round-trip preserves the suffix. `quote_ident`
28831        // only adds double quotes when the ident needs escaping, so
28832        // a plain `ts` survives bare here.
28833        assert!(
28834            t.to_string().contains("PARTITION BY RANGE (ts)"),
28835            "Display lost PARTITION BY suffix: {t}"
28836        );
28837    }
28838
28839    #[test]
28840    fn parse_create_table_partition_of_range() {
28841        use crate::ast::{PartitionOfBoundsAst, PartitionOfSpec};
28842        let stmt = parse_statement(
28843            "CREATE TABLE events_2026_06 PARTITION OF events_partitioned \
28844             FOR VALUES FROM ('2026-06-01 00:00:00+00') TO ('2026-07-01 00:00:00+00')",
28845        )
28846        .unwrap();
28847        let Statement::CreateTable(t) = stmt else {
28848            panic!("expected CreateTable");
28849        };
28850        assert!(t.columns.is_empty(), "child inherits columns from parent");
28851        assert!(t.partition_by.is_none());
28852        let of = t.partition_of.as_ref().expect("expected PARTITION OF");
28853        assert_eq!(of.parent_name, "events_partitioned");
28854        let PartitionOfSpec { bounds, .. } = of.clone();
28855        match bounds {
28856            PartitionOfBoundsAst::Range { lower, upper } => {
28857                assert!(lower.to_string().contains("2026-06-01"));
28858                assert!(upper.to_string().contains("2026-07-01"));
28859            }
28860            other => panic!("expected Range, got {other:?}"),
28861        }
28862        // Display round-trip emits the FOR VALUES tail. `quote_ident`
28863        // skips quotes when not required, so the parent name appears
28864        // bare here.
28865        let s = t.to_string();
28866        assert!(
28867            s.contains("PARTITION OF events_partitioned"),
28868            "Display lost PARTITION OF: {s}"
28869        );
28870        assert!(s.contains("FOR VALUES FROM"), "Display lost FROM: {s}");
28871        assert!(s.contains(") TO ("), "Display lost TO: {s}");
28872    }
28873
28874    #[test]
28875    fn parse_create_table_partition_of_default() {
28876        use crate::ast::PartitionOfBoundsAst;
28877        let stmt =
28878            parse_statement("CREATE TABLE events_default PARTITION OF events_partitioned DEFAULT")
28879                .unwrap();
28880        let Statement::CreateTable(t) = stmt else {
28881            panic!("expected CreateTable");
28882        };
28883        let of = t.partition_of.as_ref().expect("expected PARTITION OF");
28884        assert_eq!(of.parent_name, "events_partitioned");
28885        assert!(matches!(of.bounds, PartitionOfBoundsAst::Default));
28886        assert!(
28887            t.to_string()
28888                .contains("PARTITION OF events_partitioned DEFAULT"),
28889            "Display lost DEFAULT: {t}"
28890        );
28891    }
28892
28893    #[test]
28894    fn parse_create_table_partition_by_list() {
28895        // v7.37.16 (16.1) — `PARTITION BY LIST (key)` parent + a
28896        // child with `FOR VALUES IN (lit, lit, …)`.
28897        use crate::ast::{PartitionBySpec, PartitionKindAst, PartitionOfBoundsAst};
28898        let parent =
28899            parse_statement("CREATE TABLE events_listed (region TEXT) PARTITION BY LIST (region)")
28900                .unwrap();
28901        let Statement::CreateTable(t) = parent else {
28902            panic!("expected CreateTable");
28903        };
28904        let Some(PartitionBySpec {
28905            kind,
28906            ref key_columns,
28907        }) = t.partition_by
28908        else {
28909            panic!("expected PARTITION BY");
28910        };
28911        assert_eq!(kind, PartitionKindAst::List);
28912        assert_eq!(*key_columns, vec!["region".to_string()]);
28913        assert!(t.to_string().contains("PARTITION BY LIST (region)"));
28914
28915        let child = parse_statement(
28916            "CREATE TABLE events_apac PARTITION OF events_listed \
28917             FOR VALUES IN ('jp', 'kr', 'tw')",
28918        )
28919        .unwrap();
28920        let Statement::CreateTable(c) = child else {
28921            panic!("expected CreateTable");
28922        };
28923        let of = c.partition_of.as_ref().expect("expected PARTITION OF");
28924        let PartitionOfBoundsAst::List { values } = &of.bounds else {
28925            panic!("expected List bounds, got {:?}", of.bounds);
28926        };
28927        assert_eq!(values.len(), 3);
28928        let disp = c.to_string();
28929        assert!(disp.contains("FOR VALUES IN ("), "Display lost IN: {disp}");
28930    }
28931
28932    #[test]
28933    fn parse_create_table_partition_by_hash() {
28934        // v7.37.16 (16.2) — `PARTITION BY HASH (key)` parent + a
28935        // child with `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
28936        use crate::ast::{PartitionBySpec, PartitionKindAst, PartitionOfBoundsAst};
28937        let parent =
28938            parse_statement("CREATE TABLE orders_h (id BIGINT) PARTITION BY HASH (id)").unwrap();
28939        let Statement::CreateTable(t) = parent else {
28940            panic!("expected CreateTable");
28941        };
28942        let Some(PartitionBySpec {
28943            kind,
28944            ref key_columns,
28945        }) = t.partition_by
28946        else {
28947            panic!("expected PARTITION BY");
28948        };
28949        assert_eq!(kind, PartitionKindAst::Hash);
28950        assert_eq!(*key_columns, vec!["id".to_string()]);
28951        assert!(t.to_string().contains("PARTITION BY HASH (id)"));
28952
28953        let child = parse_statement(
28954            "CREATE TABLE orders_h_0 PARTITION OF orders_h \
28955             FOR VALUES WITH (MODULUS 4, REMAINDER 0)",
28956        )
28957        .unwrap();
28958        let Statement::CreateTable(c) = child else {
28959            panic!("expected CreateTable");
28960        };
28961        let of = c.partition_of.as_ref().expect("expected PARTITION OF");
28962        let PartitionOfBoundsAst::Hash { modulus, remainder } = of.bounds else {
28963            panic!("expected Hash bounds");
28964        };
28965        assert_eq!(modulus, 4);
28966        assert_eq!(remainder, 0);
28967        let disp = c.to_string();
28968        assert!(
28969            disp.contains("FOR VALUES WITH (MODULUS 4, REMAINDER 0)"),
28970            "Display lost HASH bounds: {disp}"
28971        );
28972
28973        // Validation: REMAINDER ≥ MODULUS is rejected at parse time.
28974        let bad = parse_statement(
28975            "CREATE TABLE orders_h_bad PARTITION OF orders_h \
28976             FOR VALUES WITH (MODULUS 4, REMAINDER 4)",
28977        );
28978        let msg = format!("{}", bad.unwrap_err());
28979        assert!(
28980            msg.contains("REMAINDER") && msg.contains("MODULUS"),
28981            "expected REMAINDER/MODULUS validation error: {msg}"
28982        );
28983    }
28984
28985    #[test]
28986    fn parse_create_table_partition_of_rejects_columns() {
28987        // v7.37.6-B contract: PARTITION OF children inherit columns
28988        // from the parent; an explicit list MUST surface as a parse
28989        // error rather than getting silently ignored.
28990        let err = parse_statement(
28991            "CREATE TABLE events_2026_06 PARTITION OF events_partitioned (id BIGINT) \
28992             FOR VALUES FROM ('a') TO ('b')",
28993        );
28994        assert!(err.is_err(), "expected parse error for explicit columns");
28995        let msg = format!("{}", err.unwrap_err());
28996        assert!(
28997            msg.contains("PARTITION OF") && msg.contains("column"),
28998            "error should mention PARTITION OF + columns: {msg}"
28999        );
29000    }
29001
29002    #[test]
29003    fn insert_single_value() {
29004        let s = parse("INSERT INTO foo VALUES (42)");
29005        let Statement::Insert(i) = s else {
29006            panic!("expected Insert")
29007        };
29008        assert_eq!(i.table, "foo");
29009        assert_eq!(i.rows.len(), 1);
29010        assert_eq!(i.rows[0].len(), 1);
29011        assert!(matches!(i.rows[0][0], Expr::Literal(Literal::Integer(42))));
29012    }
29013
29014    #[test]
29015    fn insert_multi_value_with_mixed_literals() {
29016        let s = parse("INSERT INTO foo VALUES (1, 'hi', 3.14, TRUE, NULL)");
29017        let Statement::Insert(i) = s else { panic!() };
29018        assert_eq!(i.rows.len(), 1);
29019        assert_eq!(i.rows[0].len(), 5);
29020    }
29021
29022    #[test]
29023    fn insert_missing_into_errors() {
29024        assert!(parse_statement("INSERT foo VALUES (1)").is_err());
29025    }
29026
29027    #[test]
29028    fn create_table_round_trip() {
29029        let original =
29030            parse("CREATE TABLE foo (id BIGINT NOT NULL, label TEXT, score FLOAT NOT NULL)");
29031        let text = original.to_string();
29032        let again = parse_statement(&text).expect("re-parse");
29033        assert_eq!(original, again);
29034    }
29035
29036    #[test]
29037    fn insert_round_trip_with_negation_and_string() {
29038        let original = parse("INSERT INTO t VALUES (-1, 'it''s', NULL)");
29039        let text = original.to_string();
29040        let again = parse_statement(&text).expect("re-parse");
29041        assert_eq!(original, again);
29042    }
29043
29044    #[test]
29045    fn unknown_keyword_at_statement_start_errors() {
29046        // v4.4: UPDATE is real SQL now. Use a fabricated keyword so
29047        // the top-level dispatch still has no branch to take.
29048        let err = parse_statement("FROBNICATE foo SET x = 1").unwrap_err();
29049        assert_eq!(err.message, "syntax error at or near \"FROBNICATE\"");
29050    }
29051
29052    // --- v0.8 CREATE INDEX --------------------------------------------------
29053
29054    #[test]
29055    fn create_index_basic() {
29056        let s = parse("CREATE INDEX idx_id ON users (id)");
29057        let Statement::CreateIndex(c) = s else {
29058            panic!("expected CreateIndex")
29059        };
29060        assert_eq!(c.name, "idx_id");
29061        assert_eq!(c.table, "users");
29062        assert_eq!(c.column, "id");
29063    }
29064
29065    #[test]
29066    fn create_index_missing_on_errors() {
29067        assert!(parse_statement("CREATE INDEX foo users (id)").is_err());
29068    }
29069
29070    #[test]
29071    fn create_index_missing_paren_errors() {
29072        assert!(parse_statement("CREATE INDEX foo ON users id").is_err());
29073    }
29074
29075    #[test]
29076    fn create_index_round_trip() {
29077        let original = parse("CREATE INDEX by_name ON users (name)");
29078        let again = parse_statement(&original.to_string()).unwrap();
29079        assert_eq!(original, again);
29080    }
29081
29082    // --- v7.9.29 CREATE UNIQUE INDEX [WHERE pred] (mailrs K1) -------------
29083
29084    #[test]
29085    fn create_unique_index_basic() {
29086        let s = parse("CREATE UNIQUE INDEX uq_x ON t (a)");
29087        let Statement::CreateIndex(c) = s else {
29088            panic!("expected CreateIndex");
29089        };
29090        assert!(c.is_unique);
29091        assert_eq!(c.column, "a");
29092        assert!(c.partial_predicate.is_none());
29093    }
29094
29095    #[test]
29096    fn create_unique_index_partial() {
29097        // mailrs's email_templates "one default per user" shape.
29098        let s = parse(
29099            "CREATE UNIQUE INDEX idx_email_templates_user_default \
29100             ON email_templates (user_address) WHERE is_default = true",
29101        );
29102        let Statement::CreateIndex(c) = s else {
29103            panic!("expected CreateIndex");
29104        };
29105        assert!(c.is_unique);
29106        assert_eq!(c.table, "email_templates");
29107        assert_eq!(c.column, "user_address");
29108        assert!(c.partial_predicate.is_some());
29109    }
29110
29111    #[test]
29112    fn create_unique_index_composite_with_predicate() {
29113        // mailrs's calendar_events instance: composite columns.
29114        let s = parse(
29115            "CREATE UNIQUE INDEX uq_calendar_events_instance \
29116             ON calendar_events (calendar_id, uid, recurrence_id) \
29117             WHERE recurrence_id IS NOT NULL",
29118        );
29119        let Statement::CreateIndex(c) = s else {
29120            panic!("expected CreateIndex");
29121        };
29122        assert!(c.is_unique);
29123        assert_eq!(c.column, "calendar_id");
29124        assert_eq!(
29125            c.extra_columns,
29126            vec!["uid".to_string(), "recurrence_id".to_string()]
29127        );
29128        assert!(c.partial_predicate.is_some());
29129    }
29130
29131    #[test]
29132    fn create_unique_index_using_btree_ok() {
29133        let s = parse("CREATE UNIQUE INDEX uq_x ON t USING btree (a)");
29134        assert!(matches!(s, Statement::CreateIndex(ref c) if c.is_unique));
29135    }
29136
29137    #[test]
29138    fn create_unique_index_using_hnsw_rejected() {
29139        let err =
29140            parse_statement("CREATE UNIQUE INDEX uq_v ON t USING hnsw (embedding)").unwrap_err();
29141        assert!(err.message.contains("UNIQUE"), "{}", err.message);
29142    }
29143
29144    #[test]
29145    fn create_unique_index_round_trip() {
29146        let original = parse(
29147            "CREATE UNIQUE INDEX uq_calendar_events_master \
29148             ON calendar_events (calendar_id, uid) WHERE recurrence_id IS NULL",
29149        );
29150        let again = parse_statement(&original.to_string()).unwrap();
29151        assert_eq!(original, again);
29152    }
29153
29154    #[test]
29155    fn create_unique_without_index_errors() {
29156        let err = parse_statement("CREATE UNIQUE TABLE t (a INT)").unwrap_err();
29157        // v7.39 (round 340, V56) — PG 18.4, verbatim.
29158        assert_eq!(err.message, "syntax error at or near \"TABLE\"");
29159    }
29160
29161    // --- v7.10.4 BYTES / BYTEA column type (Epic 1) ----------------------
29162
29163    #[test]
29164    fn create_table_bytea_column() {
29165        let s = parse("CREATE TABLE t (id INT NOT NULL, payload BYTEA NOT NULL)");
29166        let Statement::CreateTable(c) = s else {
29167            panic!("expected CreateTable");
29168        };
29169        assert_eq!(c.columns.len(), 2);
29170        assert_eq!(c.columns[1].ty, ColumnTypeName::Bytes);
29171        assert!(!c.columns[1].nullable);
29172    }
29173
29174    #[test]
29175    fn create_table_bytes_alias_column() {
29176        let s = parse("CREATE TABLE t (blob BYTES)");
29177        let Statement::CreateTable(c) = s else {
29178            panic!("expected CreateTable");
29179        };
29180        assert_eq!(c.columns[0].ty, ColumnTypeName::Bytes);
29181    }
29182
29183    #[test]
29184    fn bytea_round_trip_display() {
29185        let original = parse("CREATE TABLE t (a BYTEA NOT NULL)");
29186        let again = parse_statement(&original.to_string()).unwrap();
29187        assert_eq!(original, again);
29188    }
29189
29190    // --- v0.9 transactions -------------------------------------------------
29191
29192    #[test]
29193    fn begin_commit_rollback_parse_as_unit_variants() {
29194        let plain = crate::ast::TransactionModes::default();
29195        assert_eq!(parse("BEGIN"), Statement::Begin(plain));
29196        assert_eq!(parse("COMMIT"), Statement::Commit);
29197        // r1066 — PG synonyms pgbench's tpcb script relies on.
29198        assert_eq!(parse("END"), Statement::Commit);
29199        assert_eq!(parse("END TRANSACTION"), Statement::Commit);
29200        assert_eq!(parse("COMMIT WORK"), Statement::Commit);
29201        assert_eq!(parse("ROLLBACK"), Statement::Rollback);
29202        // Trailing semicolons accepted too.
29203        assert_eq!(parse("BEGIN;"), Statement::Begin(plain));
29204        // v7.39 (read01 round 118, B3) — an explicit ISOLATION LEVEL rides the
29205        // statement (with or without the WORK/TRANSACTION noise word).
29206        assert_eq!(
29207            parse("BEGIN ISOLATION LEVEL REPEATABLE READ"),
29208            Statement::Begin(crate::ast::TransactionModes {
29209                isolation: Some(IsolationLevel::RepeatableRead),
29210                read_only: None,
29211            })
29212        );
29213        assert_eq!(
29214            parse("START TRANSACTION ISOLATION LEVEL SERIALIZABLE"),
29215            Statement::Begin(crate::ast::TransactionModes {
29216                isolation: Some(IsolationLevel::Serializable),
29217                read_only: None,
29218            })
29219        );
29220        // v7.39 — this line used to read
29221        //
29222        //     // A non-isolation mode keeps the session default (None).
29223        //     assert_eq!(parse("BEGIN READ ONLY"), Statement::Begin(None));
29224        //
29225        // which pinned the defect rather than catching it: the READ ONLY
29226        // was thrown away, so the statement opened an ordinary read-write
29227        // transaction and every write inside it was accepted. The
29228        // isolation level is still absent here, because this statement
29229        // does not name one — that part was right.
29230        assert_eq!(
29231            parse("BEGIN READ ONLY"),
29232            Statement::Begin(crate::ast::TransactionModes {
29233                isolation: None,
29234                read_only: Some(true),
29235            })
29236        );
29237        assert_eq!(
29238            parse("START TRANSACTION READ WRITE"),
29239            Statement::Begin(crate::ast::TransactionModes {
29240                isolation: None,
29241                read_only: Some(false),
29242            })
29243        );
29244        assert_eq!(
29245            parse("BEGIN ISOLATION LEVEL SERIALIZABLE, READ ONLY"),
29246            Statement::Begin(crate::ast::TransactionModes {
29247                isolation: Some(IsolationLevel::Serializable),
29248                read_only: Some(true),
29249            })
29250        );
29251    }
29252
29253    // --- v1.2: pgvector distance ops + ::vector cast --------------------
29254
29255    #[test]
29256    fn inner_product_binop_parses() {
29257        let s = parse("SELECT v <#> [1.0, 2.0] FROM t");
29258        let Statement::Select(s) = s else { panic!() };
29259        let SelectItem::Expr { expr, .. } = &s.items[0] else {
29260            panic!()
29261        };
29262        assert!(matches!(
29263            expr,
29264            Expr::Binary {
29265                op: BinOp::InnerProduct,
29266                ..
29267            }
29268        ));
29269    }
29270
29271    #[test]
29272    fn cosine_distance_binop_parses() {
29273        let s = parse("SELECT v <=> [1.0, 2.0] FROM t");
29274        let Statement::Select(s) = s else { panic!() };
29275        let SelectItem::Expr { expr, .. } = &s.items[0] else {
29276            panic!()
29277        };
29278        assert!(matches!(
29279            expr,
29280            Expr::Binary {
29281                op: BinOp::CosineDistance,
29282                ..
29283            }
29284        ));
29285    }
29286
29287    #[test]
29288    fn vector_cast_postfix_wraps_string_literal() {
29289        let s = parse("SELECT '[1,2,3]'::vector FROM t");
29290        let Statement::Select(s) = s else { panic!() };
29291        let SelectItem::Expr { expr, .. } = &s.items[0] else {
29292            panic!()
29293        };
29294        assert!(matches!(
29295            expr,
29296            Expr::Cast {
29297                target: CastTarget::Vector,
29298                ..
29299            }
29300        ));
29301    }
29302
29303    #[test]
29304    fn unsupported_cast_target_errors() {
29305        // v7.37.5 ship triage promoted the parser to accept every
29306        // ident as a `CastTarget::Named(canonical)`; the engine
29307        // surfaces the "unsupported cast target" error at eval
29308        // time when `type_name_to_data_type` can't resolve it.
29309        // Parser-side error now requires a NON-ident after `::`
29310        // (e.g. a punctuation token).
29311        let err = parse_statement("SELECT 1::, FROM t").unwrap_err();
29312        assert_eq!(err.message, "syntax error at or near \",\"");
29313    }
29314
29315    #[test]
29316    fn tx_statements_round_trip() {
29317        for q in ["BEGIN", "COMMIT", "ROLLBACK"] {
29318            let original = parse(q);
29319            let again = parse_statement(&original.to_string()).unwrap();
29320            assert_eq!(original, again);
29321        }
29322    }
29323
29324    #[test]
29325    fn interval_text_parsing_units() {
29326        // v7.37.5 β — three-field shape `(months, days, micros)` so
29327        // `'1 day'` and `'24 hours'` no longer collide (PG parity).
29328        // Single unit.
29329        assert_eq!(parse_interval_text("1 day"), Some((0, 1, 0)));
29330        assert_eq!(
29331            parse_interval_text("24 hours"),
29332            Some((0, 0, 86_400_000_000))
29333        );
29334        assert_eq!(parse_interval_text("1 second"), Some((0, 0, 1_000_000)));
29335        assert_eq!(parse_interval_text("1 month"), Some((1, 0, 0)));
29336        assert_eq!(parse_interval_text("2 years"), Some((24, 0, 0)));
29337        assert_eq!(parse_interval_text("1 week"), Some((0, 7, 0)));
29338        // Compound spans accumulate per-dimension.
29339        assert_eq!(parse_interval_text("1 year 6 months"), Some((18, 0, 0)));
29340        assert_eq!(
29341            parse_interval_text("1 day 2 hours"),
29342            Some((0, 1, 7_200_000_000))
29343        );
29344        // Negative numbers carry through per-dimension.
29345        assert_eq!(parse_interval_text("-1 day"), Some((0, -1, 0)));
29346        // Bad shapes return None.
29347        assert_eq!(parse_interval_text(""), None);
29348        assert_eq!(parse_interval_text("garbage"), None);
29349        assert_eq!(parse_interval_text("1 fortnight"), None);
29350        // v7.39 (GUC knife 3) — PG reads a bare number as SECONDS
29351        // (`INTERVAL '1'` = 00:00:01), verified against the oracle.
29352        assert_eq!(parse_interval_text("1"), Some((0, 0, 1_000_000)));
29353        assert_eq!(parse_interval_text("0"), Some((0, 0, 0)));
29354        assert_eq!(parse_interval_text("1.5"), Some((0, 0, 1_500_000)));
29355    }
29356
29357    #[test]
29358    fn interval_literal_roundtrips_via_display() {
29359        let parsed = parse("SELECT INTERVAL '1 day 2 hours'");
29360        let s = parsed.to_string();
29361        // Display preserves the original text verbatim.
29362        assert!(s.contains("INTERVAL '1 day 2 hours'"), "got: {s}");
29363        // And re-parsing yields a structurally equal statement.
29364        let again = parse_statement(&s).unwrap();
29365        assert_eq!(parsed, again);
29366    }
29367
29368    // ── v6.1.2: CREATE / DROP PUBLICATION ────────────────────
29369
29370    #[test]
29371    fn parser_recognises_create_publication_bare() {
29372        let s = parse("CREATE PUBLICATION pub_a");
29373        let Statement::CreatePublication(p) = s else {
29374            panic!("expected CreatePublication, got {s:?}")
29375        };
29376        assert_eq!(p.name, "pub_a");
29377        assert_eq!(p.scope, PublicationScope::AllTables);
29378    }
29379
29380    #[test]
29381    fn parser_recognises_create_publication_for_all_tables() {
29382        let s = parse("CREATE PUBLICATION pub_a FOR ALL TABLES");
29383        let Statement::CreatePublication(p) = s else {
29384            panic!("expected CreatePublication, got {s:?}")
29385        };
29386        assert_eq!(p.name, "pub_a");
29387        assert_eq!(p.scope, PublicationScope::AllTables);
29388    }
29389
29390    #[test]
29391    fn parser_recognises_drop_publication() {
29392        let s = parse("DROP PUBLICATION pub_a");
29393        let Statement::DropPublication { name, .. } = s else {
29394            panic!("expected DropPublication, got {s:?}")
29395        };
29396        assert_eq!(name, "pub_a");
29397    }
29398
29399    #[test]
29400    fn parser_recognises_for_table_list() {
29401        let s = parse("CREATE PUBLICATION pub_a FOR TABLE t1, t2, t3");
29402        let Statement::CreatePublication(p) = s else {
29403            panic!("expected CreatePublication, got {s:?}")
29404        };
29405        assert_eq!(p.name, "pub_a");
29406        let PublicationScope::ForTables(ts) = p.scope else {
29407            panic!("expected ForTables scope")
29408        };
29409        assert_eq!(ts, alloc::vec!["t1", "t2", "t3"]);
29410    }
29411
29412    #[test]
29413    fn parser_rejects_bare_for_tables_and_takes_in_schema() {
29414        // v7.39 (round 754, F31-B5) — PG18-measured: the bare plural
29415        // is rejected (`invalid publication object list`; the old
29416        // test pinned an unverifiable "PG 19 accepts both" claim);
29417        // TABLES pairs with IN SCHEMA.
29418        let err = parse_statement("CREATE PUBLICATION pub_a FOR TABLES t1, t2")
29419            .expect_err("bare FOR TABLES must reject");
29420        assert!(
29421            alloc::format!("{err}").contains("invalid publication object list"),
29422            "got: {err}"
29423        );
29424        let s = parse("CREATE PUBLICATION pub_a FOR TABLES IN SCHEMA public");
29425        let Statement::CreatePublication(p) = s else {
29426            panic!("expected CreatePublication, got {s:?}")
29427        };
29428        let PublicationScope::TablesInSchema(schema) = p.scope else {
29429            panic!("expected TablesInSchema")
29430        };
29431        assert_eq!(schema, "public");
29432    }
29433
29434    #[test]
29435    fn parser_recognises_for_all_tables_except_list() {
29436        let s = parse("CREATE PUBLICATION p FOR ALL TABLES EXCEPT t1, t2");
29437        let Statement::CreatePublication(p) = s else {
29438            panic!()
29439        };
29440        let PublicationScope::AllTablesExcept(ts) = p.scope else {
29441            panic!("expected AllTablesExcept")
29442        };
29443        assert_eq!(ts, alloc::vec!["t1", "t2"]);
29444    }
29445
29446    #[test]
29447    fn parser_rejects_for_table_with_empty_list() {
29448        // `FOR TABLE` with nothing after is a parse error.
29449        let err = parse_statement("CREATE PUBLICATION p FOR TABLE")
29450            .expect_err("must error on empty list");
29451        // No specific message asserted — the call falls through to
29452        // expect_ident_like which yields "expected identifier, got …".
29453        assert!(!err.message.is_empty());
29454    }
29455
29456    #[test]
29457    fn parser_recognises_show_publications() {
29458        // v6.1.3 — SHOW PUBLICATIONS lands here. PUBLICATIONS is a
29459        // bare ident in this position, NOT a reserved keyword.
29460        let s = parse("SHOW PUBLICATIONS");
29461        assert!(matches!(s, Statement::ShowPublications));
29462    }
29463
29464    // ── v6.1.4: CREATE / DROP SUBSCRIPTION + SHOW SUBSCRIPTIONS ─
29465
29466    #[test]
29467    fn parser_recognises_create_subscription_single_publication() {
29468        let s = parse(
29469            "CREATE SUBSCRIPTION sub_a CONNECTION 'host=127.0.0.1 port=20002' PUBLICATION pub_a",
29470        );
29471        let Statement::CreateSubscription(c) = s else {
29472            panic!("expected CreateSubscription, got {s:?}")
29473        };
29474        assert_eq!(c.name, "sub_a");
29475        assert_eq!(c.conn_str, "host=127.0.0.1 port=20002");
29476        assert_eq!(c.publications, alloc::vec!["pub_a"]);
29477    }
29478
29479    #[test]
29480    fn parser_recognises_create_subscription_multi_publication() {
29481        let s = parse("CREATE SUBSCRIPTION sub_a CONNECTION 'host=h' PUBLICATION p1, p2, p3");
29482        let Statement::CreateSubscription(c) = s else {
29483            panic!()
29484        };
29485        assert_eq!(c.publications, alloc::vec!["p1", "p2", "p3"]);
29486    }
29487
29488    #[test]
29489    fn parser_rejects_create_subscription_missing_connection() {
29490        let err = parse_statement("CREATE SUBSCRIPTION s PUBLICATION p")
29491            .expect_err("must error on missing CONNECTION");
29492        assert_eq!(err.message, "syntax error at or near \"PUBLICATION\"");
29493    }
29494
29495    #[test]
29496    fn parser_rejects_create_subscription_missing_publication() {
29497        let err = parse_statement("CREATE SUBSCRIPTION s CONNECTION 'host=x'")
29498            .expect_err("must error on missing PUBLICATION");
29499        assert_eq!(err.message, "syntax error at end of input");
29500    }
29501
29502    #[test]
29503    fn parser_recognises_drop_subscription() {
29504        let s = parse("DROP SUBSCRIPTION sub_a");
29505        let Statement::DropSubscription { name, .. } = s else {
29506            panic!("expected DropSubscription, got {s:?}")
29507        };
29508        assert_eq!(name, "sub_a");
29509    }
29510
29511    #[test]
29512    fn parser_recognises_show_subscriptions() {
29513        let s = parse("SHOW SUBSCRIPTIONS");
29514        assert!(matches!(s, Statement::ShowSubscriptions));
29515    }
29516
29517    #[test]
29518    fn parser_recognises_wait_for_wal_position_no_timeout() {
29519        let s = parse("WAIT FOR WAL POSITION 12345");
29520        let Statement::WaitForWalPosition { pos, timeout_ms } = s else {
29521            panic!("expected WaitForWalPosition, got {s:?}")
29522        };
29523        assert_eq!(pos, 12345);
29524        assert!(timeout_ms.is_none());
29525    }
29526
29527    #[test]
29528    fn parser_recognises_wait_for_wal_position_with_timeout() {
29529        let s = parse("WAIT FOR WAL POSITION 67890 WITH TIMEOUT 5000");
29530        let Statement::WaitForWalPosition { pos, timeout_ms } = s else {
29531            panic!()
29532        };
29533        assert_eq!(pos, 67890);
29534        assert_eq!(timeout_ms, Some(5000));
29535    }
29536
29537    #[test]
29538    fn parser_rejects_wait_with_negative_position() {
29539        // The lexer treats `-` as a token; `expect_u64_literal`
29540        // only sees the Integer that follows, so the negative
29541        // arrives as a unary-minus expression at higher levels.
29542        // Bare `WAIT FOR WAL POSITION -1` thus surfaces as a
29543        // parse error one way or another.
29544        let err = parse_statement("WAIT FOR WAL POSITION -1").unwrap_err();
29545        assert!(!err.message.is_empty());
29546    }
29547
29548    #[test]
29549    fn parser_recognises_bare_analyze() {
29550        let s = parse("ANALYZE");
29551        assert!(matches!(s, Statement::Analyze(None)));
29552    }
29553
29554    #[test]
29555    fn parser_recognises_analyze_with_table() {
29556        let s = parse("ANALYZE users");
29557        let Statement::Analyze(Some(name)) = s else {
29558            panic!("expected Analyze, got {s:?}")
29559        };
29560        assert_eq!(name, "users");
29561    }
29562
29563    #[test]
29564    fn parser_recognises_analyze_with_quoted_table() {
29565        let s = parse("ANALYZE \"Mixed Case\"");
29566        let Statement::Analyze(Some(name)) = s else {
29567            panic!()
29568        };
29569        assert_eq!(name, "Mixed Case");
29570    }
29571
29572    #[test]
29573    fn parser_rejects_analyze_with_garbage_token() {
29574        let err = parse_statement("ANALYZE 42").expect_err("must error");
29575        assert!(!err.message.is_empty());
29576    }
29577
29578    #[test]
29579    fn analyze_display_roundtrips() {
29580        for sql in ["ANALYZE", "ANALYZE users"] {
29581            let s = parse(sql);
29582            let printed = s.to_string();
29583            let again = parse_statement(&printed)
29584                .unwrap_or_else(|e| panic!("re-parse failed for {printed:?}: {e}"));
29585            assert_eq!(s, again);
29586        }
29587    }
29588
29589    #[test]
29590    fn wait_for_display_roundtrips() {
29591        for sql in [
29592            "WAIT FOR WAL POSITION 12345",
29593            "WAIT FOR WAL POSITION 67890 WITH TIMEOUT 5000",
29594        ] {
29595            let s = parse(sql);
29596            let printed = s.to_string();
29597            let again = parse_statement(&printed)
29598                .unwrap_or_else(|e| panic!("re-parse failed for {printed:?}: {e}"));
29599            assert_eq!(s, again, "round-trip mismatch for {sql:?}");
29600        }
29601    }
29602
29603    #[test]
29604    fn subscription_ddl_display_roundtrips() {
29605        for sql in [
29606            "CREATE SUBSCRIPTION sub_a CONNECTION 'host=h port=20002' PUBLICATION pub_a",
29607            "CREATE SUBSCRIPTION sub_b CONNECTION 'host=h' PUBLICATION p1, p2",
29608            "DROP SUBSCRIPTION sub_a",
29609            "SHOW SUBSCRIPTIONS",
29610        ] {
29611            let s = parse(sql);
29612            let printed = s.to_string();
29613            let again = parse_statement(&printed)
29614                .unwrap_or_else(|e| panic!("re-parse failed for {printed:?}: {e}"));
29615            assert_eq!(s, again, "round-trip mismatch for {sql:?}");
29616        }
29617    }
29618
29619    #[test]
29620    fn parser_drop_dispatches_user_vs_publication() {
29621        // Pre-v6.1.2 DROP USER took the bare-ident path; v6.1.2
29622        // tokenises DROP. Both targets must still parse.
29623        let s = parse("DROP USER 'alice'");
29624        let Statement::DropUser { name, .. } = s else {
29625            panic!("expected DropUser, got {s:?}")
29626        };
29627        assert_eq!(name, "alice");
29628        // And DROP PUBLICATION lands the new variant.
29629        let s = parse("DROP PUBLICATION p1");
29630        assert!(matches!(s, Statement::DropPublication { .. }));
29631    }
29632
29633    #[test]
29634    fn publication_ddl_display_roundtrips() {
29635        // Every CREATE PUBLICATION variant must Display → parse →
29636        // same AST. v6.1.3 covers all three scope shapes.
29637        for sql in [
29638            "CREATE PUBLICATION pub_a",
29639            "CREATE PUBLICATION pub_a FOR ALL TABLES",
29640            "CREATE PUBLICATION pub_a FOR TABLE t1, t2",
29641            "CREATE PUBLICATION pub_a FOR ALL TABLES EXCEPT t1",
29642            "DROP PUBLICATION pub_a",
29643            "SHOW PUBLICATIONS",
29644        ] {
29645            let s = parse(sql);
29646            let printed = s.to_string();
29647            let again = parse_statement(&printed)
29648                .unwrap_or_else(|e| panic!("re-parse failed for {printed:?}: {e}"));
29649            assert_eq!(s, again, "round-trip mismatch for {sql:?}");
29650        }
29651    }
29652
29653    // --- v7.12.4: CREATE FUNCTION + CREATE TRIGGER + PL/pgSQL ---
29654
29655    #[test]
29656    fn create_function_returns_trigger_plpgsql_minimal() {
29657        let sql = "CREATE FUNCTION noop() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN RETURN NEW; END; $$";
29658        let s = parse(sql);
29659        let Statement::CreateFunction(f) = s else {
29660            panic!("expected CreateFunction");
29661        };
29662        assert_eq!(f.name, "noop");
29663        assert!(!f.or_replace);
29664        assert!(f.args.is_empty());
29665        assert!(matches!(f.returns, FunctionReturn::Trigger));
29666        assert_eq!(f.language, "plpgsql");
29667        let FunctionBody::PlPgSql(block) = f.body else {
29668            panic!("expected PlPgSql body");
29669        };
29670        assert_eq!(block.statements.len(), 1);
29671        assert!(matches!(
29672            block.statements[0],
29673            PlPgSqlStmt::Return(ReturnTarget::New)
29674        ));
29675    }
29676
29677    #[test]
29678    fn create_function_or_replace_with_assignment() {
29679        // mailrs-shape trigger function: NEW.col := to_tsvector(...);
29680        // RETURN NEW.
29681        let sql = "CREATE OR REPLACE FUNCTION update_sv() RETURNS TRIGGER LANGUAGE plpgsql AS $$
29682BEGIN
29683  NEW.search_vector := to_tsvector('english', NEW.subject);
29684  RETURN NEW;
29685END;
29686$$";
29687        let s = parse(sql);
29688        let Statement::CreateFunction(f) = s else {
29689            panic!("expected CreateFunction");
29690        };
29691        assert!(f.or_replace);
29692        let FunctionBody::PlPgSql(block) = &f.body else {
29693            panic!("expected PlPgSql body");
29694        };
29695        assert_eq!(block.statements.len(), 2);
29696        // First statement: NEW.search_vector := to_tsvector(...)
29697        let PlPgSqlStmt::Assign { target, .. } = &block.statements[0] else {
29698            panic!("expected Assign as first stmt");
29699        };
29700        match target {
29701            AssignTarget::NewColumn(c) => assert_eq!(c, "search_vector"),
29702            other => panic!("expected NEW.col, got {other:?}"),
29703        }
29704        // Second statement: RETURN NEW
29705        assert!(matches!(
29706            block.statements[1],
29707            PlPgSqlStmt::Return(ReturnTarget::New)
29708        ));
29709    }
29710
29711    #[test]
29712    fn create_trigger_after_insert_or_update() {
29713        let sql = "CREATE TRIGGER tg AFTER INSERT OR UPDATE ON messages FOR EACH ROW EXECUTE FUNCTION update_sv()";
29714        let s = parse(sql);
29715        let Statement::CreateTrigger(t) = s else {
29716            panic!("expected CreateTrigger");
29717        };
29718        assert_eq!(t.name, "tg");
29719        assert_eq!(t.table, "messages");
29720        assert_eq!(t.timing, TriggerTiming::After);
29721        assert_eq!(t.events, vec![TriggerEvent::Insert, TriggerEvent::Update]);
29722        assert_eq!(t.for_each, TriggerForEach::Row);
29723        assert_eq!(t.function, "update_sv");
29724    }
29725
29726    #[test]
29727    fn create_trigger_before_delete_execute_procedure_alias() {
29728        // PG also accepts the legacy `EXECUTE PROCEDURE` spelling.
29729        let sql =
29730            "CREATE TRIGGER guard BEFORE DELETE ON t FOR EACH ROW EXECUTE PROCEDURE block_delete()";
29731        let s = parse(sql);
29732        let Statement::CreateTrigger(t) = s else {
29733            panic!("expected CreateTrigger");
29734        };
29735        assert_eq!(t.timing, TriggerTiming::Before);
29736        assert_eq!(t.events, vec![TriggerEvent::Delete]);
29737    }
29738
29739    #[test]
29740    fn drop_trigger_if_exists_round_trips() {
29741        // No parser support for DROP TRIGGER yet — added in v7.12.5
29742        // alongside the broader DROP …{IF EXISTS} cleanup. The
29743        // AST + Display impls are in place so we round-trip via
29744        // construction:
29745        let s = Statement::DropTrigger {
29746            name: "tg".into(),
29747            table: "messages".into(),
29748            if_exists: true,
29749        };
29750        assert_eq!(s.to_string(), "DROP TRIGGER IF EXISTS tg ON messages");
29751    }
29752
29753    #[test]
29754    fn trigger_ddl_display_roundtrips_through_parser() {
29755        // CREATE TRIGGER + its referenced CREATE FUNCTION must
29756        // Display → parse → same AST (modulo PL/pgSQL body
29757        // formatting which is parser-canonicalised).
29758        for sql in [
29759            "CREATE TRIGGER tg AFTER INSERT ON t FOR EACH ROW EXECUTE FUNCTION f()",
29760            "CREATE TRIGGER tg2 BEFORE UPDATE OR DELETE ON t FOR EACH ROW EXECUTE FUNCTION g()",
29761        ] {
29762            let s = parse(sql);
29763            let printed = s.to_string();
29764            let again = parse_statement(&printed)
29765                .unwrap_or_else(|e| panic!("re-parse failed for {printed:?}: {e}"));
29766            assert_eq!(s, again, "round-trip mismatch for {sql:?}");
29767        }
29768    }
29769}