Skip to main content

rudb_parse/
transform.rs

1//! From the parse tree to the AST.
2//!
3//! This is the one module that reads rule names out of the vendored grammar, and that is deliberate
4//! containment: an upstream bump that renames a rule breaks a match arm here and nothing else in
5//! the repository. `spec/04-architecture.md` section 4.5 says this transformer is ours and has to
6//! be total over the rule table, and total is the load bearing word. Every rule reaches a defined
7//! answer. For the ones this milestone covers that answer is an AST node, and for the rest it is a
8//! `Not implemented` error naming the construct, which is what DuckDB itself answers for syntax it
9//! parses and does not support. There is no arm that panics and none that silently drops a clause,
10//! because a dropped clause is a wrong answer and a wrong answer is worse than an error.
11//!
12//! The mechanism that makes it tractable is the default arm. Two thirds of the parse tree is the
13//! expression precedence chain, twenty rules of the form `X <- Y Tail*` that exist to make the
14//! grammar unambiguous and that carry no meaning once it has been parsed. Rather than name all
15//! twenty, the expression walker handles the case where a rule matched something interesting and
16//! otherwise descends through any node with exactly one child. That is not a shortcut. It is the
17//! statement that a rule with one child said nothing, which is true of every chain link, and it
18//! means the twenty first precedence level upstream adds costs us nothing.
19
20use std::collections::HashMap;
21
22use rudb_common::{Error, IdentifierCase, Result, Value};
23
24use crate::ast::{
25    Ast, BinaryOp, CaseArm, ColumnDef, CreateTable, CreateView, Distinct, DropTable, Expr, ExprRef,
26    Insert, JoinKind, LiteralKind, Nulls, Order, OrderItem, Quantifier, Query, QueryBody, QueryRef,
27    Scope, Select, SelectRef, SetOp, Setting, Slice, Source, SourceRef, Statement, StrRef, Target,
28    UnaryOp,
29};
30use crate::generated::rules::PROGRAM;
31use crate::matcher::{NONE, Tree, parse_tokens};
32use crate::token::{Kind, Token};
33use crate::tokenize::tokenize;
34
35/// Parse a script and transform it into the AST.
36///
37/// The tokens are produced once and handed to both halves. Calling [`crate::parse`] here instead
38/// would be shorter and would tokenize the query a second time, which `cargo xtask bench` prices
39/// at about a tenth of the whole front end.
40pub fn parse_ast(query: &str) -> Result<Ast> {
41    parse_ast_with_case(query, IdentifierCase::Preserve)
42}
43
44/// Parse a script while folding its unquoted identifiers for this session.
45pub fn parse_ast_with_case(query: &str, identifier_case: IdentifierCase) -> Result<Ast> {
46    let tokens = tokenize(query)?;
47    let tree = parse_tokens(query, &tokens, PROGRAM, true)?;
48    transform_with_case(query, &tokens, &tree, identifier_case)
49}
50
51/// Transform a parse tree that has already been produced.
52pub fn transform(query: &str, tokens: &[Token], tree: &Tree) -> Result<Ast> {
53    transform_with_case(query, tokens, tree, IdentifierCase::Preserve)
54}
55
56/// Transform a parse tree while folding its unquoted identifiers for this session.
57pub fn transform_with_case(
58    query: &str,
59    tokens: &[Token],
60    tree: &Tree,
61    identifier_case: IdentifierCase,
62) -> Result<Ast> {
63    let mut transform = Transform {
64        query,
65        tokens,
66        tree,
67        ast: Ast::default(),
68        interned: HashMap::new(),
69        anonymous: 0,
70        identifier_case,
71    };
72    transform.program(tree.root())?;
73    Ok(transform.ast)
74}
75
76struct Transform<'a> {
77    query: &'a str,
78    tokens: &'a [Token],
79    tree: &'a Tree,
80    ast: Ast,
81    interned: HashMap<String, StrRef>,
82    /// How many bare `?` parameters have been seen, which is what numbers the next one.
83    anonymous: u32,
84    identifier_case: IdentifierCase,
85}
86
87impl<'a> Transform<'a> {
88    // The parts that walk the parse tree without caring what it says.
89
90    /// The text a node covers.
91    fn text(&self, node: u32) -> &'a str {
92        self.tree.text(node, self.query, self.tokens)
93    }
94
95    /// The name of the rule a node is.
96    fn name(&self, node: u32) -> &'static str {
97        self.tree.name(node)
98    }
99
100    /// The children of a node.
101    ///
102    /// Returned with the tree's lifetime rather than the borrow of `self`, so that the caller can
103    /// iterate it while calling the `&mut self` methods that build the arena. Copying the `&Tree`
104    /// out first is what buys that, and it is why every walker here starts by doing so.
105    fn kids(&self, node: u32) -> impl Iterator<Item = u32> + use<'a> {
106        let tree = self.tree;
107        tree.children(node)
108    }
109
110    /// How many children a node has.
111    fn count(&self, node: u32) -> usize {
112        self.kids(node).count()
113    }
114
115    /// The n'th child, or `NONE`.
116    fn nth(&self, node: u32, n: usize) -> u32 {
117        self.kids(node).nth(n).unwrap_or(NONE)
118    }
119
120    /// The first child, or `NONE`.
121    fn first(&self, node: u32) -> u32 {
122        self.nth(node, 0)
123    }
124
125    /// The first child named `name`, or `NONE`.
126    ///
127    /// Optional parts of a sequence do not leave a placeholder behind, so `SimpleSelect` with a
128    /// `WHERE` and no `GROUP BY` has the where clause as its second child and a `SimpleSelect` with
129    /// neither has something else there. Positional indexing into an optional sequence is the
130    /// single easiest way to write a transformer that is subtly wrong, so nothing here does it.
131    fn find(&self, node: u32, name: &str) -> u32 {
132        self.kids(node).find(|&kid| self.name(kid) == name).unwrap_or(NONE)
133    }
134
135    /// The first node named `name` anywhere under `node`, or `NONE`.
136    fn descendant(&self, node: u32, name: &str) -> u32 {
137        if self.name(node) == name {
138            return node;
139        }
140        self.kids(node)
141            .map(|kid| self.descendant(kid, name))
142            .find(|&found| found != NONE)
143            .unwrap_or(NONE)
144    }
145
146    /// Whether a subtree contains a node with this rule name.
147    fn contains(&self, node: u32, name: &str) -> bool {
148        self.name(node) == name || self.kids(node).any(|kid| self.contains(kid, name))
149    }
150
151    /// Every leaf of a subtree, in order.
152    ///
153    /// A leaf is a rule that matched only terminals, which for a name is the identifier itself. It
154    /// is how all thirty odd spellings of a qualified name collapse into one walk: whether the
155    /// parse said `SchemaQualification ReservedTableQualification ReservedColumnName` or
156    /// `IdentifierDot IdentifierDot ColumnName`, the leaves are the parts in order.
157    fn leaves(&self, node: u32, out: &mut Vec<u32>) {
158        let mut any = false;
159        for kid in self.kids(node) {
160            any = true;
161            self.leaves(kid, &mut *out);
162        }
163        if !any {
164            out.push(node);
165        }
166    }
167
168    // The parts that build the arena.
169
170    /// Intern a string, returning its index.
171    fn intern(&mut self, text: &str) -> StrRef {
172        if let Some(&index) = self.interned.get(text) {
173            return index;
174        }
175        let index = u32::try_from(self.ast.strings.len())
176            .map_err(|_| Error::internal("more than four billion strings in one query"))
177            .unwrap_or(NONE);
178        self.ast.strings.push(text.to_string());
179        self.interned.insert(text.to_string(), index);
180        index
181    }
182
183    /// Push an expression and return its index.
184    fn push(&mut self, expr: Expr) -> ExprRef {
185        let index = self.ast.exprs.len() as u32;
186        self.ast.exprs.push(expr);
187        index
188    }
189
190    /// Push a from item and return its index.
191    fn push_source(&mut self, source: Source) -> SourceRef {
192        let index = self.ast.sources.len() as u32;
193        self.ast.sources.push(source);
194        index
195    }
196
197    /// Push a query and return its index.
198    fn push_query(&mut self, query: Query) -> QueryRef {
199        let index = self.ast.queries.len() as u32;
200        self.ast.queries.push(query);
201        index
202    }
203
204    /// Push a select and return its index.
205    fn push_select(&mut self, select: Select) -> SelectRef {
206        let index = self.ast.selects.len() as u32;
207        self.ast.selects.push(select);
208        index
209    }
210
211    /// Turn a vector of expressions into a slice of the expression list arena.
212    fn expr_slice(&mut self, items: Vec<ExprRef>) -> Slice {
213        let start = self.ast.expr_lists.len() as u32;
214        self.ast.expr_lists.extend(items);
215        Slice { start, len: self.ast.expr_lists.len() as u32 - start }
216    }
217
218    /// Turn a vector of strings into a slice of the name arena.
219    fn part_slice(&mut self, items: Vec<StrRef>) -> Slice {
220        let start = self.ast.parts.len() as u32;
221        self.ast.parts.extend(items);
222        Slice { start, len: self.ast.parts.len() as u32 - start }
223    }
224
225    /// Turn a vector of column definitions into a slice of the column arena.
226    fn column_def_slice(&mut self, items: Vec<ColumnDef>) -> Slice {
227        let start = self.ast.column_defs.len() as u32;
228        self.ast.column_defs.extend(items);
229        Slice { start, len: self.ast.column_defs.len() as u32 - start }
230    }
231
232    /// Turn a vector of targets into a slice of the target arena.
233    fn target_slice(&mut self, items: Vec<Target>) -> Slice {
234        let start = self.ast.targets.len() as u32;
235        self.ast.targets.extend(items);
236        Slice { start, len: self.ast.targets.len() as u32 - start }
237    }
238
239    /// Turn a vector of qualified names into a slice of the name list arena.
240    fn name_list_slice(&mut self, items: Vec<Slice>) -> Slice {
241        let start = self.ast.name_lists.len() as u32;
242        self.ast.name_lists.extend(items);
243        Slice { start, len: self.ast.name_lists.len() as u32 - start }
244    }
245
246    /// The error for a construct the transformer does not cover yet.
247    ///
248    /// Both halves matter. The text is what the user wrote, which is the only part they can act on,
249    /// and the rule name is what we act on, because it is the exact grammar rule to go implement.
250    fn unsupported<T>(&self, node: u32) -> Result<T> {
251        let text = self.text(node);
252        let text = if text.chars().count() > 60 {
253            let cut = text.char_indices().nth(60).map_or(text.len(), |(at, _)| at);
254            format!("{}...", &text[..cut])
255        } else {
256            text.to_string()
257        };
258        Err(Error::not_implemented(format!(
259            "{text} is not supported yet, the grammar rule is {}",
260            self.name(node)
261        )))
262    }
263
264    // Names.
265
266    /// One identifier out of a subtree, with the quoting and any trailing dot removed.
267    fn identifier(&mut self, node: u32) -> StrRef {
268        let mut leaves = Vec::new();
269        self.leaves(node, &mut leaves);
270        let text = leaves.last().map_or("", |&leaf| self.text(leaf));
271        let text = self.fold_identifier(text.strip_suffix('.').unwrap_or(text));
272        self.intern(&text)
273    }
274
275    /// Every part of a qualified name, outermost first.
276    fn name_parts(&mut self, node: u32) -> Slice {
277        let mut leaves = Vec::new();
278        self.leaves(node, &mut leaves);
279        let mut parts = Vec::with_capacity(leaves.len());
280        for leaf in leaves {
281            let text = self.text(leaf);
282            // A node that covers no tokens is an optional part that was not written, and a bare
283            // `*` is the star and not a name part. Neither is a component of anything.
284            if text.is_empty() || text == "*" {
285                continue;
286            }
287            let text = self.fold_identifier(text.strip_suffix('.').unwrap_or(text));
288            let interned = self.intern(&text);
289            parts.push(interned);
290        }
291        self.part_slice(parts)
292    }
293
294    fn fold_identifier(&self, text: &str) -> String {
295        if text.starts_with(['"', '\'']) {
296            return unquote(text);
297        }
298        match self.identifier_case {
299            IdentifierCase::Preserve => text.to_string(),
300            IdentifierCase::Lower => text.to_ascii_lowercase(),
301            IdentifierCase::Upper => text.to_ascii_uppercase(),
302        }
303    }
304
305    // Statements.
306
307    /// `Program <- TopLevelStatement*`.
308    fn program(&mut self, node: u32) -> Result<()> {
309        for top in self.kids(node) {
310            // A script that ends in a semicolon produces a last `TopLevelStatement` whose only
311            // child is the end of input, because the grammar says `Statement? (';'+ / EndOfInput)`
312            // and both halves of that are happy to match nothing. It is a real node and it is not a
313            // statement, so it is dropped here rather than pretended away in the matcher.
314            let Some(statement) = self.kids(top).find(|&kid| self.name(kid) == "Statement") else {
315                continue;
316            };
317            let statement = self.statement(statement)?;
318            self.ast.statements.push(statement);
319        }
320        Ok(())
321    }
322
323    /// `Statement <- SelectStatement / ...`, twenty seven alternatives of which four are done.
324    fn statement(&mut self, node: u32) -> Result<Statement> {
325        let inner = self.first(node);
326        match self.name(inner) {
327            "SelectStatement" => {
328                let query = self.query(self.first(inner))?;
329                Ok(Statement::Query(query))
330            }
331            "CreateStatement" => self.create_statement(inner),
332            "DropStatement" => self.drop_statement(inner),
333            "InsertStatement" => self.insert_statement(inner),
334            "SetStatement" => self.set_statement(inner),
335            "ResetStatement" => self.reset_statement(inner),
336            "PragmaStatement" => self.pragma_statement(inner),
337            "ExplainStatement" => self.explain_statement(inner),
338            "CheckpointStatement" => Ok(Statement::Checkpoint),
339            _ => self.unsupported(inner),
340        }
341    }
342
343    /// `ExplainStatement <- 'EXPLAIN' AnalyzeKeyword? ExplainOptionList? ExplainableStatements`.
344    ///
345    /// Of the twenty one explainable statements, the one that is done is the query. The other
346    /// twenty either do not exist here yet or have nothing to show: a plan is what `EXPLAIN`
347    /// prints, and a `SET` has no plan. An `INSERT` has a plan for its source and showing that
348    /// would answer a question nobody asked, since the source is not what the statement does.
349    ///
350    /// The option list is a refusal. `EXPLAIN (FORMAT JSON)` asks for the plan in a shape nothing
351    /// here writes, and answering it with the text form would be answering a different question
352    /// quietly.
353    fn explain_statement(&mut self, node: u32) -> Result<Statement> {
354        let analyze = self.find(node, "AnalyzeKeyword") != NONE;
355        let options = self.find(node, "ExplainOptionList");
356        if options != NONE {
357            return self.unsupported(options);
358        }
359        let inner = self.first(self.find(node, "ExplainableStatements"));
360        if self.name(inner) != "ExplainSelectStatement" {
361            return self.unsupported(inner);
362        }
363        let query = self.query(self.find(inner, "SelectStatementInternal"))?;
364        Ok(Statement::Explain { query, analyze })
365    }
366
367    /// `SetStatement <- 'SET' SetAssignmentOrTimeZone`.
368    ///
369    /// Of the three assignments, `StandardAssignment` is the one that is done. `SET SCHEMA` and
370    /// `SET TIME ZONE` are each a setting this database has nothing to do with yet, and they are a
371    /// refusal rather than a silent success, because a statement that says where to look for a
372    /// table and is ignored is a statement that changes an answer.
373    fn set_statement(&mut self, node: u32) -> Result<Statement> {
374        let inner = self.first(self.find(node, "SetAssignmentOrTimeZone"));
375        if self.name(inner) == "SetTimeZone" {
376            return self.set_time_zone(inner);
377        }
378        if self.name(inner) != "StandardAssignment" {
379            return self.unsupported(inner);
380        }
381        let (name, scope) = self.setting_name(self.find(inner, "SetVariableOrSetting"))?;
382        let assignment = self.find(inner, "SetAssignment");
383        let list = self.find(assignment, "VariableList");
384        let kids: Vec<u32> = self.kids(list).collect();
385        if kids.len() == 1 && self.contains(list, "DefaultExpression") {
386            let index = self.ast.settings.len() as u32;
387            self.ast.settings.push(Setting { name, scope, value: NONE });
388            return Ok(Statement::Reset(index));
389        }
390        let mut values = Vec::new();
391        for kid in kids {
392            values.push(self.expr(kid)?);
393        }
394        // The grammar takes a list because `SET search_path = a, b` is a list in postgres. Nothing
395        // here has a setting that reads one, and taking the first of several would be worse than
396        // saying so.
397        let [value] = values[..] else {
398            return self.unsupported(list);
399        };
400        let index = self.ast.settings.len() as u32;
401        self.ast.settings.push(Setting { name, scope, value });
402        Ok(Statement::Set(index))
403    }
404
405    /// `SET TIME ZONE value`, normalized to the `TimeZone` setting DuckDB exposes beside it.
406    fn set_time_zone(&mut self, node: u32) -> Result<Statement> {
407        let zone = self.first(self.find(node, "ZoneValue"));
408        let name = self.intern("TimeZone");
409        if matches!(self.name(zone), "ZoneDefault" | "ZoneLocal") {
410            let index = self.ast.settings.len() as u32;
411            self.ast.settings.push(Setting { name, scope: Scope::Unwritten, value: NONE });
412            return Ok(Statement::Reset(index));
413        }
414        let text = match self.name(zone) {
415            "ZoneStringLiteral" => self.string_value(self.find(zone, "StringLiteral"))?,
416            "ZoneIdentifier" => {
417                let identifier = self.find(zone, "Identifier");
418                let identifier = self.identifier(identifier);
419                self.ast.string(identifier).to_string()
420            }
421            _ => return self.unsupported(zone),
422        };
423        let text = self.intern(&text);
424        let value = self.push(Expr::Literal { kind: LiteralKind::String, text });
425        let index = self.ast.settings.len() as u32;
426        self.ast.settings.push(Setting { name, scope: Scope::Unwritten, value });
427        Ok(Statement::Set(index))
428    }
429
430    /// `ResetStatement <- 'RESET' SetVariableOrSetting`.
431    fn reset_statement(&mut self, node: u32) -> Result<Statement> {
432        let (name, scope) = self.setting_name(self.find(node, "SetVariableOrSetting"))?;
433        let index = self.ast.settings.len() as u32;
434        self.ast.settings.push(Setting { name, scope, value: NONE });
435        Ok(Statement::Reset(index))
436    }
437
438    /// `PragmaStatement <- 'PRAGMA' PragmaAssignOrFunction`, which is two statements in one word.
439    ///
440    /// `PRAGMA memory_limit = '1GB'` is a `SET` with a different spelling and nothing else, so it
441    /// lands on the same [`Statement::Set`] and the same setting arena entry. The scope is
442    /// unwritten because the grammar has no room for one here, which is the same thing as a plain
443    /// `SET` with no scope word.
444    ///
445    /// `PRAGMA version` is a query. Upstream rewrites it to `SELECT * FROM pragma_version()` and
446    /// gives that away in its own error messages, which print the rewritten call back, so the
447    /// rewrite happens here rather than being a statement kind the planner has to know about. The
448    /// whole family comes out of it for free: an unknown pragma is the catalog's complaint, a bad
449    /// argument is the function's, and the answer is a relation like any other.
450    fn pragma_statement(&mut self, node: u32) -> Result<Statement> {
451        let inner = self.first(self.find(node, "PragmaAssignOrFunction"));
452        match self.name(inner) {
453            "PragmaAssign" => self.pragma_assign(inner),
454            "PragmaFunction" => self.pragma_function(inner),
455            _ => self.unsupported(inner),
456        }
457    }
458
459    /// `PragmaAssign <- SettingName '=' VariableList`, which is a `SET` and is treated as one.
460    fn pragma_assign(&mut self, node: u32) -> Result<Statement> {
461        let name = self.identifier(self.find(node, "SettingName"));
462        let list = self.find(node, "VariableList");
463        let mut values = Vec::new();
464        for kid in self.kids(list) {
465            values.push(self.expr(kid)?);
466        }
467        // The same refusal `set_statement` makes about a list, for the same reason. Nothing here
468        // reads one and taking the first of several would be worse than saying so.
469        let [value] = values[..] else {
470            return self.unsupported(list);
471        };
472        let index = self.ast.settings.len() as u32;
473        self.ast.settings.push(Setting { name, scope: Scope::Unwritten, value });
474        Ok(Statement::Set(index))
475    }
476
477    /// `PragmaFunction <- PragmaName PragmaParameters?`, rewritten into the call it stands for.
478    ///
479    /// The name is written without the prefix and the function carries it, so `PRAGMA table_info`
480    /// is `pragma_table_info`. The case the user wrote is kept rather than folded, because the name
481    /// goes back out in the message about a pragma that does not exist and upstream prints that
482    /// name back as it was typed.
483    ///
484    /// `PRAGMA version()` with empty parentheses is a parser error rather than a call, on both
485    /// engines, and that falls out of the grammar here without anything being done about it:
486    /// `PragmaParameters` is `Parens(List(Expression))` and a list of no expressions does not match.
487    fn pragma_function(&mut self, node: u32) -> Result<Statement> {
488        let interned = self.identifier(self.find(node, "PragmaName"));
489        let written = self.ast.string(interned).to_string();
490        let part = self.intern(&format!("pragma_{written}"));
491        let name = self.part_slice(vec![part]);
492        // The parameters are optional in the rule, so `PRAGMA version` has no node here at all
493        // rather than a node covering nothing.
494        let parameters = self.find(node, "PragmaParameters");
495        let mut args = Vec::new();
496        if parameters != NONE {
497            for kid in self.kids(parameters) {
498                let expr = self.expr(kid)?;
499                args.push(Target { expr: self.quoted(expr), alias: NONE });
500            }
501        }
502        let args = self.target_slice(args);
503        let source = self.push_source(Source::Function {
504            name,
505            args,
506            alias: NONE,
507            columns: Slice::default(),
508            pragma: true,
509        });
510        Ok(Statement::Query(self.star_over(source)))
511    }
512
513    /// A bare name in a pragma's parentheses is the name of a thing and not a column reference.
514    ///
515    /// `PRAGMA table_info(t)` and `PRAGMA table_info('t')` are the same statement on the pin, and
516    /// so are `PRAGMA table_info(s.u)` and `PRAGMA table_info('s.u')`, because there is no `FROM`
517    /// clause here for a column to come out of. Only a name is turned: `PRAGMA table_info(1)` stays
518    /// an integer and is told there is no overload that takes one, which is what the pin says too.
519    fn quoted(&mut self, expr: ExprRef) -> ExprRef {
520        let Expr::Column { name } = self.ast.exprs[expr as usize] else {
521            return expr;
522        };
523        let written: Vec<&str> = self.ast.name(name).collect();
524        let joined = written.join(".");
525        let text = self.intern(&joined);
526        self.push(Expr::Literal { kind: LiteralKind::String, text })
527    }
528
529    /// `SetVariableOrSetting <- SetVariable / SetSetting`, where the setting carries a scope word.
530    ///
531    /// `SET VARIABLE x = 1` is the other alternative and is a different feature: a variable is a
532    /// value the session holds and `getvariable` reads back, where a setting is a knob on the
533    /// engine. Refused rather than treated as a setting of that name.
534    fn setting_name(&mut self, node: u32) -> Result<(StrRef, Scope)> {
535        let inner = self.first(node);
536        if self.name(inner) != "SetSetting" {
537            return self.unsupported(inner);
538        }
539        let written = self.find(inner, "SettingScope");
540        let scope = if written == NONE {
541            Scope::Unwritten
542        } else {
543            match self.name(self.first(written)) {
544                "GlobalScope" => Scope::Global,
545                "SessionScope" => Scope::Session,
546                "LocalScope" => Scope::Local,
547                _ => return self.unsupported(written),
548            }
549        };
550        Ok((self.identifier(self.find(inner, "SettingName")), scope))
551    }
552
553    /// `CreateStatement <- 'CREATE' OrReplace? Temporary? CreateStatementVariation`.
554    ///
555    /// Of the nine variations, `CreateTableStmt` and `CreateViewStmt` are the ones that are done.
556    /// The other seven are a macro, a sequence, a type, a schema, an index, a secret and a trigger,
557    /// and each of them is a catalog entry this database has no room for yet.
558    fn create_statement(&mut self, node: u32) -> Result<Statement> {
559        let or_replace = self.find(node, "OrReplace") != NONE;
560        let temporary = self.find(node, "Temporary") != NONE;
561        let variation = self.find(node, "CreateStatementVariation");
562        let inner = self.first(variation);
563        // duckdb refuses this pair in the parser, with a caret under the `NOT`, because none of its
564        // create rules has room for both. The vendored grammar has room for both, so the refusal is
565        // here instead, which is the same stage and therefore the same sentence.
566        if or_replace && self.find(inner, "IfNotExists") != NONE {
567            return Err(Error::parser(
568                "Cannot specify both OR REPLACE and IF NOT EXISTS within single create statement",
569            ));
570        }
571        match self.name(inner) {
572            "CreateTableStmt" => self.create_table_statement(inner, or_replace, temporary),
573            "CreateViewStmt" => self.create_view_statement(inner, or_replace, temporary),
574            _ => self.unsupported(inner),
575        }
576    }
577
578    /// `CreateTableStmt <- 'TABLE' IfNotExists? QualifiedName CreateTableDefinition`.
579    fn create_table_statement(
580        &mut self,
581        inner: u32,
582        or_replace: bool,
583        temporary: bool,
584    ) -> Result<Statement> {
585        let name = self.name_parts(self.find(inner, "QualifiedName"));
586        let if_not_exists = self.find(inner, "IfNotExists") != NONE;
587        let definition = self.find(inner, "CreateTableDefinition");
588        let body = self.first(definition);
589        let (columns, query) = match self.name(body) {
590            "CreateColumnList" => (self.column_list(body)?, NONE),
591            "CreateTableAs" => self.create_table_as(body)?,
592            _ => return self.unsupported(body),
593        };
594        let index = self.ast.create_tables.len() as u32;
595        self.ast.create_tables.push(CreateTable {
596            name,
597            columns,
598            query,
599            if_not_exists,
600            or_replace,
601            temporary,
602        });
603        Ok(Statement::CreateTable(index))
604    }
605
606    /// `CreateViewStmt <- CreateSecure? CreateRecursive? 'VIEW' IfNotExists? QualifiedName
607    /// InsertColumnList? WithList? 'AS' SelectStatementInternal`.
608    ///
609    /// The body is transformed here as well as kept as text. Transforming it is what makes a view
610    /// whose body does not parse a parse error at creation, which is where it belongs, and the text
611    /// is what the catalog keeps so that the body can be bound again at every reference.
612    fn create_view_statement(
613        &mut self,
614        inner: u32,
615        or_replace: bool,
616        temporary: bool,
617    ) -> Result<Statement> {
618        for kid in self.kids(inner) {
619            // `SECURE` is a column and row policy, `RECURSIVE` is a different shape of view
620            // entirely, and `WITH` carries options. Dropping any of the three silently would make a
621            // view that is not the view that was asked for.
622            if matches!(self.name(kid), "CreateSecure" | "CreateRecursive" | "WithList") {
623                return self.unsupported(kid);
624            }
625        }
626        let name = self.name_parts(self.find(inner, "QualifiedName"));
627        let if_not_exists = self.find(inner, "IfNotExists") != NONE;
628        let list = self.find(inner, "InsertColumnList");
629        let columns = if list == NONE {
630            Slice::default()
631        } else {
632            let mut parts = Vec::new();
633            for kid in self.kids(self.find(list, "ColumnList")) {
634                parts.push(self.identifier(kid));
635            }
636            self.part_slice(parts)
637        };
638        let body = self.find(inner, "SelectStatementInternal");
639        let sql = self.text(body).to_string();
640        let sql = self.intern(&sql);
641        let query = self.query(body)?;
642        let index = self.ast.create_views.len() as u32;
643        self.ast.create_views.push(CreateView {
644            name,
645            columns,
646            query,
647            sql,
648            if_not_exists,
649            or_replace,
650            temporary,
651        });
652        Ok(Statement::CreateView(index))
653    }
654
655    /// `CreateColumnList <- Parens(CreateTableColumnList?) PartitionSortedOptions? WithList?`.
656    fn column_list(&mut self, node: u32) -> Result<Slice> {
657        for kid in self.kids(node) {
658            if matches!(self.name(kid), "PartitionOptions" | "SortedOptions" | "WithList") {
659                return self.unsupported(kid);
660            }
661        }
662        let list = self.find(node, "CreateTableColumnList");
663        if list == NONE {
664            // `CREATE TABLE t ()` parses. It is a table of no columns, and the catalog is entitled
665            // to refuse it, but that is not this layer's refusal to make.
666            return Ok(Slice::default());
667        }
668        let mut defs = Vec::new();
669        for element in self.kids(list) {
670            let inner = self.first(element);
671            if self.name(inner) != "CreateTableColumnDefinition" {
672                // A table level `PRIMARY KEY`, `UNIQUE`, `CHECK` or `FOREIGN KEY`. Constraints are
673                // not enforced anywhere yet and silently dropping one is a wrong answer waiting to
674                // happen, so it is refused instead.
675                return self.unsupported(inner);
676            }
677            defs.push(self.column_definition(self.first(inner))?);
678        }
679        Ok(self.column_def_slice(defs))
680    }
681
682    /// `ColumnDefinition <- DottedIdentifier Type? GeneratedColumn? ConstraintNameClause?
683    /// ColumnConstraint*`.
684    fn column_definition(&mut self, node: u32) -> Result<ColumnDef> {
685        let name = self.identifier(self.find(node, "DottedIdentifier"));
686        let type_node = self.find(node, "Type");
687        let ty = if type_node == NONE {
688            NONE
689        } else {
690            let text = self.text(type_node).to_string();
691            self.intern(&text)
692        };
693        if self.find(node, "GeneratedColumn") != NONE {
694            return self.unsupported(self.find(node, "GeneratedColumn"));
695        }
696        let mut not_null = false;
697        for kid in self.kids(node) {
698            if self.name(kid) != "ColumnConstraint" {
699                continue;
700            }
701            let constraint = self.first(kid);
702            match self.name(constraint) {
703                "NotNullConstraint" => {
704                    not_null = self.name(self.first(constraint)) == "NotNullColumnConstraint";
705                }
706                _ => return self.unsupported(constraint),
707            }
708        }
709        Ok(ColumnDef { name, ty, not_null })
710    }
711
712    /// `CreateTableAs <- IdentifierList? PartitionSortedOptions? WithList? 'AS' Statement
713    /// WithData?`.
714    ///
715    /// The names in the `IdentifierList` become column definitions with no type, because the types
716    /// are the query's and only the names are the syntax's to say.
717    fn create_table_as(&mut self, node: u32) -> Result<(Slice, QueryRef)> {
718        for kid in self.kids(node) {
719            if matches!(
720                self.name(kid),
721                "PartitionOptions" | "SortedOptions" | "WithList" | "WithData"
722            ) {
723                return self.unsupported(kid);
724            }
725        }
726        let names = self.find(node, "IdentifierList");
727        let columns = if names == NONE {
728            Slice::default()
729        } else {
730            let mut defs = Vec::new();
731            for kid in self.kids(names) {
732                let name = self.identifier(kid);
733                defs.push(ColumnDef { name, ty: NONE, not_null: false });
734            }
735            self.column_def_slice(defs)
736        };
737        let statement = self.find(node, "Statement");
738        let inner = self.first(statement);
739        if self.name(inner) != "SelectStatement" {
740            return self.unsupported(inner);
741        }
742        let query = self.query(self.first(inner))?;
743        Ok((columns, query))
744    }
745
746    /// `DropStatement <- 'DROP' DropEntries DropBehavior?`.
747    ///
748    /// `DropTable <- TableOrView IfExists? List(BaseTableName)`, and `TableOrView` covers `VIEW`
749    /// and `MATERIALIZED VIEW` as well as `TABLE`, so it is checked rather than assumed. The first
750    /// two are done and a materialized view is not a thing this database has.
751    fn drop_statement(&mut self, node: u32) -> Result<Statement> {
752        if self.find(node, "DropBehavior") != NONE {
753            return self.unsupported(self.find(node, "DropBehavior"));
754        }
755        let entries = self.find(node, "DropEntries");
756        let inner = self.first(entries);
757        if self.name(inner) != "DropTable" {
758            return self.unsupported(inner);
759        }
760        let kind = self.find(inner, "TableOrView");
761        let view = match self.name(self.first(kind)) {
762            "CommentTable" => false,
763            "CommentView" => true,
764            _ => return self.unsupported(kind),
765        };
766        let if_exists = self.find(inner, "IfExists") != NONE;
767        let mut names = Vec::new();
768        for kid in self.kids(inner) {
769            if self.name(kid) == "BaseTableName" {
770                names.push(self.name_parts(kid));
771            }
772        }
773        let names = self.name_list_slice(names);
774        let index = self.ast.drop_tables.len() as u32;
775        self.ast.drop_tables.push(DropTable { names, if_exists, view });
776        Ok(Statement::DropTable(index))
777    }
778
779    /// `InsertStatement <- ... InsertTarget InsertColumnList? InsertValues ...`.
780    ///
781    /// `ON CONFLICT`, `RETURNING`, `BY NAME`, `BY POSITION`, `OR REPLACE` and the rest of the
782    /// clauses the grammar hangs off this are each a refusal, because every one of them changes
783    /// what the statement means and none of them changes it in a way anything downstream would
784    /// notice if it were dropped.
785    fn insert_statement(&mut self, node: u32) -> Result<Statement> {
786        for kid in self.kids(node) {
787            if matches!(
788                self.name(kid),
789                "InsertTarget" | "InsertColumnList" | "InsertValues" | "WithClause"
790            ) {
791                continue;
792            }
793            return self.unsupported(kid);
794        }
795        if self.find(node, "WithClause") != NONE {
796            return self.unsupported(self.find(node, "WithClause"));
797        }
798        let name = self.name_parts(self.find(self.find(node, "InsertTarget"), "BaseTableName"));
799        let list = self.find(node, "InsertColumnList");
800        let columns = if list == NONE {
801            Slice::default()
802        } else {
803            let mut parts = Vec::new();
804            for kid in self.kids(self.find(list, "ColumnList")) {
805                parts.push(self.identifier(kid));
806            }
807            self.part_slice(parts)
808        };
809        let values = self.find(node, "InsertValues");
810        let inner = self.first(values);
811        if self.name(inner) != "SelectInsertValues" {
812            return self.unsupported(inner);
813        }
814        let source = self.query(self.find(inner, "SelectStatementInternal"))?;
815        let index = self.ast.inserts.len() as u32;
816        self.ast.inserts.push(Insert { name, columns, source });
817        Ok(Statement::Insert(index))
818    }
819
820    /// `SelectStatementInternal <- WithClause? SelectSetOpChain ResultModifiers?`.
821    fn query(&mut self, node: u32) -> Result<QueryRef> {
822        if self.find(node, "WithClause") != NONE {
823            return self.unsupported(self.find(node, "WithClause"));
824        }
825        let chain = self.find(node, "SelectSetOpChain");
826        if chain == NONE {
827            return self.unsupported(node);
828        }
829        let query = self.set_op_chain(chain)?;
830        let modifiers = self.find(node, "ResultModifiers");
831        if modifiers != NONE {
832            self.result_modifiers(query, modifiers)?;
833        }
834        Ok(query)
835    }
836
837    /// `SelectSetOpChain <- IntersectChain SelectSetOpChainTail*`, left associative.
838    fn set_op_chain(&mut self, node: u32) -> Result<QueryRef> {
839        let mut kids = self.kids(node);
840        let head = kids.next().unwrap_or(NONE);
841        let mut left = self.intersect_chain(head)?;
842        for tail in kids {
843            // `SelectSetOpChainTail <- SetopClause IntersectChain`.
844            let clause = self.first(tail);
845            let (op, quantifier, by_name) = self.setop_clause(clause)?;
846            let right = self.intersect_chain(self.nth(tail, 1))?;
847            left = self.push_query(Query::bare(QueryBody::SetOp {
848                op,
849                quantifier,
850                by_name,
851                left,
852                right,
853            }));
854        }
855        Ok(left)
856    }
857
858    /// `IntersectChain <- SelectAtom IntersectChainTail*`, which binds tighter than union.
859    fn intersect_chain(&mut self, node: u32) -> Result<QueryRef> {
860        let mut kids = self.kids(node);
861        let head = kids.next().unwrap_or(NONE);
862        let mut left = self.select_atom(head)?;
863        for tail in kids {
864            // `IntersectChainTail <- SetIntersectClause SelectAtom`.
865            let clause = self.first(tail);
866            let quantifier = self.quantifier(self.find(clause, "DistinctOrAll"));
867            let right = self.select_atom(self.nth(tail, 1))?;
868            left = self.push_query(Query::bare(QueryBody::SetOp {
869                op: SetOp::Intersect,
870                quantifier,
871                by_name: false,
872                left,
873                right,
874            }));
875        }
876        Ok(left)
877    }
878
879    /// `SetopClause <- SetopType DistinctOrAll? ByName?`.
880    fn setop_clause(&mut self, node: u32) -> Result<(SetOp, Quantifier, bool)> {
881        let kind = self.find(node, "SetopType");
882        let op = match self.name(self.first(kind)) {
883            "SetopUnion" => SetOp::Union,
884            "SetopExcept" => SetOp::Except,
885            _ => return self.unsupported(kind),
886        };
887        let quantifier = self.quantifier(self.find(node, "DistinctOrAll"));
888        Ok((op, quantifier, self.find(node, "ByName") != NONE))
889    }
890
891    /// `DistinctOrAll <- DistinctKeyword / AllKeyword`, absent included.
892    fn quantifier(&self, node: u32) -> Quantifier {
893        if node == NONE {
894            return Quantifier::Unstated;
895        }
896        match self.name(self.first(node)) {
897            "DistinctKeyword" => Quantifier::Distinct,
898            "AllKeyword" => Quantifier::All,
899            _ => Quantifier::Unstated,
900        }
901    }
902
903    /// `SelectAtom <- SelectParens / SelectStatementType`.
904    fn select_atom(&mut self, node: u32) -> Result<QueryRef> {
905        let inner = self.first(node);
906        match self.name(inner) {
907            // `SelectParens <- Parens(SelectStatementInternal)`, so the parens buy a query that
908            // carries its own order by and limit and nothing else.
909            "SelectParens" => self.query(self.first(inner)),
910            "SelectStatementType" => {
911                let kind = self.first(inner);
912                match self.name(kind) {
913                    "OptionalParensSimpleSelect" => {
914                        let select = self.simple_select(self.unwrap_parens(kind))?;
915                        Ok(self.push_query(Query::bare(QueryBody::Select(select))))
916                    }
917                    "ValuesClause" => {
918                        let rows = self.values_clause(kind)?;
919                        Ok(self.push_query(Query::bare(QueryBody::Values(rows))))
920                    }
921                    "DescribeStatement" => self.describe_statement(kind),
922                    _ => self.unsupported(kind),
923                }
924            }
925            _ => self.unsupported(inner),
926        }
927    }
928
929    /// `DescribeStatement <- ShowTables / ShowDeprecatedSelect / DescribeSelect / ShowAllTables /
930    /// ShowByName / DescribeByName`.
931    ///
932    /// Two of the six are done and they are the two that describe a relation. The four that are
933    /// not are `SHOW`, which is a different statement wearing this rule: three of its four forms
934    /// list what the database has rather than what a query returns, and the fourth is `SHOW <query>`,
935    /// which upstream documents as deprecated. Describing something through a deprecated spelling
936    /// is not worth implementing before the spelling that replaced it has users.
937    ///
938    /// `SUMMARIZE` shares `DescribeByName` and `DescribeSelect` with `DESCRIBE` and is refused
939    /// here, because it returns twelve columns of statistics rather than six of schema and reading
940    /// it as a describe would answer a different question than the one that was asked.
941    fn describe_statement(&mut self, node: u32) -> Result<QueryRef> {
942        let inner = self.first(node);
943        match self.name(inner) {
944            "DescribeSelect" => {
945                self.describe_and_not_summarize(inner)?;
946                let query = self.query(self.find(inner, "SelectStatementInternal"))?;
947                Ok(self.push_query(Query::bare(QueryBody::Describe(query))))
948            }
949            "DescribeByName" => {
950                self.describe_and_not_summarize(inner)?;
951                let target = self.find(inner, "DescribeTarget");
952                if target == NONE {
953                    return self.unsupported(inner);
954                }
955                let source = self.describe_target(target)?;
956                let query = self.star_over(source);
957                Ok(self.push_query(Query::bare(QueryBody::Describe(query))))
958            }
959            "ShowByName" => {
960                let target = self.find(inner, "ShowTarget");
961                if target == NONE {
962                    return self.unsupported(inner);
963                }
964                let name = self.name_parts(target);
965                let source = self.push_source(Source::Table {
966                    name,
967                    alias: NONE,
968                    columns: Slice::default(),
969                });
970                let relation = self.star_over(source);
971                Ok(self.push_query(Query::bare(QueryBody::Show { name, relation })))
972            }
973            _ => self.unsupported(inner),
974        }
975    }
976
977    /// `DescribeOrSummarize <- DescribeRule / Summarize`, where only the first is done.
978    fn describe_and_not_summarize(&mut self, node: u32) -> Result<()> {
979        let word = self.find(node, "DescribeOrSummarize");
980        if word == NONE || self.name(self.first(word)) != "DescribeRule" {
981            return self.unsupported(if word == NONE { node } else { word });
982        }
983        Ok(())
984    }
985
986    /// `DescribeTarget <- DescribeBaseTableName / DescribeStringLiteral`, as a source to read from.
987    ///
988    /// Both become a `FROM` item and not a lookup of their own, because the string form is the
989    /// replacement scan and the binder already knows how to turn `'hits.parquet'` into a reader.
990    /// A name that is a table, a view, a file or nothing at all then gets one answer from one place.
991    fn describe_target(&mut self, node: u32) -> Result<SourceRef> {
992        let inner = self.first(node);
993        let name = match self.name(inner) {
994            "DescribeBaseTableName" => self.name_parts(self.find(inner, "BaseTableName")),
995            "DescribeStringLiteral" => {
996                let text = self.string_value(self.find(inner, "StringLiteral"))?;
997                let part = self.intern(&text);
998                self.part_slice(vec![part])
999            }
1000            _ => return self.unsupported(inner),
1001        };
1002        Ok(self.push_source(Source::Table { name, alias: NONE, columns: Slice::default() }))
1003    }
1004
1005    /// `SELECT * FROM <source>`, which is what `DESCRIBE t` means.
1006    fn star_over(&mut self, source: SourceRef) -> QueryRef {
1007        let star =
1008            self.push(Expr::Star { qualifier: Slice::default(), replacements: Slice::default() });
1009        let targets = self.target_slice(vec![Target { expr: star, alias: NONE }]);
1010        let start = self.ast.source_lists.len() as u32;
1011        self.ast.source_lists.push(source);
1012        let from = Slice { start, len: 1 };
1013        let select = self.push_select(Select { targets, from, ..Select::empty() });
1014        self.push_query(Query::bare(QueryBody::Select(select)))
1015    }
1016
1017    /// `ValuesClause <- 'VALUES' List(ValuesExpressions)`, each of which is `Parens(List(Expression))`.
1018    ///
1019    /// The rows are not checked against each other for width here. Two rows of different widths
1020    /// parse, and saying so is the binder's job, because the message wants to name the column count
1021    /// it expected and the parser does not know it for `INSERT` where the table decides.
1022    fn values_clause(&mut self, node: u32) -> Result<Slice> {
1023        let mut rows = Vec::new();
1024        for kid in self.kids(node) {
1025            if self.name(kid) != "ValuesExpressions" {
1026                continue;
1027            }
1028            let mut items = Vec::new();
1029            for expr in self.kids(kid) {
1030                items.push(self.expr(expr)?);
1031            }
1032            let slice = self.expr_slice(items);
1033            rows.push(slice);
1034        }
1035        let start = self.ast.rows.len() as u32;
1036        self.ast.rows.extend(rows);
1037        Ok(Slice { start, len: self.ast.rows.len() as u32 - start })
1038    }
1039
1040    /// `OptionalParensSimpleSelect <- SimpleSelectParens / SimpleSelect`, down to the select.
1041    fn unwrap_parens(&self, node: u32) -> u32 {
1042        let mut node = self.first(node);
1043        while self.name(node) == "SimpleSelectParens" {
1044            node = self.first(node);
1045        }
1046        node
1047    }
1048
1049    /// `ResultModifiers <- OrderByClause? LimitOffset?`.
1050    fn result_modifiers(&mut self, query: QueryRef, node: u32) -> Result<()> {
1051        let order = self.find(node, "OrderByClause");
1052        if order != NONE {
1053            let (items, all) = self.order_by(order)?;
1054            let start = self.ast.order_items.len() as u32;
1055            self.ast.order_items.extend(items);
1056            self.ast.queries[query as usize].order_by =
1057                Slice { start, len: self.ast.order_items.len() as u32 - start };
1058            self.ast.queries[query as usize].order_by_all = all;
1059        }
1060        let limit = self.find(node, "LimitOffset");
1061        if limit != NONE {
1062            self.limit_offset(query, self.first(limit))?;
1063        }
1064        Ok(())
1065    }
1066
1067    /// The four spellings of a limit and an offset, in either order and either one alone.
1068    fn limit_offset(&mut self, query: QueryRef, node: u32) -> Result<()> {
1069        match self.name(node) {
1070            "LimitOffsetClause" | "OffsetLimitClause" => {
1071                let limit = self.find(node, "LimitClause");
1072                if limit != NONE {
1073                    self.limit(query, limit)?;
1074                }
1075                let offset = self.find(node, "OffsetClause");
1076                if offset != NONE {
1077                    self.offset(query, offset)?;
1078                }
1079                Ok(())
1080            }
1081            _ => self.unsupported(node),
1082        }
1083    }
1084
1085    /// `LimitClause <- 'LIMIT' LimitValue`.
1086    fn limit(&mut self, query: QueryRef, node: u32) -> Result<()> {
1087        let value = self.first(node);
1088        let inner = self.first(value);
1089        match self.name(inner) {
1090            // `LIMIT ALL` is no limit at all, which is what an absent limit already means.
1091            "LimitAll" => Ok(()),
1092            // `LimitExpression <- Expression '%'?`. The percent sign is a terminal so it leaves no
1093            // node behind, and the only thing that says it was written is the text of the rule that
1094            // matched it.
1095            "LimitExpression" => {
1096                let expr = self.expr(self.first(inner))?;
1097                self.ast.queries[query as usize].limit = expr;
1098                self.ast.queries[query as usize].limit_percent = self.text(inner).ends_with('%');
1099                Ok(())
1100            }
1101            "LimitLiteralPercent" => {
1102                let expr = self.expr(self.first(inner))?;
1103                self.ast.queries[query as usize].limit = expr;
1104                self.ast.queries[query as usize].limit_percent = true;
1105                Ok(())
1106            }
1107            _ => self.unsupported(inner),
1108        }
1109    }
1110
1111    /// `OffsetClause <- 'OFFSET' OffsetValue`, where `OffsetValue <- Expression RowOrRows?`.
1112    fn offset(&mut self, query: QueryRef, node: u32) -> Result<()> {
1113        let value = self.first(node);
1114        let expr = self.expr(self.first(value))?;
1115        self.ast.queries[query as usize].offset = expr;
1116        Ok(())
1117    }
1118
1119    /// `SimpleSelect <- SelectFrom WhereClause? GroupByClause? HavingClause? WindowClause?
1120    /// QualifyClause? SampleClause?`.
1121    fn simple_select(&mut self, node: u32) -> Result<SelectRef> {
1122        for name in ["WindowClause", "QualifyClause", "SampleClause"] {
1123            let clause = self.find(node, name);
1124            if clause != NONE {
1125                return self.unsupported(clause);
1126            }
1127        }
1128        let mut select = Select::empty();
1129        self.select_from(&mut select, self.first(node))?;
1130        let filter = self.find(node, "WhereClause");
1131        if filter != NONE {
1132            select.filter = self.expr(self.first(filter))?;
1133        }
1134        let group = self.find(node, "GroupByClause");
1135        if group != NONE {
1136            self.group_by(&mut select, self.first(group))?;
1137        }
1138        let having = self.find(node, "HavingClause");
1139        if having != NONE {
1140            select.having = self.expr(self.first(having))?;
1141        }
1142        Ok(self.push_select(select))
1143    }
1144
1145    /// `SelectFrom <- SelectFromClause / FromSelectClause`, which is `SELECT ... FROM ...` and
1146    /// DuckDB's `FROM ... SELECT ...` written the other way round.
1147    fn select_from(&mut self, select: &mut Select, node: u32) -> Result<()> {
1148        let clause = self.first(node);
1149        let targets = self.find(clause, "SelectClause");
1150        let from = self.find(clause, "FromClause");
1151        if from != NONE {
1152            select.from = self.sources(from)?;
1153        }
1154        if targets == NONE {
1155            // `FROM t` on its own. DuckDB reads it as `SELECT * FROM t`, and inventing the star
1156            // here rather than in the binder keeps the binder from having to know the shape of the
1157            // clause that was missing.
1158            let star = self
1159                .push(Expr::Star { qualifier: Slice::default(), replacements: Slice::default() });
1160            let start = self.ast.targets.len() as u32;
1161            self.ast.targets.push(Target { expr: star, alias: NONE });
1162            select.targets = Slice { start, len: 1 };
1163            return Ok(());
1164        }
1165        self.select_clause(select, targets)
1166    }
1167
1168    /// `SelectClause <- 'SELECT' DistinctClause? TargetList?`.
1169    fn select_clause(&mut self, select: &mut Select, node: u32) -> Result<()> {
1170        let distinct = self.find(node, "DistinctClause");
1171        if distinct != NONE {
1172            let inner = self.first(distinct);
1173            select.distinct = match self.name(inner) {
1174                // `SELECT ALL` is the default spelled out.
1175                "DistinctAll" => Distinct::No,
1176                "DistinctOn" => {
1177                    let on = self.find(inner, "DistinctOnTargets");
1178                    if on == NONE {
1179                        Distinct::Yes
1180                    } else {
1181                        let mut items = Vec::new();
1182                        for kid in self.kids(on) {
1183                            items.push(self.expr(kid)?);
1184                        }
1185                        Distinct::On(self.expr_slice(items))
1186                    }
1187                }
1188                _ => return self.unsupported(inner),
1189            };
1190        }
1191        let list = self.find(node, "TargetList");
1192        if list == NONE {
1193            return Ok(());
1194        }
1195        let mut targets = Vec::new();
1196        for kid in self.kids(list) {
1197            targets.push(self.target(kid)?);
1198        }
1199        select.targets = self.target_slice(targets);
1200        Ok(())
1201    }
1202
1203    /// `AliasedExpression <- ColIdExpression / ExpressionAsCollabel / ExpressionOptIdentifier`.
1204    fn target(&mut self, node: u32) -> Result<Target> {
1205        let inner = self.first(node);
1206        match self.name(inner) {
1207            // `ColIdExpression <- ColId ':' Expression`, the alias written first.
1208            "ColIdExpression" => {
1209                let alias = self.identifier(self.first(inner));
1210                let expr = self.expr(self.nth(inner, 1))?;
1211                Ok(Target { expr, alias })
1212            }
1213            "ExpressionAsCollabel" => {
1214                let expr = self.expr(self.first(inner))?;
1215                let alias = self.identifier(self.nth(inner, 1));
1216                Ok(Target { expr, alias })
1217            }
1218            "ExpressionOptIdentifier" => {
1219                let expr = self.expr(self.first(inner))?;
1220                let alias =
1221                    if self.count(inner) > 1 { self.identifier(self.nth(inner, 1)) } else { NONE };
1222                Ok(Target { expr, alias })
1223            }
1224            _ => self.unsupported(inner),
1225        }
1226    }
1227
1228    /// `GroupByClause <- 'GROUP' 'BY' GroupByExpressions`.
1229    fn group_by(&mut self, select: &mut Select, node: u32) -> Result<()> {
1230        let inner = self.first(node);
1231        match self.name(inner) {
1232            "GroupByAll" => {
1233                select.group_by_all = true;
1234                Ok(())
1235            }
1236            "GroupByList" => {
1237                let mut items = Vec::new();
1238                for kid in self.kids(inner) {
1239                    // `GroupByExpression <- EmptyGroupingItem / CubeOrRollupClause /
1240                    // GroupingSetsClause / GroupByBaseExpression`.
1241                    let expression = self.first(kid);
1242                    if self.name(expression) != "GroupByBaseExpression" {
1243                        return self.unsupported(expression);
1244                    }
1245                    items.push(self.expr(self.first(expression))?);
1246                }
1247                select.group_by = self.expr_slice(items);
1248                Ok(())
1249            }
1250            _ => self.unsupported(inner),
1251        }
1252    }
1253
1254    /// `OrderByClause <- 'ORDER' 'BY' OrderByExpressions`, where `OrderByExpressions <- OrderByAll
1255    /// / OrderByExpressionList`.
1256    fn order_by(&mut self, node: u32) -> Result<(Vec<OrderItem>, bool)> {
1257        let inner = self.first(self.first(node));
1258        match self.name(inner) {
1259            "OrderByAll" => {
1260                let (order, nulls) = self.sort_options(inner);
1261                Ok((vec![OrderItem { expr: NONE, order, nulls }], true))
1262            }
1263            "OrderByExpressionList" => {
1264                let mut items = Vec::new();
1265                for kid in self.kids(inner) {
1266                    // `OrderByExpression <- Expression DescOrAsc? NullsFirstOrLast?`.
1267                    let expr = self.expr(self.first(kid))?;
1268                    let (order, nulls) = self.sort_options(kid);
1269                    items.push(OrderItem { expr, order, nulls });
1270                }
1271                Ok((items, false))
1272            }
1273            _ => self.unsupported(inner),
1274        }
1275    }
1276
1277    /// The direction and the null placement of one sort key, either of which may be unwritten.
1278    fn sort_options(&self, node: u32) -> (Order, Nulls) {
1279        let direction = self.find(node, "DescOrAsc");
1280        let order = if direction == NONE {
1281            Order::Unstated
1282        } else if self.name(self.first(direction)) == "DescendingOrder" {
1283            Order::Descending
1284        } else {
1285            Order::Ascending
1286        };
1287        let placement = self.find(node, "NullsFirstOrLast");
1288        let nulls = if placement == NONE {
1289            Nulls::Unstated
1290        } else if self.name(self.first(placement)) == "NullsFirst" {
1291            Nulls::First
1292        } else {
1293            Nulls::Last
1294        };
1295        (order, nulls)
1296    }
1297
1298    // From clauses.
1299
1300    /// `FromClause <- 'FROM' List(TableRef)`.
1301    fn sources(&mut self, node: u32) -> Result<Slice> {
1302        let mut items = Vec::new();
1303        for kid in self.kids(node) {
1304            items.push(self.table_ref(kid)?);
1305        }
1306        let start = self.ast.source_lists.len() as u32;
1307        self.ast.source_lists.extend(items);
1308        Ok(Slice { start, len: self.ast.source_lists.len() as u32 - start })
1309    }
1310
1311    /// `TableRef <- InnerTableRef JoinOrPivot*`, left associative like the set operators.
1312    fn table_ref(&mut self, node: u32) -> Result<SourceRef> {
1313        let mut kids = self.kids(node);
1314        let head = kids.next().unwrap_or(NONE);
1315        let mut left = self.inner_table_ref(head)?;
1316        for tail in kids {
1317            let clause = self.first(tail);
1318            if self.name(clause) != "JoinClause" {
1319                return self.unsupported(clause);
1320            }
1321            left = self.join(left, self.first(clause))?;
1322        }
1323        Ok(left)
1324    }
1325
1326    /// `InnerTableRef <- ValuesRef / TableFunction / TableSubquery / BaseTableRef / ParensTableRef`.
1327    fn inner_table_ref(&mut self, node: u32) -> Result<SourceRef> {
1328        let inner = if self.name(node) == "InnerTableRef" { self.first(node) } else { node };
1329        match self.name(inner) {
1330            "BaseTableRef" => {
1331                if self.find(inner, "TableAliasColon") != NONE {
1332                    return self.unsupported(inner);
1333                }
1334                for name in ["AtClause", "SampleClause"] {
1335                    let clause = self.find(inner, name);
1336                    if clause != NONE {
1337                        return self.unsupported(clause);
1338                    }
1339                }
1340                let name = self.name_parts(self.find(inner, "BaseTableName"));
1341                let (alias, columns) = self.table_alias(self.find(inner, "TableAlias"));
1342                Ok(self.push_source(Source::Table { name, alias, columns }))
1343            }
1344            "TableSubquery" => {
1345                if self.find(inner, "TableAliasColon") != NONE
1346                    || self.find(inner, "Lateral") != NONE
1347                {
1348                    return self.unsupported(inner);
1349                }
1350                // `SubqueryReference <- Parens(SelectStatementInternal)`.
1351                let reference = self.find(inner, "SubqueryReference");
1352                let query = self.query(self.first(reference))?;
1353                let (alias, columns) = self.table_alias(self.find(inner, "TableAlias"));
1354                Ok(self.push_source(Source::Subquery { query, alias, columns }))
1355            }
1356            // `TableFunction <- TableFunctionLateralOpt / TableFunctionAliasColon`, and
1357            // `TableFunctionLateralOpt <- Lateral? QualifiedTableFunction TableFunctionArguments
1358            // WithOrdinality? TableAlias?`. The colon form and `LATERAL` are their own work, and
1359            // `WITH ORDINALITY` adds a column, so all three are turned away rather than dropped.
1360            "TableFunction" => {
1361                let form = self.first(inner);
1362                for name in ["TableAliasColon", "Lateral", "WithOrdinality", "SampleClause"] {
1363                    let clause = self.find(form, name);
1364                    if clause != NONE {
1365                        return self.unsupported(clause);
1366                    }
1367                }
1368                let name = self.name_parts(self.find(form, "QualifiedTableFunction"));
1369                let mut args = Vec::new();
1370                // `TableFunctionArguments <- Parens(List(FunctionArgument)?)`, so a call with no
1371                // arguments has the wrapper and no list under it.
1372                let list = self.find(form, "TableFunctionArguments");
1373                for kid in self.kids(list) {
1374                    args.push(self.table_argument(kid)?);
1375                }
1376                let args = self.target_slice(args);
1377                let (alias, columns) = self.table_alias(self.find(form, "TableAlias"));
1378                Ok(self.push_source(Source::Function { name, args, alias, columns, pragma: false }))
1379            }
1380            "ValuesRef" => {
1381                if self.find(inner, "TableAliasColon") != NONE {
1382                    return self.unsupported(inner);
1383                }
1384                let rows = self.values_clause(self.find(inner, "ValuesClause"))?;
1385                let (alias, columns) = self.table_alias(self.find(inner, "TableAlias"));
1386                Ok(self.push_source(Source::Values { rows, alias, columns }))
1387            }
1388            "ParensTableRef" => {
1389                if self.find(inner, "TableAliasColon") != NONE
1390                    || self.find(inner, "SampleClause") != NONE
1391                    || self.find(inner, "TableAlias") != NONE
1392                {
1393                    return self.unsupported(inner);
1394                }
1395                self.table_ref(self.find(inner, "TableRef"))
1396            }
1397            _ => self.unsupported(inner),
1398        }
1399    }
1400
1401    /// `TableAlias <- TableAliasAs / TableAliasWithoutAs`, either with a column alias list.
1402    fn table_alias(&mut self, node: u32) -> (StrRef, Slice) {
1403        if node == NONE {
1404            return (NONE, Slice::default());
1405        }
1406        let inner = self.first(node);
1407        let alias = self.identifier(self.first(inner));
1408        let list = self.find(inner, "ColumnAliases");
1409        if list == NONE {
1410            return (alias, Slice::default());
1411        }
1412        let mut columns = Vec::new();
1413        for kid in self.kids(list) {
1414            let name = self.identifier(kid);
1415            columns.push(name);
1416        }
1417        (alias, self.part_slice(columns))
1418    }
1419
1420    /// `JoinClause <- JoinByClause / RegularJoinClause / JoinWithoutOnClause / NearestJoinClause`.
1421    fn join(&mut self, left: SourceRef, node: u32) -> Result<SourceRef> {
1422        match self.name(node) {
1423            // `RegularJoinClause <- Asof? JoinType? 'JOIN' TableRef JoinQualifier`.
1424            "RegularJoinClause" => {
1425                if self.find(node, "Asof") != NONE {
1426                    return self.unsupported(node);
1427                }
1428                let kind = self.join_type(self.find(node, "JoinType"));
1429                let right = self.table_ref(self.find(node, "TableRef"))?;
1430                let (on, using) = self.join_qualifier(self.find(node, "JoinQualifier"))?;
1431                Ok(self.push_source(Source::Join { left, right, kind, natural: false, on, using }))
1432            }
1433            // `JoinWithoutOnClause <- JoinPrefix 'JOIN' InnerTableRef`, which is cross, natural and
1434            // positional. Those three are exactly the joins that carry no condition.
1435            "JoinWithoutOnClause" => {
1436                let prefix = self.first(self.find(node, "JoinPrefix"));
1437                let (kind, natural) = match self.name(prefix) {
1438                    "CrossJoinPrefix" => (JoinKind::Cross, false),
1439                    "PositionalJoinPrefix" => (JoinKind::Positional, false),
1440                    "NaturalJoinPrefix" => (self.join_type(self.find(prefix, "JoinType")), true),
1441                    _ => return self.unsupported(prefix),
1442                };
1443                let right = self.inner_table_ref(self.find(node, "InnerTableRef"))?;
1444                Ok(self.push_source(Source::Join {
1445                    left,
1446                    right,
1447                    kind,
1448                    natural,
1449                    on: NONE,
1450                    using: Slice::default(),
1451                }))
1452            }
1453            _ => self.unsupported(node),
1454        }
1455    }
1456
1457    /// `JoinType <- FullJoin / LeftJoin / RightJoin / SemiJoin / AntiJoin / InnerJoin`, absent
1458    /// meaning inner, which is what SQL has always meant by a bare `JOIN`.
1459    fn join_type(&self, node: u32) -> JoinKind {
1460        if node == NONE {
1461            return JoinKind::Inner;
1462        }
1463        match self.name(self.first(node)) {
1464            "FullJoin" => JoinKind::Full,
1465            "LeftJoin" => JoinKind::Left,
1466            "RightJoin" => JoinKind::Right,
1467            "SemiJoin" => JoinKind::Semi,
1468            "AntiJoin" => JoinKind::Anti,
1469            _ => JoinKind::Inner,
1470        }
1471    }
1472
1473    /// `JoinQualifier <- OnClause / UsingClause`.
1474    fn join_qualifier(&mut self, node: u32) -> Result<(ExprRef, Slice)> {
1475        let inner = self.first(node);
1476        match self.name(inner) {
1477            "OnClause" => Ok((self.expr(self.first(inner))?, Slice::default())),
1478            "UsingClause" => {
1479                let mut columns = Vec::new();
1480                for kid in self.kids(inner) {
1481                    let name = self.identifier(kid);
1482                    columns.push(name);
1483                }
1484                Ok((NONE, self.part_slice(columns)))
1485            }
1486            _ => self.unsupported(inner),
1487        }
1488    }
1489
1490    // Expressions.
1491
1492    /// One expression, from wherever in the precedence chain it starts.
1493    ///
1494    /// The loop is the whole design. A rule that says something gets an arm, a rule with exactly
1495    /// one child that said nothing is stepped through, and anything else is an error naming itself.
1496    /// The chain rules never get an arm for their one child case, which is why adding a precedence
1497    /// level upstream costs nothing here.
1498    ///
1499    /// Said nothing means covered no text of its own. A keyword is not a child of the node that
1500    /// spells it, so `TRIM(x)` is a rule with one child and that child is `x`, and stepping through
1501    /// on the child count alone threw the `TRIM` away and answered the untrimmed string. Comparing
1502    /// the two spans is what tells the two cases apart: a precedence rule with one child covers
1503    /// exactly what its child covers, and a rule that wrote a keyword or a bracket covers more.
1504    /// That is the rule rather than a list of the names it happened to be wrong about, because the
1505    /// grammar has eleven hundred rules and the ones with a keyword and one child are not enumerable
1506    /// by reading the ones that are wrong today.
1507    fn expr(&mut self, node: u32) -> Result<ExprRef> {
1508        let mut node = node;
1509        loop {
1510            let count = self.count(node);
1511            let name = self.name(node);
1512            match name {
1513                "LogicalOrExpression" if count > 1 => return self.logical(node, BinaryOp::Or),
1514                "LogicalAndExpression" if count > 1 => return self.logical(node, BinaryOp::And),
1515                "LogicalNotExpression" if count > 1 => return self.logical_not(node),
1516                "IsExpression" if count > 1 => return self.is_expression(node),
1517                "BetweenInLikeExpression" if count > 1 => return self.between_in_like(node),
1518                "PrefixExpression" if count > 1 => return self.prefix(node),
1519                "BaseExpression" if count > 1 => return self.indirection(node),
1520                "LambdaArrowExpression"
1521                | "IsDistinctFromExpression"
1522                | "ComparisonExpression"
1523                | "OtherOperatorExpression"
1524                | "BitwiseExpression"
1525                | "AdditiveExpression"
1526                | "MultiplicativeExpression"
1527                | "ExponentiationExpression"
1528                | "CollateExpression"
1529                | "AtTimeZoneExpression"
1530                    if count > 1 =>
1531                {
1532                    return self.tail_chain(node);
1533                }
1534                "ColumnReference" => {
1535                    let name = self.name_parts(node);
1536                    return Ok(self.push(Expr::Column { name }));
1537                }
1538                "StarExpression" => return self.star(node),
1539                "NumberLiteral" => {
1540                    let text = self.text(node).to_string();
1541                    let text = self.intern(&text);
1542                    return Ok(self.push(Expr::Literal { kind: LiteralKind::Number, text }));
1543                }
1544                "StringLiteral" => return self.string_literal(node),
1545                "NullLiteral" | "TrueLiteral" | "FalseLiteral" => {
1546                    let kind = match name {
1547                        "NullLiteral" => LiteralKind::Null,
1548                        "TrueLiteral" => LiteralKind::True,
1549                        _ => LiteralKind::False,
1550                    };
1551                    return Ok(self.push(Expr::Literal { kind, text: NONE }));
1552                }
1553                "FunctionExpression" => return self.function(node),
1554                "CoalesceExpression" => return self.coalesce(node),
1555                "NullIfExpression" => return self.null_if(node),
1556                "SubstringExpression" => return self.substring(node),
1557                "PositionExpression" => return self.position(node),
1558                "TrimExpression" => return self.trim(node),
1559                "OverlayExpression" => return self.overlay(node),
1560                "ExtractExpression" => return self.extract(node),
1561                "CastExpression" => return self.cast(node),
1562                "TypeLiteral" => return self.typed_literal(node),
1563                "IntervalLiteral" => return self.interval_literal(node),
1564                "CaseExpression" => return self.case(node),
1565                "ParenthesisExpression" => return self.row(node),
1566                // `ParensExpression <- Parens(Expression)` covers more text than its child and
1567                // still says nothing about the value, because the brackets are grouping. It is the
1568                // one rule of that shape, which is why it is an arm rather than a second rule in
1569                // the step below. `ParenthesisExpression` is not this: it holds a list, and a list
1570                // of more than one is a row.
1571                "ParensExpression" if count == 1 => node = self.first(node),
1572                "BoundedListExpression" => return self.list(node),
1573                "QuestionMarkNumberedParameter"
1574                | "AnonymousParameter"
1575                | "NumberedParameter"
1576                | "ColLabelParameter" => return self.parameter(node),
1577                "SubqueryExpression" => return self.subquery(node),
1578                _ if count == 1 && self.text(self.first(node)) == self.text(node) => {
1579                    node = self.first(node);
1580                }
1581                _ => return self.unsupported(node),
1582            }
1583        }
1584    }
1585
1586    /// `X <- Y XTail*` where `XTail <- Operator Y`, the shape ten precedence levels share.
1587    fn tail_chain(&mut self, node: u32) -> Result<ExprRef> {
1588        let mut kids = self.kids(node);
1589        let head = kids.next().unwrap_or(NONE);
1590        let mut left = self.expr(head)?;
1591        for tail in kids {
1592            let operator = self.first(tail);
1593            // `ComparisonExpressionTail <- ComparisonOperator NotExpression? BetweenInLikeExpression`
1594            // is the one tail with an optional middle, so the operand is the last child and not the
1595            // second one. Taking the last is right for every tail and wrong for none.
1596            let operand = self.kids(tail).last().unwrap_or(NONE);
1597            if self.count(tail) > 2 {
1598                return self.unsupported(tail);
1599            }
1600            if self.contains(operator, "AnyAllParsedOperator") {
1601                let any_op = self.descendant(operator, "AnyOp");
1602                let op = self.binary_op(any_op)?;
1603                let reference = self.descendant(operand, "SubqueryReference");
1604                if reference == NONE {
1605                    return self.unsupported(operand);
1606                }
1607                let query = self.query(self.first(reference))?;
1608                let all = self.contains(operator, "SubqueryAll");
1609                left = self.push(Expr::QuantifiedSubquery { operand: left, op, query, all });
1610                continue;
1611            }
1612            let op = self.binary_op(operator)?;
1613            let right = self.expr(operand)?;
1614            left = self.push(Expr::Binary { op, left, right });
1615        }
1616        Ok(left)
1617    }
1618
1619    /// Which infix operator a tail's operator node is.
1620    fn binary_op(&mut self, node: u32) -> Result<BinaryOp> {
1621        // The operator rules nest: `ComparisonOperator` over `OperatorGreaterThan` over the symbol
1622        // itself. Every one of them covers the same tokens, so the text is the same at every level
1623        // and reading it once at the top is enough. The name is not, which is why the bottom of the
1624        // chain is walked to as well: `OtherOperator` says nothing and `OperatorLiteral` says
1625        // everything, and they are three levels apart.
1626        let mut leaf = node;
1627        while self.count(leaf) == 1 {
1628            leaf = self.first(leaf);
1629        }
1630        let text = self.text(node);
1631        let upper = text.to_ascii_uppercase();
1632        let op = match upper.as_str() {
1633            "OR" => BinaryOp::Or,
1634            "AND" => BinaryOp::And,
1635            "=" | "==" => BinaryOp::Eq,
1636            "!=" | "<>" => BinaryOp::NotEq,
1637            "<" => BinaryOp::Lt,
1638            ">" => BinaryOp::Gt,
1639            "<=" => BinaryOp::LtEq,
1640            ">=" => BinaryOp::GtEq,
1641            "+" => BinaryOp::Add,
1642            "-" => BinaryOp::Subtract,
1643            "*" => BinaryOp::Multiply,
1644            "/" => BinaryOp::Divide,
1645            "//" => BinaryOp::IntegerDivide,
1646            "%" => BinaryOp::Modulo,
1647            "^" | "**" => BinaryOp::Power,
1648            "&" => BinaryOp::BitAnd,
1649            "|" => BinaryOp::BitOr,
1650            "<<" => BinaryOp::ShiftLeft,
1651            ">>" => BinaryOp::ShiftRight,
1652            "||" => BinaryOp::Concat,
1653            "COLLATE" => BinaryOp::Collate,
1654            "->" => BinaryOp::Arrow,
1655            "->>" => BinaryOp::LongArrow,
1656            "@>" => BinaryOp::Contains,
1657            "<@" => BinaryOp::ContainedBy,
1658            "&&" => BinaryOp::Overlaps,
1659            "^@" => BinaryOp::StartsWith,
1660            "<<=" => BinaryOp::InetContainedByOrEq,
1661            ">>=" => BinaryOp::InetContainsOrEq,
1662            _ if self.name(leaf) == "AtTimeZoneOperator" => BinaryOp::AtTimeZone,
1663            // `IsDistinctFromOp <- 'IS' 'NOT'? 'DISTINCT' 'FROM'`, told apart by the middle word,
1664            // which is not in the tree because keywords are terminals.
1665            _ if self.name(leaf) == "IsDistinctFromOp" => {
1666                if upper.split_whitespace().any(|word| word == "NOT") {
1667                    BinaryOp::IsNotDistinctFrom
1668                } else {
1669                    BinaryOp::IsDistinctFrom
1670                }
1671            }
1672            // `OperatorLiteral` is the open end of the operator set. Its body in the grammar text
1673            // says `Identifier`, but it is one of the 24 rules whose body the matcher does not
1674            // walk and the matcher it is overridden to is the bare operator one, so what it
1675            // actually accepts is any run of operator characters that is not already a token.
1676            // `a <=> b` is such a run, DuckDB resolves it as a two argument function of that name,
1677            // and rejecting it here would reject SQL DuckDB accepts.
1678            _ if self.name(leaf) == "OperatorLiteral" => {
1679                let interned = self.intern(text);
1680                BinaryOp::Named(interned)
1681            }
1682            _ => return self.unsupported(node),
1683        };
1684        Ok(op)
1685    }
1686
1687    /// `LogicalOrExpression <- LogicalAndExpression LogicalOrExpressionTail*`, and the `AND` twin.
1688    ///
1689    /// Separate from the other tails because the tail here is `'OR' LogicalAndExpression` with the
1690    /// keyword as a terminal, so there is no operator node to read and the operator is the rule.
1691    fn logical(&mut self, node: u32, op: BinaryOp) -> Result<ExprRef> {
1692        let mut kids = self.kids(node);
1693        let head = kids.next().unwrap_or(NONE);
1694        let mut left = self.expr(head)?;
1695        for tail in kids {
1696            let right = self.expr(self.first(tail))?;
1697            left = self.push(Expr::Binary { op, left, right });
1698        }
1699        Ok(left)
1700    }
1701
1702    /// `LogicalNotExpression <- NotExpression? IsExpression`, where `NotExpression <- NotKeyword+`.
1703    ///
1704    /// The plus matters. `NOT NOT x` is two nodes in the parse tree and two negations in the AST,
1705    /// and folding them here would be an optimizer decision taken in the parser.
1706    fn logical_not(&mut self, node: u32) -> Result<ExprRef> {
1707        let negations = self.count(self.first(node));
1708        let mut expr = self.expr(self.nth(node, 1))?;
1709        for _ in 0..negations {
1710            expr = self.push(Expr::Unary { op: UnaryOp::Not, operand: expr });
1711        }
1712        Ok(expr)
1713    }
1714
1715    /// `IsExpression <- IsDistinctFromExpression IsTest*`, the postfix null and boolean tests.
1716    fn is_expression(&mut self, node: u32) -> Result<ExprRef> {
1717        let mut kids = self.kids(node);
1718        let head = kids.next().unwrap_or(NONE);
1719        let mut expr = self.expr(head)?;
1720        for test in kids {
1721            let inner = self.first(test);
1722            let negated = self.text(inner).to_ascii_uppercase().contains("NOT");
1723            let op = match self.name(inner) {
1724                "NotNull" => UnaryOp::IsNotNull,
1725                "IsNull" => UnaryOp::IsNull,
1726                // `IsLiteral <- 'IS' 'NOT'? IsLiteralValue`, and the value rule is one more level
1727                // down again because it is a choice of four and not four alternatives inlined.
1728                "IsLiteral" => match self.name(self.first(self.first(inner))) {
1729                    "NullLiteral" if negated => UnaryOp::IsNotNull,
1730                    "NullLiteral" => UnaryOp::IsNull,
1731                    "TrueLiteral" if negated => UnaryOp::IsNotTrue,
1732                    "TrueLiteral" => UnaryOp::IsTrue,
1733                    "FalseLiteral" if negated => UnaryOp::IsNotFalse,
1734                    "FalseLiteral" => UnaryOp::IsFalse,
1735                    "UnknownLiteral" if negated => UnaryOp::IsNotUnknown,
1736                    "UnknownLiteral" => UnaryOp::IsUnknown,
1737                    _ => return self.unsupported(inner),
1738                },
1739                _ => return self.unsupported(inner),
1740            };
1741            expr = self.push(Expr::Unary { op, operand: expr });
1742        }
1743        Ok(expr)
1744    }
1745
1746    /// `BetweenInLikeExpression <- OtherOperatorExpression BetweenInLikeOp?`.
1747    fn between_in_like(&mut self, node: u32) -> Result<ExprRef> {
1748        let operand = self.expr(self.first(node))?;
1749        // `BetweenInLikeOp <- 'NOT'? BetweenInLikeOpExpression`. The `NOT` is a terminal, so what
1750        // says it was written is that the op node covers a token the inner node does not.
1751        let op = self.nth(node, 1);
1752        let negated = self.text(op).to_ascii_uppercase().starts_with("NOT");
1753        let inner = self.first(self.first(op));
1754        match self.name(inner) {
1755            // `BetweenClause <- 'BETWEEN' x 'AND' y`.
1756            "BetweenClause" => {
1757                let low = self.expr(self.first(inner))?;
1758                let high = self.expr(self.nth(inner, 1))?;
1759                Ok(self.push(Expr::Between { operand, low, high, negated }))
1760            }
1761            // `InClause <- 'IN' InExpression`.
1762            "InClause" => {
1763                let expression = self.first(self.first(inner));
1764                match self.name(expression) {
1765                    "InExpressionList" => {
1766                        let mut items = Vec::new();
1767                        for kid in self.kids(expression) {
1768                            items.push(self.expr(kid)?);
1769                        }
1770                        let list = self.expr_slice(items);
1771                        Ok(self.push(Expr::In { operand, list, negated }))
1772                    }
1773                    "InSelectStatement" => {
1774                        let query = self.query(self.first(expression))?;
1775                        Ok(self.push(Expr::InSubquery { operand, query, negated }))
1776                    }
1777                    _ => self.unsupported(expression),
1778                }
1779            }
1780            // `LikeClause <- LikeVariations x EscapeClause?`.
1781            "LikeClause" => {
1782                if self.find(inner, "EscapeClause") != NONE {
1783                    return self.unsupported(inner);
1784                }
1785                let variation = self.name(self.first(self.first(inner)));
1786                let op = match (variation, negated) {
1787                    ("LikeToken", false) | ("NotLikeOp", true) => BinaryOp::Like,
1788                    ("LikeToken", true) | ("NotLikeOp", false) => BinaryOp::NotLike,
1789                    ("ILikeToken", false) | ("NotILikeOp", true) => BinaryOp::ILike,
1790                    ("ILikeToken", true) | ("NotILikeOp", false) => BinaryOp::NotILike,
1791                    // Glob and the bare regex match have no negated spelling of their own in
1792                    // `LikeVariations`, so a `NOT` in front of either stays an explicit negation.
1793                    ("GlobToken", _) => BinaryOp::Glob,
1794                    ("RegexMatchToken", _) => BinaryOp::Regex,
1795                    ("SimilarToToken", false) => BinaryOp::SimilarTo,
1796                    ("SimilarToToken", true) => BinaryOp::NotSimilarTo,
1797                    ("NotSimilarToOp", false) => BinaryOp::NotRegex,
1798                    ("NotSimilarToOp", true) => BinaryOp::Regex,
1799                    ("RegexInsensitiveMatchToken", false)
1800                    | ("NotRegexInsensitiveMatchOp", true) => BinaryOp::RegexInsensitive,
1801                    ("RegexInsensitiveMatchToken", true)
1802                    | ("NotRegexInsensitiveMatchOp", false) => BinaryOp::NotRegexInsensitive,
1803                    _ => return self.unsupported(inner),
1804                };
1805                let right = self.expr(self.nth(inner, 1))?;
1806                let expr = self.push(Expr::Binary { op, left: operand, right });
1807                // The like family folds its negation into the operator because it has a spelling
1808                // for the negated form. Glob and regex do not, so theirs stays where it was.
1809                if negated && matches!(op, BinaryOp::Glob | BinaryOp::Regex) {
1810                    return Ok(self.push(Expr::Unary { op: UnaryOp::Not, operand: expr }));
1811                }
1812                Ok(expr)
1813            }
1814            _ => self.unsupported(inner),
1815        }
1816    }
1817
1818    /// `PrefixExpression <- PrefixOperator* BaseExpression`, applied right to left.
1819    fn prefix(&mut self, node: u32) -> Result<ExprRef> {
1820        let kids: Vec<u32> = self.kids(node).collect();
1821        let mut expr = self.expr(kids[kids.len() - 1])?;
1822        for &operator in kids[..kids.len() - 1].iter().rev() {
1823            let op = match self.name(self.first(operator)) {
1824                "MinusPrefixOperator" => UnaryOp::Negate,
1825                "PlusPrefixOperator" => UnaryOp::Plus,
1826                "TildePrefixOperator" => UnaryOp::BitNot,
1827                _ => return self.unsupported(operator),
1828            };
1829            expr = self.push(Expr::Unary { op, operand: expr });
1830        }
1831        Ok(expr)
1832    }
1833
1834    /// `BaseExpression <- SingleExpression IndirectionList?`, the postfix chain.
1835    fn indirection(&mut self, node: u32) -> Result<ExprRef> {
1836        let mut expr = self.expr(self.first(node))?;
1837        for step in self.kids(self.nth(node, 1)) {
1838            let inner = self.first(step);
1839            expr = match self.name(inner) {
1840                // `CastOperator <- '::' Type`.
1841                "CastOperator" => {
1842                    let text = self.text(self.first(inner)).to_string();
1843                    let ty = self.intern(&text);
1844                    self.push(Expr::Cast { operand: expr, ty, try_cast: false })
1845                }
1846                "DotOperator" => {
1847                    let dot = self.first(inner);
1848                    match self.name(dot) {
1849                        // `DotColumnOperator <- '.' ColLabel`, which DuckDB resolves as a call of
1850                        // `struct_extract`. Writing it as that call rather than as its own node
1851                        // keeps the binder from needing a rule for a thing that is already a
1852                        // function.
1853                        "DotColumnOperator" => {
1854                            let field = self.identifier(self.first(dot));
1855                            let text = self.ast.string(field).to_string();
1856                            let literal = self.intern(&text);
1857                            let key = self
1858                                .push(Expr::Literal { kind: LiteralKind::String, text: literal });
1859                            let name = self.function_name("struct_extract");
1860                            let args = self.expr_slice(vec![expr, key]);
1861                            self.push(Expr::Function { name, args, distinct: false })
1862                        }
1863                        // `DotMethodOperator <- '.' MethodExpression`, where `x.f(a)` is `f(x, a)`.
1864                        "DotMethodOperator" => {
1865                            let method = self.first(dot);
1866                            let text = self.text(self.first(method)).to_string();
1867                            let text = unquote(&text);
1868                            let name = self.function_name(&text);
1869                            let mut args = vec![expr];
1870                            let list = self.find(method, "MethodExpressionArguments");
1871                            if list != NONE {
1872                                let inner = self.first(list);
1873                                let arguments = self.find(inner, "MethodFunctionArguments");
1874                                if arguments != NONE {
1875                                    for kid in self.kids(arguments) {
1876                                        args.push(self.argument(kid)?);
1877                                    }
1878                                }
1879                            }
1880                            let args = self.expr_slice(args);
1881                            self.push(Expr::Function { name, args, distinct: false })
1882                        }
1883                        _ => return self.unsupported(dot),
1884                    }
1885                }
1886                // `SliceExpression <- '[' SliceBound ']'` over
1887                // `SliceBound <- Expression? EndSliceBound? StepSliceBound?`, so a subscript is one
1888                // index when neither colon is there and a range when either of them is. Both become
1889                // a call, the same two calls DuckDB's own transformer writes.
1890                "SliceExpression" => self.subscript(inner, expr)?,
1891                // `PostfixOperator <- '!'`.
1892                "PostfixOperator" => {
1893                    self.push(Expr::Unary { op: UnaryOp::Factorial, operand: expr })
1894                }
1895                _ => return self.unsupported(inner),
1896            };
1897        }
1898        Ok(expr)
1899    }
1900
1901    /// `SliceExpression <- '[' SliceBound ']'`, which is `array_extract` or `array_slice`.
1902    ///
1903    /// The three parts of the bound are all optional and any of the eight combinations parses, so
1904    /// which call this is comes from which parts are there rather than from how many children the
1905    /// bound has. One expression and no colon is an index. Anything with a colon in it is a range,
1906    /// and a range the query did not write both ends of gets the ends DuckDB's transformer gives it:
1907    /// a missing begin is 1 and a missing end is -1, which is the last element, so `x[:]` is the
1908    /// whole of `x` and `array_slice(x, 1, -1)` answers the same thing.
1909    ///
1910    /// `EndSliceMinus` is the `-` in `x[1:-]`, which upstream reads as a range with no end rather
1911    /// than as a subtraction of nothing, and it answers `x[1:]`. So it is the missing end too.
1912    ///
1913    /// The step is the odd one. `x[1:2:]` is a step that is written and empty, and what upstream
1914    /// does with it is pass a list where the step goes, which then fails to bind because the fourth
1915    /// parameter is a BIGINT. The empty list here is that, measured off the pinned binary: it says
1916    /// `array_slice(INTEGER[], INTEGER_LITERAL, INTEGER_LITERAL, INTEGER[])` has no match, and the
1917    /// fourth type in that sentence is the list. Writing a 1 there instead would answer a row where
1918    /// the reference refuses.
1919    fn subscript(&mut self, node: u32, target: ExprRef) -> Result<ExprRef> {
1920        let bound = self.first(node);
1921        let (mut begin, mut end, mut step) = (NONE, NONE, NONE);
1922        for kid in self.kids(bound) {
1923            match self.name(kid) {
1924                "EndSliceBound" => end = kid,
1925                "StepSliceBound" => step = kid,
1926                _ => begin = kid,
1927            }
1928        }
1929        if end == NONE && step == NONE {
1930            if begin == NONE {
1931                return Err(Error::parser("Empty subscript '[]' is not allowed"));
1932            }
1933            let index = self.expr(begin)?;
1934            let name = self.function_name("array_extract");
1935            let args = self.expr_slice(vec![target, index]);
1936            return Ok(self.push(Expr::Function { name, args, distinct: false }));
1937        }
1938        let first = if begin == NONE { self.literal_number("1") } else { self.expr(begin)? };
1939        // `EndSliceBound <- ':' EndSliceValue?` and `EndSliceValue <- Expression / EndSliceMinus`,
1940        // so the end is written only when the value is there and is not the lone hyphen.
1941        let value = if end == NONE { NONE } else { self.find(end, "EndSliceValue") };
1942        let written = if value == NONE { NONE } else { self.first(value) };
1943        let last = if written == NONE || self.name(written) == "EndSliceMinus" {
1944            self.literal_number("-1")
1945        } else {
1946            self.expr(written)?
1947        };
1948        let mut args = vec![target, first, last];
1949        if step != NONE {
1950            let by = self.first(step);
1951            args.push(if by == NONE {
1952                self.push(Expr::List { items: Slice::default() })
1953            } else {
1954                self.expr(by)?
1955            });
1956        }
1957        let name = self.function_name("array_slice");
1958        let args = self.expr_slice(args);
1959        Ok(self.push(Expr::Function { name, args, distinct: false }))
1960    }
1961
1962    /// A number literal the transformer writes rather than reads, for a bound a range left out.
1963    fn literal_number(&mut self, digits: &str) -> ExprRef {
1964        let text = self.intern(digits);
1965        self.push(Expr::Literal { kind: LiteralKind::Number, text })
1966    }
1967
1968    /// A one part function name, for the calls the transformer invents rather than reads.
1969    fn function_name(&mut self, name: &str) -> Slice {
1970        let interned = self.intern(name);
1971        self.part_slice(vec![interned])
1972    }
1973
1974    /// `StarExpression <- StarQualifierList? '*' ExcludeList? ReplaceList? RenameList?`.
1975    fn star(&mut self, node: u32) -> Result<ExprRef> {
1976        for name in ["ExcludeList", "RenameList"] {
1977            let list = self.find(node, name);
1978            if list != NONE {
1979                return self.unsupported(list);
1980            }
1981        }
1982        let replace = self.find(node, "ReplaceList");
1983        let replacements =
1984            if replace == NONE { Slice::default() } else { self.replacements(replace)? };
1985        let qualifier = self.find(node, "StarQualifierList");
1986        let qualifier =
1987            if qualifier == NONE { Slice::default() } else { self.name_parts(qualifier) };
1988        Ok(self.push(Expr::Star { qualifier, replacements }))
1989    }
1990
1991    /// `ReplaceList <- 'REPLACE' ReplaceEntries`, where an entry is `Expression 'AS'
1992    /// ColumnReference` and the entries are one bare entry or a parenthesized list of them.
1993    ///
1994    /// The duplicate check is here rather than in the binder because that is where DuckDB does it:
1995    /// naming the same column twice is a Parser Error there, and it is one of the few things about
1996    /// a star that can be decided without knowing what the star stands for.
1997    fn replacements(&mut self, node: u32) -> Result<Slice> {
1998        // `ReplaceEntries <- ReplaceEntrySingle / ReplaceEntryList` and both of those hold the
1999        // entries as their own children, so the same walk reads either shape.
2000        let entries = self.first(self.first(node));
2001        let listed: Vec<u32> =
2002            self.kids(entries).filter(|&kid| self.name(kid) == "ReplaceEntry").collect();
2003        let mut replacements = Vec::with_capacity(listed.len());
2004        for entry in listed {
2005            let expr = self.expr(self.first(entry))?;
2006            let alias = self.identifier(self.nth(entry, 1));
2007            let written = self.ast.string(alias).to_string();
2008            if replacements
2009                .iter()
2010                .any(|held: &Target| self.ast.string(held.alias).eq_ignore_ascii_case(&written))
2011            {
2012                return Err(Error::parser(format!(
2013                    "Duplicate entry \"{written}\" in REPLACE list"
2014                )));
2015            }
2016            replacements.push(Target { expr, alias });
2017        }
2018        Ok(self.target_slice(replacements))
2019    }
2020
2021    /// `FunctionExpression <- FunctionIdentifier FunctionExpressionArguments WithinGroupClause?
2022    /// FilterClause? ExportClause? OverClause?`.
2023    fn function(&mut self, node: u32) -> Result<ExprRef> {
2024        for name in ["WithinGroupClause", "FilterClause", "ExportClause", "OverClause"] {
2025            let clause = self.find(node, name);
2026            if clause != NONE {
2027                return self.unsupported(clause);
2028            }
2029        }
2030        let name = self.name_parts(self.first(node));
2031        // `FunctionExpressionArguments <- Parens(FunctionExpressionArgumentList)` and
2032        // `FunctionExpressionArgumentList <- DistinctOrAll? FunctionArgumentList? OrderByClause?
2033        // IgnoreOrRespectNulls?`, so a call with no arguments still has both wrappers.
2034        let list = self.first(self.nth(node, 1));
2035        for name in ["OrderByClause", "IgnoreOrRespectNulls"] {
2036            let clause = self.find(list, name);
2037            if clause != NONE {
2038                return self.unsupported(clause);
2039            }
2040        }
2041        let distinct = self.quantifier(self.find(list, "DistinctOrAll")) == Quantifier::Distinct;
2042        let mut args = Vec::new();
2043        let arguments = self.find(list, "FunctionArgumentList");
2044        if arguments != NONE {
2045            for kid in self.kids(arguments) {
2046                args.push(self.argument(kid)?);
2047            }
2048        }
2049        // `IFNULL` is an ordinary call in the grammar and is not one by the time DuckDB's parser is
2050        // done with it: `ifnull(NULL, 3)` comes back named `COALESCE(NULL, 3)` there, and so does
2051        // `main.ifnull(NULL, 3)`, so the qualifier goes with the rewrite. The count is checked here
2052        // because that is where upstream checks it, with the sentence below rather than the binder's
2053        // arity error, and it is checked before the two arguments are looked at.
2054        if self.ast.name(name).last().is_some_and(|part| part.eq_ignore_ascii_case("ifnull")) {
2055            if args.len() != 2 {
2056                return Err(Error::parser("Wrong number of arguments to IFNULL."));
2057            }
2058            let args = self.expr_slice(args);
2059            let name = self.function_name("coalesce");
2060            return Ok(self.push(Expr::Function { name, args, distinct }));
2061        }
2062        let args = self.expr_slice(args);
2063        Ok(self.push(Expr::Function { name, args, distinct }))
2064    }
2065
2066    /// `CoalesceExpression <- 'COALESCE' Parens(List(Expression))`.
2067    ///
2068    /// A keyword is not a child and the two wrappers are transparent, so the children are the
2069    /// arguments. One of them is enough for the grammar and none of them is a syntax error, which is
2070    /// why there is no count checked here.
2071    ///
2072    /// The call is written with the canonical name rather than the one the query used, since there is
2073    /// nothing else to keep: the keyword is the name. Upstream prints the column in capitals whatever
2074    /// case was written, because `COALESCE` is an operator there and not a function name that its
2075    /// parser folded, and the binder is where that is decided here.
2076    fn coalesce(&mut self, node: u32) -> Result<ExprRef> {
2077        let mut args = Vec::new();
2078        for kid in self.kids(node) {
2079            args.push(self.expr(kid)?);
2080        }
2081        let args = self.expr_slice(args);
2082        let name = self.function_name("coalesce");
2083        Ok(self.push(Expr::Function { name, args, distinct: false }))
2084    }
2085
2086    /// `NullIfExpression <- 'NULLIF' Parens(NullIfArguments)` and
2087    /// `NullIfArguments <- Expression ',' Expression`.
2088    ///
2089    /// Exactly two arguments, because the rule says so: `nullif(1)` and `nullif(1, 2, 3)` are syntax
2090    /// errors upstream and are syntax errors here for the same reason, so there is no arity to check
2091    /// after the parse.
2092    ///
2093    /// It stays a function called `nullif` rather than becoming the `CASE` upstream's macro expands
2094    /// to, since the column it produces is named after the call and not after the expansion.
2095    fn null_if(&mut self, node: u32) -> Result<ExprRef> {
2096        let arguments = self.find(node, "NullIfArguments");
2097        if arguments == NONE {
2098            return self.unsupported(node);
2099        }
2100        let mut args = Vec::new();
2101        for kid in self.kids(arguments) {
2102            args.push(self.expr(kid)?);
2103        }
2104        let args = self.expr_slice(args);
2105        let name = self.function_name("nullif");
2106        Ok(self.push(Expr::Function { name, args, distinct: false }))
2107    }
2108
2109    /// `SubstringExpression <- 'SUBSTRING' Parens(SubstringArguments)` and
2110    /// `SubstringArguments <- SubstringParameters / SubstringExpressionList`.
2111    ///
2112    /// Both spellings are the same call and DuckDB's parser writes both of them back out as one:
2113    /// `substring(s FROM a FOR b)` comes back as the column `"substring"(s, a, b)` there, and so does
2114    /// `substring(s, a, b)`. The `FOR` on its own is the one worth pointing at, since it is not the
2115    /// two argument call it looks like. `substring('abcdef' FOR 3)` is `"substring"('abcdef', 1, 3)`
2116    /// upstream, so the start is filled in with a literal 1 here rather than left out.
2117    fn substring(&mut self, node: u32) -> Result<ExprRef> {
2118        let shape = self.first(self.first(node));
2119        let mut args = Vec::new();
2120        match self.name(shape) {
2121            "SubstringExpressionList" => {
2122                for kid in self.kids(shape) {
2123                    args.push(self.expr(kid)?);
2124                }
2125            }
2126            "SubstringParameters" => {
2127                args.push(self.expr(self.first(shape))?);
2128                // `SubstringFromFor <- SubstringFromOptionalFor / SubstringFor`, and both of those
2129                // hold the bounds as `FromExpression` and `ForExpression`, so finding them by name
2130                // reads either shape and neither one has to be told apart from the other.
2131                let bounds = self.first(self.nth(shape, 1));
2132                let from = self.find(bounds, "FromExpression");
2133                let start =
2134                    if from == NONE { self.number("1") } else { self.expr(self.first(from))? };
2135                args.push(start);
2136                let count = self.find(bounds, "ForExpression");
2137                if count != NONE {
2138                    args.push(self.expr(self.first(count))?);
2139                }
2140            }
2141            _ => return self.unsupported(shape),
2142        }
2143        let args = self.expr_slice(args);
2144        let name = self.function_name("substring");
2145        Ok(self.push(Expr::Function { name, args, distinct: false }))
2146    }
2147
2148    /// `PositionExpression <- 'POSITION' Parens(PositionArguments)` and
2149    /// `PositionArguments <- OtherOperatorExpression 'IN' Expression`.
2150    ///
2151    /// The two arguments swap. `position('c' IN 'abcdef')` is `"position"('abcdef', 'c')` upstream,
2152    /// which is the same order `strpos` and `instr` are written in, so the haystack comes first in
2153    /// the call and second in the query.
2154    fn position(&mut self, node: u32) -> Result<ExprRef> {
2155        let arguments = self.first(node);
2156        if self.count(arguments) != 2 {
2157            return self.unsupported(arguments);
2158        }
2159        let needle = self.expr(self.first(arguments))?;
2160        let haystack = self.expr(self.nth(arguments, 1))?;
2161        let args = self.expr_slice(vec![haystack, needle]);
2162        let name = self.function_name("position");
2163        Ok(self.push(Expr::Function { name, args, distinct: false }))
2164    }
2165
2166    /// `TrimExpression <- 'TRIM' Parens(TrimArguments)` and
2167    /// `TrimArguments <- TrimDirection? TrimSource? List(Expression)`.
2168    ///
2169    /// The direction is not an argument, it is the function: `LEADING` is `ltrim` upstream and
2170    /// `TRAILING` is `rtrim`, while `BOTH` and the bare form are both `trim`. The characters to strip
2171    /// are the last argument whichever way they were written, so `trim(BOTH 'x' FROM 'xxaxx')` and
2172    /// `trim('xxaxx', 'x')` are the same call, which is why the source goes on the end of the list
2173    /// rather than in front of it.
2174    fn trim(&mut self, node: u32) -> Result<ExprRef> {
2175        let arguments = self.first(node);
2176        let direction = self.find(arguments, "TrimDirection");
2177        let name = match direction {
2178            NONE => "trim",
2179            held => match self.name(self.first(held)) {
2180                "TrimLeading" => "ltrim",
2181                "TrimTrailing" => "rtrim",
2182                _ => "trim",
2183            },
2184        };
2185        let mut args = Vec::new();
2186        for kid in self.kids(arguments) {
2187            if matches!(self.name(kid), "TrimDirection" | "TrimSource") {
2188                continue;
2189            }
2190            args.push(self.expr(kid)?);
2191        }
2192        // `TrimSource <- Expression? 'FROM'`, so `trim(LEADING FROM s)` has the node with nothing
2193        // under it and there is no second argument to add.
2194        let source = self.find(arguments, "TrimSource");
2195        if source != NONE && self.count(source) == 1 {
2196            args.push(self.expr(self.first(source))?);
2197        }
2198        let args = self.expr_slice(args);
2199        let name = self.function_name(name);
2200        Ok(self.push(Expr::Function { name, args, distinct: false }))
2201    }
2202
2203    /// `OverlayExpression <- 'OVERLAY' Parens(OverlayArguments)` and
2204    /// `OverlayArguments <- OverlayParameters / OverlayExpressionList`, where
2205    /// `OverlayParameters <- Expression 'PLACING' Expression FromExpression ForExpression?`.
2206    ///
2207    /// The arguments are already in the order the call takes them, so the keyword spelling is the
2208    /// list spelling with `PLACING`, `FROM` and `FOR` where the commas would be:
2209    /// `overlay('abcdef' PLACING 'X' FROM 2 FOR 1)` is `"overlay"('abcdef', 'X', 2, 1)` upstream.
2210    fn overlay(&mut self, node: u32) -> Result<ExprRef> {
2211        let shape = self.first(self.first(node));
2212        if !matches!(self.name(shape), "OverlayParameters" | "OverlayExpressionList") {
2213            return self.unsupported(shape);
2214        }
2215        let mut args = Vec::new();
2216        for kid in self.kids(shape) {
2217            let kid = match self.name(kid) {
2218                "FromExpression" | "ForExpression" => self.first(kid),
2219                _ => kid,
2220            };
2221            args.push(self.expr(kid)?);
2222        }
2223        let args = self.expr_slice(args);
2224        let name = self.function_name("overlay");
2225        Ok(self.push(Expr::Function { name, args, distinct: false }))
2226    }
2227
2228    /// A number literal the query did not write, for the one place a lowering has to supply one.
2229    fn number(&mut self, text: &str) -> ExprRef {
2230        let text = self.intern(text);
2231        self.push(Expr::Literal { kind: LiteralKind::Number, text })
2232    }
2233
2234    /// `ExtractExpression <- 'EXTRACT' Parens(ExtractArguments)` and
2235    /// `ExtractArguments <- ExtractArgument 'FROM' Expression`.
2236    ///
2237    /// `EXTRACT` is not a function in the grammar because its argument list is not an argument
2238    /// list, and it is a function everywhere after here because DuckDB's parser does the same
2239    /// rewrite: `EXTRACT(minute FROM t)` is `date_part('minute', t)` and there is no separate
2240    /// implementation of one of them. The part is a keyword, an identifier or a string in the
2241    /// grammar, and all three become the string, which is why this is a rewrite and not a node.
2242    fn extract(&mut self, node: u32) -> Result<ExprRef> {
2243        let arguments = self.find(node, "ExtractArguments");
2244        if arguments == NONE {
2245            return self.unsupported(node);
2246        }
2247        let argument = self.first(self.first(arguments));
2248        let part = match self.name(argument) {
2249            "ExtractStringArgument" => self.string_value(argument)?,
2250            // A keyword, which is one of the thirteen the grammar names and is written back as the
2251            // one spelling that keyword has. `EXTRACT(seconds FROM t)` and `EXTRACT(SECOND FROM t)`
2252            // are both `date_part('SECOND', t)`, which was measured, and it shows up in the column
2253            // name as well as in the deparse, since an unaliased column is named after the call.
2254            "ExtractDatePartArgument" => date_part(self.text(argument)),
2255            // An identifier, taken as written. Which specifier names are legal is not a question
2256            // about syntax, so the answer to it lives with the function.
2257            "ExtractIdentifierArgument" => self.text(argument).to_string(),
2258            _ => return self.unsupported(argument),
2259        };
2260        let text = self.intern(&part);
2261        let part = self.push(Expr::Literal { kind: LiteralKind::String, text });
2262        let operand = self.expr(self.nth(arguments, 1))?;
2263        let name = self.function_name("date_part");
2264        let args = self.expr_slice(vec![part, operand]);
2265        Ok(self.push(Expr::Function { name, args, distinct: false }))
2266    }
2267
2268    /// `FunctionArgument <- NamedFunctionArgument / PositionalFunctionArgument`.
2269    fn argument(&mut self, node: u32) -> Result<ExprRef> {
2270        let inner = self.first(node);
2271        match self.name(inner) {
2272            "PositionalFunctionArgument" => self.expr(self.first(inner)),
2273            _ => self.unsupported(inner),
2274        }
2275    }
2276
2277    /// One argument of a table function, which is the same rule plus the names.
2278    ///
2279    /// `NamedParameter <- TypeFuncName Type? NamedParameterAssignment Expression` and
2280    /// `NamedParameterAssignment <- ':=' / '=>'`, so those two spellings are what the grammar has.
2281    /// The binary accepts a third, `name = value`, which the grammar has no rule for because it
2282    /// parses as an equality and is picked apart afterwards. That is what happens here too: a
2283    /// positional argument that is a comparison between a bare name and something else is a named
2284    /// parameter, which is the reading upstream's own transformer gives it. `read_parquet(f,
2285    /// binary_as_string=True)` is the query that matters and it is the spelling the ClickBench
2286    /// entry uses.
2287    ///
2288    /// The name is not resolved here and neither is the value. Which parameters a function takes
2289    /// is the binder's question, and so is whether `binary_as_string=True` means anything to the
2290    /// function it was written on.
2291    fn table_argument(&mut self, node: u32) -> Result<Target> {
2292        let inner = self.first(node);
2293        if self.name(inner) == "NamedFunctionArgument" {
2294            let named = self.first(inner);
2295            if self.count(named) != 3 {
2296                // The optional `Type` between the name and the assignment, which is a macro
2297                // parameter's declaration and not a call.
2298                return self.unsupported(named);
2299            }
2300            let alias = self.identifier(self.first(named));
2301            let expr = self.expr(self.nth(named, 2))?;
2302            return Ok(Target { expr, alias });
2303        }
2304        let expr = self.expr(self.first(inner))?;
2305        if let Expr::Binary { op: BinaryOp::Eq, left, right } = self.ast.expr(expr) {
2306            if let Expr::Column { name } = self.ast.expr(left) {
2307                if name.len == 1 {
2308                    let alias = self.ast.parts[name.start as usize];
2309                    return Ok(Target { expr: right, alias });
2310                }
2311            }
2312        }
2313        Ok(Target { expr, alias: NONE })
2314    }
2315
2316    /// `CastExpression <- CastOrTryCast Parens(CastArguments)`.
2317    fn cast(&mut self, node: u32) -> Result<ExprRef> {
2318        let try_cast = self.name(self.first(self.first(node))) == "TryCastKeyword";
2319        // `CastArguments <- Expression 'AS' Type`.
2320        let arguments = self.nth(node, 1);
2321        let operand = self.expr(self.first(arguments))?;
2322        let text = self.text(self.nth(arguments, 1)).to_string();
2323        let ty = self.intern(&text);
2324        Ok(self.push(Expr::Cast { operand, ty, try_cast }))
2325    }
2326
2327    /// `TypeLiteral <- Type StringLiteral`, which is the cast written the other way round.
2328    ///
2329    /// `DATE '1995-09-01'` and `CAST('1995-09-01' AS DATE)` are the same expression upstream, and
2330    /// the proof is the column name: the pinned binary answers both of them in a column called
2331    /// `CAST('1995-09-01' AS DATE)`. So this is the cast node and nothing else, which means every
2332    /// type the cast already takes is a typed literal for free and the two can never drift.
2333    ///
2334    /// The string is the literal the grammar matched rather than any expression, so there is no
2335    /// constant folding question here. `DATE x` does not parse in the first place.
2336    fn typed_literal(&mut self, node: u32) -> Result<ExprRef> {
2337        let text = self.text(self.first(node)).to_string();
2338        let ty = self.intern(&text);
2339        let operand = self.expr(self.nth(node, 1))?;
2340        Ok(self.push(Expr::Cast { operand, ty, try_cast: false }))
2341    }
2342
2343    /// `IntervalLiteral <- 'INTERVAL' IntervalParameter Interval?`, which is a function call.
2344    ///
2345    /// There is no interval node and there does not need to be one, because DuckDB's own
2346    /// transformer rewrites the literal into a call and the column name says so: `INTERVAL 1 DAY`
2347    /// comes back from the pinned binary in a column called
2348    /// `to_days(CAST(trunc(CAST(1 AS DOUBLE)) AS INTEGER))`. So the literal and a handwritten
2349    /// `to_days(1)` are the same expression from here on and the two cannot drift apart.
2350    ///
2351    /// Every unit goes through a DOUBLE on the way in, which is what makes `INTERVAL 1.5 DAY` one
2352    /// day rather than a day and a half: the truncation is in the rewrite and not in the function.
2353    /// The two units that can carry a fraction skip the truncation and stay a DOUBLE all the way,
2354    /// so `INTERVAL 2.7 SECOND` really is two and seven tenths of a second.
2355    ///
2356    /// A literal with no unit is the cast written the other way round, so `INTERVAL '1 day'` is
2357    /// `CAST('1 day' AS INTERVAL)`. That arm also catches a word the grammar does not read as a
2358    /// unit, since `INTERVAL 1 d` parses as this rule with no `Interval` child and a column alias
2359    /// after it, which is why upstream answers it with a cast error about an INTEGER.
2360    fn interval_literal(&mut self, node: u32) -> Result<ExprRef> {
2361        let parameter = self.find(node, "IntervalParameter");
2362        if parameter == NONE {
2363            return self.unsupported(node);
2364        }
2365        let operand = self.expr(self.first(parameter))?;
2366        let unit = self.find(node, "Interval");
2367        if unit == NONE {
2368            let ty = self.intern("INTERVAL");
2369            return Ok(self.push(Expr::Cast { operand, ty, try_cast: false }));
2370        }
2371        let spelling = self.name(self.first(unit));
2372        // The seven range forms parse and then refuse, in upstream's words, with the unit names
2373        // spelled the canonical way rather than the way they were written: `interval 1 days to
2374        // hours` is `DAY TO HOUR` there as well.
2375        if spelling == "IntervalToInterval" {
2376            let pair = self.name(self.first(self.first(unit)));
2377            return Err(Error::parser(format!("{} is not supported", worded(pair))));
2378        }
2379        let Some(&(_, function, width)) = UNITS.iter().find(|(rule, _, _)| *rule == spelling)
2380        else {
2381            return self.unsupported(unit);
2382        };
2383        let double = self.intern("DOUBLE");
2384        let mut count = self.push(Expr::Cast { operand, ty: double, try_cast: false });
2385        if let Some(width) = width {
2386            let name = self.function_name("trunc");
2387            let args = self.expr_slice(vec![count]);
2388            let whole = self.push(Expr::Function { name, args, distinct: false });
2389            let ty = self.intern(width);
2390            count = self.push(Expr::Cast { operand: whole, ty, try_cast: false });
2391        }
2392        let name = self.function_name(function);
2393        let args = self.expr_slice(vec![count]);
2394        Ok(self.push(Expr::Function { name, args, distinct: false }))
2395    }
2396
2397    /// `CaseExpression <- 'CASE' Expression? CaseWhenThen+ CaseElse? 'END'`.
2398    fn case(&mut self, node: u32) -> Result<ExprRef> {
2399        let mut operand = NONE;
2400        let mut arms = Vec::new();
2401        let mut otherwise = NONE;
2402        for kid in self.kids(node) {
2403            match self.name(kid) {
2404                // `CaseWhenThen <- 'WHEN' Expression 'THEN' Expression`.
2405                "CaseWhenThen" => {
2406                    let when = self.expr(self.first(kid))?;
2407                    let then = self.expr(self.nth(kid, 1))?;
2408                    arms.push(CaseArm { when, then });
2409                }
2410                // `CaseElse <- 'ELSE' Expression`.
2411                "CaseElse" => otherwise = self.expr(self.first(kid))?,
2412                // The bare `Expression` before the first `WHEN`, which makes it a simple case.
2413                _ => operand = self.expr(kid)?,
2414            }
2415        }
2416        let start = self.ast.case_arms.len() as u32;
2417        self.ast.case_arms.extend(arms);
2418        let arms = Slice { start, len: self.ast.case_arms.len() as u32 - start };
2419        Ok(self.push(Expr::Case { operand, arms, otherwise }))
2420    }
2421
2422    /// `ParenthesisExpression <- Parens(List(Expression)?)`, which is a row value.
2423    ///
2424    /// One item is not a row. `(a)` is `a` in every dialect and reading it as a one column row
2425    /// would change what `(a) = (b)` means.
2426    fn row(&mut self, node: u32) -> Result<ExprRef> {
2427        let mut items = Vec::new();
2428        for kid in self.kids(node) {
2429            items.push(self.expr(kid)?);
2430        }
2431        if items.len() == 1 {
2432            return Ok(items[0]);
2433        }
2434        let items = self.expr_slice(items);
2435        Ok(self.push(Expr::Row { items }))
2436    }
2437
2438    /// `Parameter <- '?' Number / '?' / '$' Number / '$' ColLabel`, a prepared statement parameter.
2439    ///
2440    /// The identifier is what follows the marker, so `?1` and `$1` are both the parameter named 1,
2441    /// and a bare `?` takes the next number by where it was written. That is what DuckDB does, which
2442    /// is why `? + $2` prints as `$1 + $2`: the counting is its own and does not skip a number
2443    /// because a later parameter claimed it.
2444    fn parameter(&mut self, node: u32) -> Result<ExprRef> {
2445        let written = self.text(node).trim();
2446        let written = written.trim_start_matches(['?', '$']).trim();
2447        let name = if written.is_empty() {
2448            self.anonymous += 1;
2449            self.anonymous.to_string()
2450        } else {
2451            written.to_string()
2452        };
2453        let name = self.intern(&name);
2454        Ok(self.push(Expr::Parameter { name }))
2455    }
2456
2457    /// `BoundedListExpression <- '[' List(Expression)? ']'`, which is a LIST value.
2458    ///
2459    /// One item is a list of one here, unlike the parenthesised form, because the brackets are what
2460    /// say list and there is nothing else `[a]` could mean.
2461    fn list(&mut self, node: u32) -> Result<ExprRef> {
2462        let mut items = Vec::new();
2463        for kid in self.kids(node) {
2464            items.push(self.expr(kid)?);
2465        }
2466        let items = self.expr_slice(items);
2467        Ok(self.push(Expr::List { items }))
2468    }
2469
2470    /// `SubqueryExpression <- SubqueryNot? SubqueryExists? SubqueryReference`.
2471    fn subquery(&mut self, node: u32) -> Result<ExprRef> {
2472        let negated = self.find(node, "SubqueryNot") != NONE;
2473        let exists = self.find(node, "SubqueryExists") != NONE;
2474        let reference = self.find(node, "SubqueryReference");
2475        let query = self.query(self.first(reference))?;
2476        Ok(if exists {
2477            self.push(Expr::Exists { query, negated })
2478        } else if negated {
2479            return self.unsupported(node);
2480        } else {
2481            self.push(Expr::Subquery { query })
2482        })
2483    }
2484
2485    /// The value of a string literal, with the quotes gone and the escapes resolved.
2486    ///
2487    /// A literal can be several tokens. `'a' 'b'` on two lines is one literal that is `ab`, which is
2488    /// the SQL standard's rule and DuckDB's, so the node is decoded token by token rather than by
2489    /// taking its text and stripping the outside.
2490    fn string_value(&self, node: u32) -> Result<String> {
2491        let span = self.tree.node(node);
2492        let mut value = String::new();
2493        for token in &self.tokens[span.start as usize..span.end as usize] {
2494            if token.kind == Kind::String {
2495                value.push_str(&string_token(token.text(self.query))?);
2496            }
2497        }
2498        Ok(value)
2499    }
2500
2501    /// The token that opens a string literal, which is the whole of it when it has a prefix.
2502    ///
2503    /// Only the first token is asked, because a prefixed literal is one token: `E'a' 'b'` is a
2504    /// syntax error upstream rather than a concatenation, so there is no second prefix to disagree
2505    /// with this one.
2506    fn first_string(&self, node: u32) -> &'a str {
2507        let span = self.tree.node(node);
2508        self.tokens[span.start as usize..span.end as usize]
2509            .iter()
2510            .find(|token| token.kind == Kind::String)
2511            .map_or("", |token| token.text(self.query))
2512    }
2513
2514    /// A string literal as an expression, which is the value plus what the prefix makes of it.
2515    ///
2516    /// `N'abc'` is a cast of the string to VARCHAR upstream and not a plain string, and the column
2517    /// name is the proof: the pinned binary answers it in a column called `CAST('abc' AS VARCHAR)`.
2518    /// So it is written here as the cast it is, and then there is nothing left to keep in step.
2519    ///
2520    /// `x'4142'` is not a string at all, it is a BLOB, so it is the one prefix that becomes a
2521    /// different kind of literal rather than a string with something done to it.
2522    fn string_literal(&mut self, node: u32) -> Result<ExprRef> {
2523        let token = self.first_string(node);
2524        let prefix = match token.as_bytes() {
2525            [prefix, b'\'', ..] => *prefix,
2526            _ => 0,
2527        };
2528        if matches!(prefix, b'X' | b'x') {
2529            if let Some(body) = token.get(1..).and_then(quoted_body) {
2530                let text = blob_text(body.as_bytes())?;
2531                let text = self.intern(&text);
2532                return Ok(self.push(Expr::Literal { kind: LiteralKind::Blob, text }));
2533            }
2534        }
2535        let value = self.string_value(node)?;
2536        let text = self.intern(&value);
2537        let literal = self.push(Expr::Literal { kind: LiteralKind::String, text });
2538        if matches!(prefix, b'N' | b'n') {
2539            let ty = self.intern("VARCHAR");
2540            return Ok(self.push(Expr::Cast { operand: literal, ty, try_cast: false }));
2541        }
2542        Ok(literal)
2543    }
2544}
2545
2546/// Each unit an interval literal can be written in, as the grammar rule that spells it, the
2547/// function it becomes, and the width the count is truncated to on the way there.
2548///
2549/// A width of `None` is the pair that keeps what is after the point. Those two stay a DOUBLE and
2550/// never see `trunc`, which is the whole of the difference between `INTERVAL 2.7 SECOND` being two
2551/// and seven tenths of a second and `INTERVAL 1.5 DAY` being one day. Every entry, both spellings
2552/// of every keyword and the width of each one was read off the pinned binary's column names.
2553const UNITS: &[(&str, &str, Option<&str>)] = &[
2554    ("YearKeyword", "to_years", Some("INTEGER")),
2555    ("MonthKeyword", "to_months", Some("INTEGER")),
2556    ("QuarterKeyword", "to_quarters", Some("INTEGER")),
2557    ("DecadeKeyword", "to_decades", Some("INTEGER")),
2558    ("CenturyKeyword", "to_centuries", Some("INTEGER")),
2559    ("MillenniumKeyword", "to_millennia", Some("INTEGER")),
2560    ("DayKeyword", "to_days", Some("INTEGER")),
2561    ("WeekKeyword", "to_weeks", Some("INTEGER")),
2562    ("HourKeyword", "to_hours", Some("BIGINT")),
2563    ("MinuteKeyword", "to_minutes", Some("BIGINT")),
2564    ("MicrosecondKeyword", "to_microseconds", Some("BIGINT")),
2565    ("SecondKeyword", "to_seconds", None),
2566    ("MillisecondKeyword", "to_milliseconds", None),
2567];
2568
2569/// The one spelling a date part keyword is written back as, which is not always the singular.
2570///
2571/// Both spellings of each of the thirteen keywords land on one name, and the name is upper case and
2572/// is plural for the two smallest parts and singular for the rest. That is not a rule, it is a list,
2573/// and it was read off the pinned binary a keyword at a time: `EXTRACT(milliseconds FROM t)` and
2574/// `EXTRACT(millisecond FROM t)` are both `date_part('MILLISECONDS', t)` while `EXTRACT(seconds FROM
2575/// t)` is `date_part('SECOND', t)`.
2576///
2577/// A word that is not a keyword never reaches here, because the grammar tells the two apart, and it
2578/// keeps whatever case it was written in. `EXTRACT(epoch FROM t)` stays lower case, measured.
2579fn date_part(written: &str) -> String {
2580    const PARTS: &[(&str, &str)] = &[
2581        ("YEAR", "YEAR"),
2582        ("YEARS", "YEAR"),
2583        ("MONTH", "MONTH"),
2584        ("MONTHS", "MONTH"),
2585        ("DAY", "DAY"),
2586        ("DAYS", "DAY"),
2587        ("HOUR", "HOUR"),
2588        ("HOURS", "HOUR"),
2589        ("MINUTE", "MINUTE"),
2590        ("MINUTES", "MINUTE"),
2591        ("SECOND", "SECOND"),
2592        ("SECONDS", "SECOND"),
2593        ("MILLISECOND", "MILLISECONDS"),
2594        ("MILLISECONDS", "MILLISECONDS"),
2595        ("MICROSECOND", "MICROSECONDS"),
2596        ("MICROSECONDS", "MICROSECONDS"),
2597        ("WEEK", "WEEK"),
2598        ("WEEKS", "WEEK"),
2599        ("QUARTER", "QUARTER"),
2600        ("QUARTERS", "QUARTER"),
2601        ("DECADE", "DECADE"),
2602        ("DECADES", "DECADE"),
2603        ("CENTURY", "CENTURY"),
2604        ("CENTURIES", "CENTURY"),
2605        ("MILLENNIUM", "MILLENNIUM"),
2606        ("MILLENNIA", "MILLENNIUM"),
2607    ];
2608    PARTS
2609        .iter()
2610        .find(|(spelling, _)| spelling.eq_ignore_ascii_case(written))
2611        .map_or_else(|| written.to_string(), |(_, name)| (*name).to_string())
2612}
2613
2614/// A grammar rule name like `DayToHour` as the words upstream puts in the message for it.
2615fn worded(rule: &str) -> String {
2616    let mut out = String::new();
2617    for character in rule.chars() {
2618        if character.is_ascii_uppercase() && !out.is_empty() {
2619            out.push(' ');
2620        }
2621        out.push(character.to_ascii_uppercase());
2622    }
2623    out
2624}
2625
2626/// The value of one string token, with the quotes gone and whatever the prefix means resolved.
2627///
2628/// There is no fall through that keeps the source text. That arm is what answered `SELECT E'a'`
2629/// with the four characters `E'a'`, and a default that silently answers with the query is a default
2630/// that will do this again with the next spelling somebody adds, so a spelling this does not know
2631/// raises instead. Per #329.
2632fn string_token(text: &str) -> Result<String> {
2633    if let Some(body) = dollar_body(text) {
2634        return Ok(body.to_string());
2635    }
2636    if let Some(body) = quoted_body(text) {
2637        return Ok(body.replace("''", "'"));
2638    }
2639    let Some(body) = text.get(1..).and_then(quoted_body) else {
2640        return Ok(text.to_string());
2641    };
2642    match text.as_bytes()[0] {
2643        b'E' | b'e' => escaped(body),
2644        // `N'abc'` is the string and nothing else. The cast that makes the name is put on outside.
2645        b'N' | b'n' => Ok(body.replace("''", "'")),
2646        // Not a bit string, whatever the spelling suggests. Upstream answers `B'101'` with the four
2647        // characters `b101` as a VARCHAR, and `B''` with the one character `b`, which is measured
2648        // and not guessed. Nothing else is done with the body.
2649        b'B' | b'b' => Ok(format!("b{}", body.replace("''", "'"))),
2650        // `x'41'` is a BLOB and a BLOB is not a string, so the places that want a string out of a
2651        // literal, which are DESCRIBE and the part in EXTRACT, do not get one from this spelling.
2652        _ => Err(Error::not_implemented(format!("the string literal {text} is not supported yet"))),
2653    }
2654}
2655
2656/// The text a blob literal's body means, which is the text a blob prints as.
2657///
2658/// `x'4142'` is two bytes and the pinned binary calls the column `'AB'::BLOB`, so what is kept here
2659/// is the printed form and not the source. The cast that reads it back gives the bytes again, which
2660/// is what makes one text enough for both the value and the name, and it is `Value` that prints it
2661/// so the two spellings of a blob cannot drift apart.
2662///
2663/// Upstream writes `\xHH` for every pair without looking at the digits and lets the cast refuse the
2664/// ones that are not hex, which is why `x'4'` is a parser error and `x'zz'` is a conversion error
2665/// one step later. Doing the same thing gives both messages in the same words. The pairs are bytes
2666/// and not characters: `x'éé'` is four bytes and so two pairs, which is how upstream counts them.
2667fn blob_text(body: &[u8]) -> Result<String> {
2668    if body.len() % 2 != 0 {
2669        return Err(Error::parser("Hex string literal must have an even number of hex digits"));
2670    }
2671    let digit = |byte: u8| (byte as char).to_digit(16).map(|digit| digit as u8);
2672    let bytes: Option<Vec<u8>> =
2673        body.chunks(2).map(|pair| Some(digit(pair[0])? * 16 + digit(pair[1])?)).collect();
2674    match bytes {
2675        Some(bytes) => Ok(Value::Blob(bytes).to_string()),
2676        None => {
2677            Ok(body.chunks(2).map(|pair| format!("\\x{}", String::from_utf8_lossy(pair))).collect())
2678        }
2679    }
2680}
2681
2682/// The body of a single quoted string, for the tokens that are one.
2683///
2684/// An unterminated token has nothing to take off the end and keeps every byte it was given, which
2685/// is why the closing quote has to be a quote that is not also the opening one.
2686fn quoted_body(text: &str) -> Option<&str> {
2687    text.strip_prefix('\'').filter(|rest| !rest.is_empty()).and_then(|rest| rest.strip_suffix('\''))
2688}
2689
2690/// The body of an `E'...'` literal, with the C style escapes resolved.
2691///
2692/// Every rule here was read off the pinned binary one at a time. The named escapes are `\n`, `\t`,
2693/// `\r`, `\b` and `\f`, and `\v` is not one of them. `\x` takes one or two hex digits and `\0`
2694/// through `\7` take one to three octal digits, both of which write a byte and not a character, so
2695/// `\xc3\xa9` is one `é` and `\377` is not a string at all. `\uHHHH` takes exactly four hex digits
2696/// and writes the character they name. Anything else, including a `\u` that is short or names a
2697/// surrogate half or a NUL, drops the backslash and keeps the character, so `\q` is `q` and `\u41`
2698/// is `u41`.
2699///
2700/// The result is bytes until the end because the escapes write bytes, and the two ways of writing
2701/// something that is not a string both raise the way upstream raises them.
2702fn escaped(body: &str) -> Result<String> {
2703    let bytes = body.as_bytes();
2704    let mut out = Vec::with_capacity(bytes.len());
2705    let mut at = 0;
2706    while at < bytes.len() {
2707        let byte = bytes[at];
2708        at += 1;
2709        if byte == b'\'' && bytes.get(at) == Some(&b'\'') {
2710            out.push(b'\'');
2711            at += 1;
2712            continue;
2713        }
2714        if byte != b'\\' || at == bytes.len() {
2715            out.push(byte);
2716            continue;
2717        }
2718        let escape = bytes[at];
2719        at += 1;
2720        match escape {
2721            b'n' => out.push(b'\n'),
2722            b't' => out.push(b'\t'),
2723            b'r' => out.push(b'\r'),
2724            b'b' => out.push(0x08),
2725            b'f' => out.push(0x0c),
2726            b'x' => match digits(bytes, &mut at, 16, 2) {
2727                Some(value) => out.push(value as u8),
2728                None => out.push(b'x'),
2729            },
2730            b'0'..=b'7' => {
2731                at -= 1;
2732                let value = digits(bytes, &mut at, 8, 3).unwrap_or(0);
2733                out.push(value as u8);
2734            }
2735            b'u' => match four_hex(bytes, at).and_then(char::from_u32).filter(|c| *c != '\0') {
2736                Some(c) => {
2737                    at += 4;
2738                    out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
2739                }
2740                None => out.push(b'u'),
2741            },
2742            other => out.push(other),
2743        }
2744    }
2745    if out.contains(&0) {
2746        return Err(Error::parser("Null character not permitted in escape string literal"));
2747    }
2748    String::from_utf8(out).map_err(|error| {
2749        Error::parser(format!(
2750            "Invalid UTF-8 in escape string literal at byte offset {}: byte mismatch",
2751            error.utf8_error().valid_up_to()
2752        ))
2753    })
2754}
2755
2756/// Up to `most` digits in `radix` starting at `at`, moving `at` past the ones that were taken.
2757///
2758/// `None` means there were none at all, which is the case where the escape was not an escape:
2759/// `\x` on its own is the letter `x` upstream and not a zero byte.
2760fn digits(bytes: &[u8], at: &mut usize, radix: u32, most: usize) -> Option<u32> {
2761    let mut value = None;
2762    for _ in 0..most {
2763        let Some(digit) = bytes.get(*at).and_then(|byte| (*byte as char).to_digit(radix)) else {
2764            break;
2765        };
2766        value = Some(value.unwrap_or(0) * radix + digit);
2767        *at += 1;
2768    }
2769    value
2770}
2771
2772/// The four hex digits of a `\uHHHH`, which has to be all four of them or it is not one.
2773///
2774/// Nothing is consumed here, because the digits are only digits if the whole escape works out. A
2775/// surrogate half is not a character and upstream does not pair it up either, so `😀` is
2776/// the ten characters it was written as, which is what the caller falls back to.
2777fn four_hex(bytes: &[u8], at: usize) -> Option<u32> {
2778    let digits = bytes.get(at..at + 4)?;
2779    if !digits.iter().all(u8::is_ascii_hexdigit) {
2780        return None;
2781    }
2782    u32::from_str_radix(std::str::from_utf8(digits).ok()?, 16).ok()
2783}
2784
2785/// The body of a dollar quoted string, for the tokens that are one.
2786///
2787/// The tag is whatever sits between the opening pair of dollars and may be empty, so `$$a$$` and
2788/// `$tag$a$tag$` both arrive here, and nothing inside the body is escaped, which is the whole reason
2789/// the spelling exists. The tokenizer has already found the closing tag, which is the part that takes
2790/// work, so this says where the body starts and ends and no more. A token that is not dollar quoted
2791/// gives `None` and so does an unterminated one, which has no closing tag to take off and keeps every
2792/// byte it was given, the way the matcher already treats it. Per #276.
2793fn dollar_body(text: &str) -> Option<&str> {
2794    let rest = text.strip_prefix('$')?;
2795    let close = rest.find('$')?;
2796    let (tag, body) = (&rest[..close], &rest[close + 1..]);
2797    body.strip_suffix(&format!("${tag}$"))
2798}
2799
2800/// Strip the quoting off an identifier.
2801///
2802/// DuckDB does not fold identifier case at any point, quoted or not, so this only removes the
2803/// quotes and resolves the doubled ones. Anything else would be the parser deciding what a name is.
2804///
2805/// Single quotes are stripped too, and the only way one gets here is the file name in `FROM
2806/// 'hits.parquet'`, because the matcher takes a string for a name in that position and in `COPY t TO
2807/// '...'` and nowhere else. Leaving them on would make that name different from the one `FROM
2808/// "hits.parquet"` writes, and DuckDB reads both of those as the same file.
2809fn unquote(text: &str) -> String {
2810    if let Some(body) = text.strip_prefix('"').and_then(|rest| rest.strip_suffix('"')) {
2811        return body.replace("\"\"", "\"");
2812    }
2813    match text.strip_prefix('\'').and_then(|rest| rest.strip_suffix('\'')) {
2814        Some(body) => body.replace("''", "'"),
2815        None => text.to_string(),
2816    }
2817}
2818
2819#[cfg(test)]
2820mod tests {
2821    use super::*;
2822    use crate::corpus::CORPUS;
2823    use crate::matcher::parse;
2824
2825    /// The AST written back out as text, which is what the assertions below read.
2826    ///
2827    /// Not a SQL printer and not trying to be. It is deliberately not valid SQL: operators are
2828    /// spelled with the name of the variant and every binary node is parenthesised, so that a test
2829    /// asserting on this text is asserting on the shape of the tree and not on a formatting choice.
2830    /// `a - b - c` and `a - (b - c)` have to look different here or the test that tells them apart
2831    /// is not a test.
2832    fn show(ast: &Ast, expr: ExprRef) -> String {
2833        if expr == NONE {
2834            return "-".to_string();
2835        }
2836        let list = |slice: Slice| {
2837            ast.expr_list(slice).iter().map(|&item| show(ast, item)).collect::<Vec<_>>().join(", ")
2838        };
2839        match ast.expr(expr) {
2840            Expr::Star { qualifier, replacements } => {
2841                let star = if qualifier.is_empty() {
2842                    "*".to_string()
2843                } else {
2844                    format!("{}.*", ast.name_text(qualifier))
2845                };
2846                if replacements.is_empty() {
2847                    return star;
2848                }
2849                let entries: Vec<String> = ast
2850                    .target_list(replacements)
2851                    .iter()
2852                    .map(|target| {
2853                        format!("{} AS {}", show(ast, target.expr), ast.string(target.alias))
2854                    })
2855                    .collect();
2856                format!("{star} REPLACE ({})", entries.join(", "))
2857            }
2858            Expr::Column { name } => ast.name_text(name),
2859            Expr::Literal { kind, text } => match kind {
2860                LiteralKind::Number => ast.string(text).to_string(),
2861                LiteralKind::String => format!("'{}'", ast.string(text)),
2862                LiteralKind::Blob => format!("'{}'::BLOB", ast.string(text)),
2863                other => format!("{other:?}").to_uppercase(),
2864            },
2865            Expr::Unary { op, operand } => format!("({op:?} {})", show(ast, operand)),
2866            Expr::Binary { op, left, right } => {
2867                let op = match op {
2868                    BinaryOp::Named(name) => ast.string(name).to_string(),
2869                    other => format!("{other:?}"),
2870                };
2871                format!("({} {op} {})", show(ast, left), show(ast, right))
2872            }
2873            Expr::Function { name, args, distinct } => {
2874                let distinct = if distinct { "DISTINCT " } else { "" };
2875                format!("{}({distinct}{})", ast.name_text(name), list(args))
2876            }
2877            Expr::Cast { operand, ty, try_cast } => {
2878                let word = if try_cast { "TRY_CAST" } else { "CAST" };
2879                format!("{word}({} AS {})", show(ast, operand), ast.string(ty))
2880            }
2881            Expr::Case { operand, arms, otherwise } => {
2882                let arms = ast
2883                    .arm_list(arms)
2884                    .iter()
2885                    .map(|arm| format!("WHEN {} THEN {}", show(ast, arm.when), show(ast, arm.then)))
2886                    .collect::<Vec<_>>()
2887                    .join(" ");
2888                format!("CASE {} {arms} ELSE {} END", show(ast, operand), show(ast, otherwise))
2889            }
2890            Expr::Between { operand, low, high, negated } => {
2891                let not = if negated { "NOT " } else { "" };
2892                format!(
2893                    "({not}{} BETWEEN {} AND {})",
2894                    show(ast, operand),
2895                    show(ast, low),
2896                    show(ast, high)
2897                )
2898            }
2899            Expr::In { operand, list: items, negated } => {
2900                let not = if negated { "NOT " } else { "" };
2901                format!("({not}{} IN [{}])", show(ast, operand), list(items))
2902            }
2903            Expr::List { items } => format!("[{}]", list(items)),
2904            Expr::Parameter { name } => format!("${}", ast.string(name)),
2905            Expr::Row { items } => format!("ROW({})", list(items)),
2906            Expr::Subquery { query } => format!("({})", show_query(ast, query)),
2907            Expr::Exists { query, negated } => {
2908                let exists = format!("EXISTS ({})", show_query(ast, query));
2909                if negated { format!("NOT {exists}") } else { exists }
2910            }
2911            Expr::InSubquery { operand, query, negated } => {
2912                let written = format!("{} IN ({})", show(ast, operand), show_query(ast, query));
2913                if negated { format!("NOT {written}") } else { written }
2914            }
2915            Expr::QuantifiedSubquery { operand, op, query, all } => {
2916                let quantifier = if all { "ALL" } else { "ANY" };
2917                format!("{} {op:?} {quantifier} ({})", show(ast, operand), show_query(ast, query))
2918            }
2919        }
2920    }
2921
2922    /// One from item written back out.
2923    fn show_source(ast: &Ast, source: SourceRef) -> String {
2924        let alias = |alias: StrRef| match alias {
2925            NONE => String::new(),
2926            other => format!(" AS {}", ast.string(other)),
2927        };
2928        match ast.source(source) {
2929            Source::Table { name, alias: name_alias, .. } => {
2930                format!("{}{}", ast.name_text(name), alias(name_alias))
2931            }
2932            Source::Function { name, args, alias: call_alias, .. } => {
2933                let args = ast
2934                    .target_list(args)
2935                    .iter()
2936                    .map(|item| match item.alias {
2937                        NONE => show(ast, item.expr),
2938                        named => format!("{} := {}", ast.string(named), show(ast, item.expr)),
2939                    })
2940                    .collect::<Vec<_>>()
2941                    .join(", ");
2942                format!("{}({args}){}", ast.name_text(name), alias(call_alias))
2943            }
2944            Source::Subquery { query, alias: query_alias, .. } => {
2945                format!("({}){}", show_query(ast, query), alias(query_alias))
2946            }
2947            Source::Values { rows, alias: values_alias, .. } => {
2948                format!("{}{}", show_rows(ast, rows), alias(values_alias))
2949            }
2950            Source::Join { left, right, kind, natural, on, using } => {
2951                let natural = if natural { "NATURAL " } else { "" };
2952                let on = if on == NONE { String::new() } else { format!(" ON {}", show(ast, on)) };
2953                let using = if using.is_empty() {
2954                    String::new()
2955                } else {
2956                    format!(" USING ({})", ast.name_text(using))
2957                };
2958                format!(
2959                    "({} {natural}{kind:?} JOIN {}{on}{using})",
2960                    show_source(ast, left),
2961                    show_source(ast, right)
2962                )
2963            }
2964        }
2965    }
2966
2967    /// The rows of a `VALUES` written back out.
2968    fn show_rows(ast: &Ast, rows: Slice) -> String {
2969        let rows = ast
2970            .rows(rows)
2971            .iter()
2972            .map(|&row| {
2973                let items = ast
2974                    .expr_list(row)
2975                    .iter()
2976                    .map(|&item| show(ast, item))
2977                    .collect::<Vec<_>>()
2978                    .join(", ");
2979                format!("({items})")
2980            })
2981            .collect::<Vec<_>>()
2982            .join(", ");
2983        format!("VALUES {rows}")
2984    }
2985
2986    /// One query written back out.
2987    fn show_query(ast: &Ast, index: QueryRef) -> String {
2988        let query = ast.query(index);
2989        let list = |slice: Slice| {
2990            ast.expr_list(slice).iter().map(|&item| show(ast, item)).collect::<Vec<_>>().join(", ")
2991        };
2992        let mut out = match query.body {
2993            QueryBody::SetOp { op, quantifier, by_name, left, right } => {
2994                let by_name = if by_name { " BY NAME" } else { "" };
2995                format!(
2996                    "({} {op:?} {quantifier:?}{by_name} {})",
2997                    show_query(ast, left),
2998                    show_query(ast, right)
2999                )
3000            }
3001            QueryBody::Select(index) => {
3002                let select = ast.select(index);
3003                let distinct = match select.distinct {
3004                    Distinct::No => String::new(),
3005                    Distinct::Yes => " DISTINCT".to_string(),
3006                    Distinct::On(on) => format!(" DISTINCT ON ({})", list(on)),
3007                };
3008                let targets = ast
3009                    .target_list(select.targets)
3010                    .iter()
3011                    .map(|target| match target.alias {
3012                        NONE => show(ast, target.expr),
3013                        alias => format!("{} AS {}", show(ast, target.expr), ast.string(alias)),
3014                    })
3015                    .collect::<Vec<_>>()
3016                    .join(", ");
3017                let mut out = format!("SELECT{distinct} {targets}");
3018                if !select.from.is_empty() {
3019                    let from = ast
3020                        .source_list(select.from)
3021                        .iter()
3022                        .map(|&source| show_source(ast, source))
3023                        .collect::<Vec<_>>()
3024                        .join(", ");
3025                    out += &format!(" FROM {from}");
3026                }
3027                if select.filter != NONE {
3028                    out += &format!(" WHERE {}", show(ast, select.filter));
3029                }
3030                if select.group_by_all {
3031                    out += " GROUP BY ALL";
3032                } else if !select.group_by.is_empty() {
3033                    out += &format!(" GROUP BY {}", list(select.group_by));
3034                }
3035                if select.having != NONE {
3036                    out += &format!(" HAVING {}", show(ast, select.having));
3037                }
3038                out
3039            }
3040            QueryBody::Values(rows) => show_rows(ast, rows),
3041            QueryBody::Describe(inner) => format!("DESCRIBE {}", show_query(ast, inner)),
3042            QueryBody::Show { name, .. } => format!("SHOW {}", ast.name_text(name)),
3043        };
3044        if query.order_by_all {
3045            out += " ORDER BY ALL";
3046        } else if !query.order_by.is_empty() {
3047            let items = ast
3048                .order_list(query.order_by)
3049                .iter()
3050                .map(|item| format!("{} {:?} {:?}", show(ast, item.expr), item.order, item.nulls))
3051                .collect::<Vec<_>>()
3052                .join(", ");
3053            out += &format!(" ORDER BY {items}");
3054        }
3055        if query.limit != NONE {
3056            let percent = if query.limit_percent { "%" } else { "" };
3057            out += &format!(" LIMIT {}{percent}", show(ast, query.limit));
3058        }
3059        if query.offset != NONE {
3060            out += &format!(" OFFSET {}", show(ast, query.offset));
3061        }
3062        out
3063    }
3064
3065    /// One statement, transformed and written back out.
3066    fn round(query: &str) -> String {
3067        let ast = parse_ast(query).unwrap_or_else(|error| panic!("{query}: {error}"));
3068        assert_eq!(ast.statements.len(), 1, "{query} is one statement");
3069        let Statement::Query(index) = ast.statements[0] else {
3070            panic!("{query} is not a query");
3071        };
3072        show_query(&ast, index)
3073    }
3074
3075    fn round_with_case(query: &str, case: IdentifierCase) -> String {
3076        let ast =
3077            parse_ast_with_case(query, case).unwrap_or_else(|error| panic!("{query}: {error}"));
3078        let Statement::Query(index) = ast.statements[0] else {
3079            panic!("{query} is not a query");
3080        };
3081        show_query(&ast, index)
3082    }
3083
3084    /// One statement, transformed and written back out as the DDL and DML shape it is.
3085    fn round_statement(query: &str) -> String {
3086        let ast = parse_ast(query).unwrap_or_else(|error| panic!("{query}: {error}"));
3087        assert_eq!(ast.statements.len(), 1, "{query} is one statement");
3088        match ast.statements[0] {
3089            Statement::Query(index) => show_query(&ast, index),
3090            Statement::CreateTable(index) => {
3091                let create = ast.create_table(index);
3092                let mut out = "CREATE".to_string();
3093                if create.or_replace {
3094                    out += " OR REPLACE";
3095                }
3096                if create.temporary {
3097                    out += " TEMPORARY";
3098                }
3099                out += " TABLE";
3100                if create.if_not_exists {
3101                    out += " IF NOT EXISTS";
3102                }
3103                out += &format!(" {}", ast.name_text(create.name));
3104                let columns = ast
3105                    .column_defs(create.columns)
3106                    .iter()
3107                    .map(|def| {
3108                        let ty = match def.ty {
3109                            NONE => String::new(),
3110                            other => format!(" {}", ast.string(other)),
3111                        };
3112                        let null = if def.not_null { " NOT NULL" } else { "" };
3113                        format!("{}{ty}{null}", ast.string(def.name))
3114                    })
3115                    .collect::<Vec<_>>()
3116                    .join(", ");
3117                if !columns.is_empty() || create.query == NONE {
3118                    out += &format!(" ({columns})");
3119                }
3120                if create.query != NONE {
3121                    out += &format!(" AS {}", show_query(&ast, create.query));
3122                }
3123                out
3124            }
3125            Statement::CreateView(index) => {
3126                let create = ast.create_view(index);
3127                let mut out = "CREATE".to_string();
3128                if create.or_replace {
3129                    out += " OR REPLACE";
3130                }
3131                if create.temporary {
3132                    out += " TEMPORARY";
3133                }
3134                out += " VIEW";
3135                if create.if_not_exists {
3136                    out += " IF NOT EXISTS";
3137                }
3138                out += &format!(" {}", ast.name_text(create.name));
3139                if !create.columns.is_empty() {
3140                    let columns = ast.name(create.columns).collect::<Vec<_>>().join(", ");
3141                    out += &format!(" ({columns})");
3142                }
3143                out + &format!(" AS {}", show_query(&ast, create.query))
3144            }
3145            Statement::DropTable(index) => {
3146                let drop = ast.drop_table(index);
3147                let mut out = if drop.view { "DROP VIEW" } else { "DROP TABLE" }.to_string();
3148                if drop.if_exists {
3149                    out += " IF EXISTS";
3150                }
3151                let names = ast
3152                    .name_list(drop.names)
3153                    .iter()
3154                    .map(|&name| ast.name_text(name))
3155                    .collect::<Vec<_>>()
3156                    .join(", ");
3157                out + &format!(" {names}")
3158            }
3159            Statement::Insert(index) => {
3160                let insert = ast.insert(index);
3161                let mut out = format!("INSERT INTO {}", ast.name_text(insert.name));
3162                if !insert.columns.is_empty() {
3163                    let columns = ast.name(insert.columns).collect::<Vec<_>>().join(", ");
3164                    out += &format!(" ({columns})");
3165                }
3166                out + &format!(" {}", show_query(&ast, insert.source))
3167            }
3168            Statement::Set(index) => {
3169                let setting = ast.setting(index);
3170                let scope = match setting.scope.keyword() {
3171                    "" => String::new(),
3172                    word => format!(" {word}"),
3173                };
3174                format!("SET{scope} {} = {}", ast.string(setting.name), show(&ast, setting.value))
3175            }
3176            Statement::Reset(index) => {
3177                let setting = ast.setting(index);
3178                let scope = match setting.scope.keyword() {
3179                    "" => String::new(),
3180                    word => format!(" {word}"),
3181                };
3182                format!("RESET{scope} {}", ast.string(setting.name))
3183            }
3184            Statement::Checkpoint => "CHECKPOINT".to_string(),
3185            Statement::Explain { query, analyze } => {
3186                let analyze = if analyze { "ANALYZE " } else { "" };
3187                format!("EXPLAIN {analyze}{}", show_query(&ast, query))
3188            }
3189        }
3190    }
3191
3192    #[test]
3193    fn an_explain_keeps_the_query_it_was_asked_about() {
3194        assert_eq!(
3195            round_statement("EXPLAIN SELECT a FROM t WHERE a > 1"),
3196            "EXPLAIN SELECT a FROM t WHERE (a Gt 1)"
3197        );
3198        assert_eq!(round_statement("explain select 1"), "EXPLAIN SELECT 1");
3199        assert_eq!(round_statement("explain analyze select 1"), "EXPLAIN ANALYZE SELECT 1");
3200    }
3201
3202    #[test]
3203    fn the_parts_of_an_explain_that_are_not_the_query_are_refused_by_name() {
3204        // An option list that chooses a format is a promise about the output this does not keep,
3205        // and a statement that is not a query has no plan to show.
3206        for (query, named) in [
3207            ("EXPLAIN (FORMAT JSON) SELECT 1", "ExplainOptionList"),
3208            ("EXPLAIN INSERT INTO t VALUES (1)", "InsertStatement"),
3209            ("EXPLAIN CREATE TABLE u (a INTEGER)", "CreateStatement"),
3210        ] {
3211            let error = parse_ast(query).expect_err(query).to_string();
3212            assert!(error.contains(named), "{query}: {error}");
3213        }
3214    }
3215
3216    #[test]
3217    fn a_set_keeps_its_name_its_scope_and_its_value() {
3218        assert_eq!(round_statement("SET memory_limit = '1GB'"), "SET memory_limit = '1GB'");
3219        assert_eq!(round_statement("set threads=4"), "SET threads = 4");
3220        assert_eq!(round_statement("SET GLOBAL threads = 4"), "SET GLOBAL threads = 4");
3221        assert_eq!(round_statement("SET SESSION threads = 4"), "SET SESSION threads = 4");
3222        assert_eq!(round_statement("SET LOCAL threads = 4"), "SET LOCAL threads = 4");
3223        assert_eq!(round_statement("RESET memory_limit"), "RESET memory_limit");
3224        assert_eq!(round_statement("RESET GLOBAL memory_limit"), "RESET GLOBAL memory_limit");
3225        assert_eq!(
3226            round_statement("SET TIME ZONE 'Asia/Kathmandu'"),
3227            "SET TimeZone = 'Asia/Kathmandu'"
3228        );
3229        assert_eq!(round_statement("SET TIME ZONE UTC"), "SET TimeZone = 'UTC'");
3230        assert_eq!(round_statement("SET TIME ZONE DEFAULT"), "RESET TimeZone");
3231        assert_eq!(round_statement("SET TIME ZONE LOCAL"), "RESET TimeZone");
3232    }
3233
3234    #[test]
3235    fn the_two_other_things_the_word_set_starts_are_refused_rather_than_read_as_settings() {
3236        // `SET VARIABLE x = 1` declares a session variable and `SET SCHEMA` picks where an
3237        // unqualified name is looked up. Neither is a knob on the engine and reading either as one
3238        // would change an answer quietly.
3239        for statement in ["SET VARIABLE x = 1", "SET SCHEMA 'main'"] {
3240            let error = parse_ast(statement).expect_err(statement);
3241            assert_eq!(error.code().duckdb_name(), "Not implemented Error", "{statement}");
3242        }
3243    }
3244
3245    #[test]
3246    fn a_setting_written_with_a_list_of_values_is_refused_rather_than_taking_the_first() {
3247        let error = parse_ast("SET search_path = a, b").expect_err("a list of two");
3248        assert_eq!(error.code().duckdb_name(), "Not implemented Error");
3249    }
3250
3251    #[test]
3252    fn the_query_m0_has_to_run_transforms() {
3253        assert_eq!(round("SELECT * FROM t WHERE x > 5"), "SELECT * FROM t WHERE (x Gt 5)");
3254    }
3255
3256    #[test]
3257    fn a_replace_list_rides_on_the_star_it_changes() {
3258        // The parentheses are optional around a single entry, which is how the clickbench load
3259        // recipe is not written but is how a lot of hand written sql is.
3260        assert_eq!(
3261            round("SELECT * REPLACE (a + 1 AS a) FROM t"),
3262            "SELECT * REPLACE ((a Add 1) AS a) FROM t"
3263        );
3264        assert_eq!(
3265            round("SELECT * REPLACE a + 1 AS a FROM t"),
3266            "SELECT * REPLACE ((a Add 1) AS a) FROM t"
3267        );
3268        assert_eq!(
3269            round("SELECT t.* REPLACE (make_date(a) AS a, b * 2 AS b) FROM t"),
3270            "SELECT t.* REPLACE (make_date(a) AS a, (b Multiply 2) AS b) FROM t"
3271        );
3272    }
3273
3274    #[test]
3275    fn one_column_cannot_be_replaced_twice() {
3276        // Caught here rather than in the binder because it is a mistake in what was written and
3277        // not a mistake about what is in the table, and duckdb reports it the same way.
3278        let error = parse_ast("SELECT * REPLACE (a + 1 AS a, a + 2 AS A) FROM t").unwrap_err();
3279        assert_eq!(error.to_string(), "Parser Error: Duplicate entry \"A\" in REPLACE list");
3280    }
3281
3282    #[test]
3283    fn a_table_function_argument_can_have_a_name_written_in_front_of_it() {
3284        // The grammar has `:=` and `=>`. It does not have `=`, which parses as a comparison and is
3285        // read back apart here, and that is the spelling the clickbench load recipe uses.
3286        for spelling in
3287            ["binary_as_string := True", "binary_as_string => True", "binary_as_string = True"]
3288        {
3289            assert_eq!(
3290                round(&format!("SELECT * FROM read_parquet('f.parquet', {spelling})")),
3291                "SELECT * FROM read_parquet('f.parquet', binary_as_string := TRUE)",
3292                "{spelling}"
3293            );
3294        }
3295    }
3296
3297    #[test]
3298    fn an_equality_that_is_not_a_bare_name_stays_an_argument() {
3299        // A qualified name on the left is not a parameter name, and neither is anything that is
3300        // not a name at all, so both of those stay the comparison they were written as.
3301        assert_eq!(round("SELECT * FROM f(t.a = 1)"), "SELECT * FROM f((t.a Eq 1))");
3302        assert_eq!(round("SELECT * FROM f(1 = 1)"), "SELECT * FROM f((1 Eq 1))");
3303    }
3304
3305    #[test]
3306    fn a_create_table_keeps_its_types_as_text() {
3307        assert_eq!(
3308            round_statement("CREATE TABLE t (a INTEGER, b VARCHAR NOT NULL)"),
3309            "CREATE TABLE t (a INTEGER, b VARCHAR NOT NULL)"
3310        );
3311        // The type is the text between the identifier and whatever follows it, parentheses and
3312        // all, because resolving `DECIMAL(18, 3)` into a width and a scale is the binder's job and
3313        // doing it here would mean two places that know the type table.
3314        assert_eq!(
3315            round_statement("CREATE TABLE t (a DECIMAL(18, 3), b STRUCT(x INT))"),
3316            "CREATE TABLE t (a DECIMAL(18, 3), b STRUCT(x INT))"
3317        );
3318    }
3319
3320    #[test]
3321    fn the_modifiers_on_a_create_table_survive() {
3322        assert_eq!(
3323            round_statement("CREATE OR REPLACE TEMPORARY TABLE s.t (a INT)"),
3324            "CREATE OR REPLACE TEMPORARY TABLE s.t (a INT)"
3325        );
3326        assert_eq!(
3327            round_statement("CREATE TEMPORARY TABLE IF NOT EXISTS s.t (a INT)"),
3328            "CREATE TEMPORARY TABLE IF NOT EXISTS s.t (a INT)"
3329        );
3330    }
3331
3332    #[test]
3333    fn or_replace_and_if_not_exists_in_one_statement_is_refused_here_and_not_later() {
3334        // The grammar has room for both and duckdb's has not, so its refusal is a parser error with
3335        // a caret under the `NOT` and this one is a parser error at the same stage. It is the same
3336        // sentence whatever is being created.
3337        for sql in [
3338            "CREATE OR REPLACE TABLE IF NOT EXISTS t (a INT)",
3339            "CREATE OR REPLACE VIEW IF NOT EXISTS v AS SELECT 1",
3340        ] {
3341            let error = parse_ast(sql).unwrap_err().to_string();
3342            assert_eq!(
3343                error,
3344                "Parser Error: Cannot specify both OR REPLACE and IF NOT EXISTS within single \
3345                 create statement"
3346            );
3347        }
3348    }
3349
3350    #[test]
3351    fn a_create_table_as_carries_the_query_and_not_the_types() {
3352        assert_eq!(
3353            round_statement("CREATE TABLE t AS SELECT a FROM u"),
3354            "CREATE TABLE t AS SELECT a FROM u"
3355        );
3356        // The names are the syntax's to say and the types are the query's, so the column
3357        // definitions here have names and no types.
3358        assert_eq!(
3359            round_statement("CREATE TABLE t (x, y) AS SELECT a, b FROM u"),
3360            "CREATE TABLE t (x, y) AS SELECT a, b FROM u"
3361        );
3362    }
3363
3364    #[test]
3365    fn a_create_view_carries_its_body_twice_over() {
3366        assert_eq!(
3367            round_statement("CREATE VIEW v AS SELECT a FROM u"),
3368            "CREATE VIEW v AS SELECT a FROM u"
3369        );
3370        assert_eq!(
3371            round_statement("CREATE OR REPLACE VIEW main.v (x, y) AS SELECT a, b FROM u"),
3372            "CREATE OR REPLACE VIEW main.v (x, y) AS SELECT a, b FROM u"
3373        );
3374        // The text the catalog keeps is the body and only the body, so that binding it again is
3375        // binding a query rather than a `CREATE` statement.
3376        let ast = parse_ast("CREATE VIEW v (x) AS SELECT a FROM u WHERE a > 1").expect("parses");
3377        let Statement::CreateView(index) = ast.statements[0] else {
3378            panic!("not a create view");
3379        };
3380        assert_eq!(ast.string(ast.create_view(index).sql), "SELECT a FROM u WHERE a > 1");
3381    }
3382
3383    #[test]
3384    fn a_drop_view_is_not_a_drop_table() {
3385        assert_eq!(round_statement("DROP VIEW IF EXISTS a, b"), "DROP VIEW IF EXISTS a, b");
3386        assert_eq!(round_statement("DROP TABLE a"), "DROP TABLE a");
3387    }
3388
3389    #[test]
3390    fn a_drop_table_is_a_list_of_qualified_names() {
3391        assert_eq!(round_statement("DROP TABLE t"), "DROP TABLE t");
3392        assert_eq!(round_statement("DROP TABLE IF EXISTS a, b.c"), "DROP TABLE IF EXISTS a, b.c");
3393    }
3394
3395    #[test]
3396    fn dropping_something_that_is_neither_a_table_nor_a_view_is_refused() {
3397        // `TableOrView` covers `MATERIALIZED VIEW` as well, which is not a thing this database has,
3398        // and dropping one as if it were an ordinary view is a wrong answer rather than a missing
3399        // feature.
3400        let error = parse_ast("DROP MATERIALIZED VIEW v").unwrap_err().to_string();
3401        assert!(error.starts_with("Not implemented Error"), "{error}");
3402    }
3403
3404    #[test]
3405    fn both_spellings_of_insert_arrive_at_a_query() {
3406        assert_eq!(
3407            round_statement("INSERT INTO t VALUES (1, 'a'), (2, 'b')"),
3408            "INSERT INTO t VALUES (1, 'a'), (2, 'b')"
3409        );
3410        assert_eq!(
3411            round_statement("INSERT INTO t (a, b) SELECT x, y FROM u"),
3412            "INSERT INTO t (a, b) SELECT x, y FROM u"
3413        );
3414    }
3415
3416    #[test]
3417    fn an_insert_clause_that_changes_the_answer_is_refused() {
3418        for query in [
3419            "INSERT INTO t VALUES (1) RETURNING *",
3420            "INSERT OR REPLACE INTO t VALUES (1)",
3421            "INSERT INTO t BY NAME SELECT 1 AS a",
3422            "INSERT INTO t VALUES (1) ON CONFLICT DO NOTHING",
3423            "INSERT INTO t DEFAULT VALUES",
3424        ] {
3425            let error = parse_ast(query).unwrap_err().to_string();
3426            assert!(error.starts_with("Not implemented Error"), "{query} gave {error}");
3427        }
3428    }
3429
3430    #[test]
3431    fn a_column_constraint_that_is_not_not_null_is_refused() {
3432        // Nothing enforces a constraint yet. Accepting one and not enforcing it is the wrong
3433        // answer, so `NOT NULL` is kept because the column already has a nullability and the rest
3434        // are refused until there is somewhere to put them.
3435        for query in [
3436            "CREATE TABLE t (a INT PRIMARY KEY)",
3437            "CREATE TABLE t (a INT UNIQUE)",
3438            "CREATE TABLE t (a INT CHECK (a > 0))",
3439            "CREATE TABLE t (a INT DEFAULT 1)",
3440            "CREATE TABLE t (a INT REFERENCES u (b))",
3441            "CREATE TABLE t (a INT, PRIMARY KEY (a))",
3442        ] {
3443            let error = parse_ast(query).unwrap_err().to_string();
3444            assert!(error.starts_with("Not implemented Error"), "{query} gave {error}");
3445        }
3446    }
3447
3448    #[test]
3449    fn values_is_a_query_on_its_own_and_in_a_from() {
3450        assert_eq!(round("VALUES (1), (2)"), "VALUES (1), (2)");
3451        // Parenthesised it is a subquery whose body is the values, and bare it is a `ValuesRef`.
3452        // Two rules and one meaning, which is the grammar's doing and not something to flatten
3453        // here, because the parenthesised form can carry an order by and the bare one cannot.
3454        assert_eq!(
3455            round("SELECT * FROM (VALUES (1, 2), (3, 4)) t(a, b)"),
3456            "SELECT * FROM (VALUES (1, 2), (3, 4)) AS t"
3457        );
3458        assert_eq!(
3459            round("SELECT * FROM VALUES (1, 2), (3, 4) AS t(a, b)"),
3460            "SELECT * FROM VALUES (1, 2), (3, 4) AS t"
3461        );
3462        // Rows of different widths parse. Saying so wants the column count, which for an insert is
3463        // the table's, so the check belongs to the binder and not here.
3464        assert_eq!(round("VALUES (1), (2, 3)"), "VALUES (1), (2, 3)");
3465    }
3466
3467    /// `DESCRIBE` is a query body, and the two spellings that name something become a star over it.
3468    ///
3469    /// Naming a table is not a shortcut for the query. On the reference binary `DESCRIBE t` and
3470    /// `DESCRIBE SELECT * FROM t` print the same six columns and the same rows, down to the `NO` on
3471    /// a column that refuses nulls, so rewriting one into the other costs nothing and leaves the
3472    /// binder with one case instead of three. A file name goes down the same path as a table name
3473    /// because a bare string in a `FROM` clause is already a name the replacement scan picks up.
3474    #[test]
3475    fn describe_rewrites_a_name_into_a_star_over_it() {
3476        assert_eq!(round("DESCRIBE SELECT 1 AS a"), "DESCRIBE SELECT 1 AS a");
3477        assert_eq!(round("DESCRIBE t"), "DESCRIBE SELECT * FROM t");
3478        assert_eq!(round("DESC t"), "DESCRIBE SELECT * FROM t");
3479        assert_eq!(round("DESCRIBE 'x.parquet'"), "DESCRIBE SELECT * FROM x.parquet");
3480        // A body and not a statement kind, so it nests both ways with no rule of its own.
3481        assert_eq!(
3482            round("SELECT column_name FROM (DESCRIBE SELECT 1 AS a)"),
3483            "SELECT column_name FROM (DESCRIBE SELECT 1 AS a)"
3484        );
3485        assert_eq!(round("DESCRIBE DESCRIBE SELECT 1 AS a"), "DESCRIBE DESCRIBE SELECT 1 AS a");
3486    }
3487
3488    /// `SUMMARIZE` shares both of `DESCRIBE`'s grammar rules and is a different statement.
3489    ///
3490    /// It reads every row and returns one row per column carrying the min, the max, the count and
3491    /// the approximate distinct count, so none of it falls out of the `DESCRIBE` path. The word is
3492    /// the only thing in the tree that tells the two apart, which is why the transform looks at it
3493    /// rather than trusting the rule name it arrived under.
3494    #[test]
3495    fn summarize_is_refused_even_though_it_parses_as_a_describe() {
3496        for query in ["SUMMARIZE t", "SUMMARIZE SELECT 1"] {
3497            let error = parse_ast(query).expect_err("summarize is not implemented");
3498            let message = error.to_string();
3499            assert!(message.starts_with("Not implemented Error"), "{query} failed with {message}");
3500        }
3501    }
3502
3503    #[test]
3504    fn every_statement_in_the_corpus_gets_a_defined_answer() {
3505        // The point of the test is the word defined. Half of these are statement kinds and
3506        // clauses this milestone does not cover, and the requirement is not that they work, it is
3507        // that they fail by saying so. A panic, a silently dropped clause or an internal error
3508        // would each be a different bug and all three would be invisible without this.
3509        let mut done = 0;
3510        for query in CORPUS {
3511            match parse_ast(query) {
3512                Ok(ast) => {
3513                    assert_eq!(ast.statements.len(), 1, "{query}");
3514                    done += 1;
3515                }
3516                Err(error) => {
3517                    let message = error.to_string();
3518                    assert!(
3519                        message.starts_with("Not implemented Error"),
3520                        "{query} failed with {message}, which is not a not-implemented error"
3521                    );
3522                }
3523            }
3524        }
3525        // Not an assertion about the right number. It is a ratchet: this only moves up, and the
3526        // day it moves down somebody has taken a construct out without meaning to.
3527        assert!(done >= 31, "only {done} of the corpus transforms, which is fewer than it was");
3528    }
3529
3530    #[test]
3531    fn the_ast_is_far_smaller_than_the_parse_tree() {
3532        let query = CORPUS[4];
3533        let tree = parse(query).unwrap();
3534        let ast = parse_ast(query).unwrap();
3535        // The twenty precedence levels are the difference. Every one of them is a node in the
3536        // parse tree for every expression at every depth, and none of them survives into the AST.
3537        assert!(
3538            ast.node_count() * 20 < tree.arena_len(),
3539            "{} ast nodes against {} parse nodes",
3540            ast.node_count(),
3541            tree.arena_len()
3542        );
3543    }
3544
3545    #[test]
3546    fn precedence_comes_out_of_the_chain_and_into_the_tree() {
3547        assert_eq!(round("SELECT 1 + 2 * 3"), "SELECT (1 Add (2 Multiply 3))");
3548        assert_eq!(round("SELECT (1 + 2) * 3"), "SELECT ((1 Add 2) Multiply 3)");
3549        assert_eq!(round("SELECT 1 + 2 + 3"), "SELECT ((1 Add 2) Add 3)");
3550        assert_eq!(round("SELECT 1 - 2 - 3"), "SELECT ((1 Subtract 2) Subtract 3)");
3551        assert_eq!(
3552            round("SELECT a OR b AND c"),
3553            "SELECT (a Or (b And c))",
3554            "and binds tighter than or"
3555        );
3556    }
3557
3558    #[test]
3559    fn a_double_negation_is_two_nodes_and_not_none() {
3560        // Folding it would be an optimizer decision and this is not the optimizer. It also would
3561        // not be safe in general: `NOT NOT x` on a null is still null and on a non boolean it is
3562        // still an error, and both of those have to survive to the binder to be reported.
3563        assert_eq!(round("SELECT NOT NOT a"), "SELECT (Not (Not a))");
3564    }
3565
3566    #[test]
3567    fn a_parenthesised_single_expression_is_not_a_row() {
3568        assert_eq!(round("SELECT (a)"), "SELECT a");
3569        assert_eq!(round("SELECT (a, b)"), "SELECT ROW(a, b)");
3570    }
3571
3572    #[test]
3573    fn a_bracketed_list_is_a_list_of_however_many_items_were_written() {
3574        // One item is a list of one, which is where this parts company with the parenthesised form
3575        // above: `(a)` is `a` and `[a]` is a list, because the brackets are what say list.
3576        assert_eq!(round("SELECT [a]"), "SELECT [a]");
3577        assert_eq!(round("SELECT [1, 2, 3]"), "SELECT [1, 2, 3]");
3578        assert_eq!(round("SELECT []"), "SELECT []");
3579        assert_eq!(round("SELECT ['a.parquet', 'b.parquet']"), "SELECT ['a.parquet', 'b.parquet']");
3580    }
3581
3582    #[test]
3583    fn a_parameter_carries_its_identifier_however_it_was_written() {
3584        assert_eq!(round("SELECT $1"), "SELECT $1");
3585        assert_eq!(round("SELECT ?1"), "SELECT $1");
3586        assert_eq!(round("SELECT $name"), "SELECT $name");
3587        // A bare question mark is numbered by where it is, and the counting is its own, so a later
3588        // `$2` does not push the first one along. This is duckdb v1.4.1, which prints `$1 + $2`.
3589        assert_eq!(round("SELECT ? + $2"), "SELECT ($1 Add $2)");
3590        assert_eq!(round("SELECT ?, ?, ?"), "SELECT $1, $2, $3");
3591    }
3592
3593    #[test]
3594    fn the_parameters_of_a_statement_are_listed_once_each_in_written_order() {
3595        let ast = parse_ast("SELECT $b, $a, $b WHERE $a").expect("parses");
3596        assert_eq!(ast.parameters(), vec!["b", "a"]);
3597        assert!(parse_ast("SELECT 1").expect("parses").parameters().is_empty());
3598    }
3599
3600    #[test]
3601    fn the_three_ways_to_write_an_alias_all_arrive() {
3602        assert_eq!(round("SELECT a AS b"), "SELECT a AS b");
3603        assert_eq!(round("SELECT a b"), "SELECT a AS b");
3604        assert_eq!(round("SELECT b: a"), "SELECT a AS b");
3605        assert_eq!(round("SELECT a"), "SELECT a", "and no alias when none was written");
3606    }
3607
3608    #[test]
3609    fn a_from_with_no_select_selects_everything() {
3610        // DuckDB's own shorthand. Inventing the star here rather than in the binder means the
3611        // binder never has to know that the clause it is looking at was the one that was missing.
3612        assert_eq!(round("FROM t"), "SELECT * FROM t");
3613        assert_eq!(round("FROM t SELECT a"), "SELECT a FROM t");
3614    }
3615
3616    #[test]
3617    fn joins_nest_to_the_left() {
3618        assert_eq!(
3619            round("SELECT * FROM a JOIN b ON a.i = b.i LEFT JOIN c USING (k)"),
3620            "SELECT * FROM ((a Inner JOIN b ON (a.i Eq b.i)) Left JOIN c USING (k))"
3621        );
3622        assert_eq!(
3623            round("SELECT * FROM a NATURAL JOIN b"),
3624            "SELECT * FROM (a NATURAL Inner JOIN b)"
3625        );
3626        assert_eq!(round("SELECT * FROM a CROSS JOIN b"), "SELECT * FROM (a Cross JOIN b)");
3627        assert_eq!(
3628            round("SELECT * FROM a POSITIONAL JOIN b"),
3629            "SELECT * FROM (a Positional JOIN b)"
3630        );
3631        assert_eq!(round("SELECT * FROM a, b"), "SELECT * FROM a, b", "a comma is not a join node");
3632    }
3633
3634    #[test]
3635    fn a_qualified_name_keeps_its_parts_however_it_was_spelled() {
3636        // Five grammar rules can produce a column reference and they disagree about which
3637        // component is a schema and which is a table. None of that is decidable without the
3638        // catalog, so the AST holds the parts and the binder decides.
3639        assert_eq!(round("SELECT a"), "SELECT a");
3640        assert_eq!(round("SELECT t.a"), "SELECT t.a");
3641        assert_eq!(round("SELECT s.t.a"), "SELECT s.t.a");
3642        assert_eq!(round("SELECT c.s.t.a"), "SELECT c.s.t.a");
3643        assert_eq!(round("SELECT * FROM s.t"), "SELECT * FROM s.t");
3644    }
3645
3646    #[test]
3647    fn a_star_can_be_qualified() {
3648        assert_eq!(round("SELECT *"), "SELECT *");
3649        assert_eq!(round("SELECT t.*"), "SELECT t.*");
3650        assert_eq!(round("SELECT s.t.*"), "SELECT s.t.*");
3651    }
3652
3653    #[test]
3654    fn a_quoted_identifier_keeps_its_case_and_loses_its_quotes() {
3655        // DuckDB does not fold identifier case at any point, quoted or not, which the tokenizer
3656        // work established by reading the source. So the only thing to do here is take the quotes
3657        // off and resolve the doubled ones.
3658        let ast = parse_ast("SELECT \"Mixed Case\", \"a\"\"b\"").unwrap();
3659        assert_eq!(ast.strings[0], "Mixed Case");
3660        assert_eq!(ast.strings[1], "a\"b");
3661    }
3662
3663    #[test]
3664    fn a_string_literal_is_decoded_and_adjacent_ones_are_joined() {
3665        assert_eq!(round("SELECT 'it''s'"), "SELECT 'it's'");
3666        assert_eq!(round("SELECT 'a'\n'b'"), "SELECT 'ab'", "the standard's adjacency rule");
3667    }
3668
3669    /// Per #276, where the tag and the dollars were coming through as part of the value.
3670    #[test]
3671    fn a_dollar_quoted_string_loses_its_dollars_and_its_tag() {
3672        assert_eq!(round("SELECT $$dollar quoted$$"), "SELECT 'dollar quoted'");
3673        assert_eq!(round("SELECT $tag$body$tag$"), "SELECT 'body'");
3674        assert_eq!(round("SELECT $$$$"), "SELECT ''", "an empty tag and an empty body");
3675        // Nothing in the body is escaped, which is what the spelling is for, so a quote is a quote
3676        // and a dollar that is not the closing tag is a dollar.
3677        assert_eq!(round("SELECT $tag$it''s $other$ fine$tag$"), "SELECT 'it''s $other$ fine'");
3678        // An unterminated one has no closing tag to take off and keeps every byte it was given.
3679        assert_eq!(round("SELECT $$open"), "SELECT '$$open'");
3680    }
3681
3682    /// Per #329, where every prefixed spelling came back as the source text it was written as.
3683    ///
3684    /// The escapes are the ones the pinned binary takes, read off it one at a time. The two that
3685    /// are easy to get wrong are `\v`, which is not an escape and is the letter, and `\u`, which
3686    /// wants all four digits and otherwise drops the backslash and keeps the letter.
3687    #[test]
3688    fn an_escape_string_resolves_its_backslashes() {
3689        assert_eq!(round("SELECT E'a\\nb'"), "SELECT 'a\nb'");
3690        assert_eq!(round("SELECT e'a\\tb'"), "SELECT 'a\tb'", "the prefix is a letter, not a name");
3691        assert_eq!(round("SELECT E'a\\rb'"), "SELECT 'a\rb'");
3692        assert_eq!(round("SELECT E'a\\bb'"), "SELECT 'a\u{8}b'");
3693        assert_eq!(round("SELECT E'a\\fb'"), "SELECT 'a\u{c}b'");
3694        assert_eq!(round("SELECT E'a\\\\b'"), "SELECT 'a\\b'");
3695        assert_eq!(round("SELECT E'a\\'b'"), "SELECT 'a'b'", "a quote, the same as ''");
3696        assert_eq!(round("SELECT E'a''b'"), "SELECT 'a'b'", "and '' still means a quote here");
3697        // A backslash in front of anything else is dropped and the character is kept, which is what
3698        // makes \v the letter v.
3699        assert_eq!(round("SELECT E'a\\vb'"), "SELECT 'avb'");
3700        assert_eq!(round("SELECT E'a\\qb'"), "SELECT 'aqb'");
3701    }
3702
3703    /// The escapes that write a byte rather than a character, and the one that writes a character.
3704    #[test]
3705    fn a_numeric_escape_writes_the_byte_or_the_character_it_names() {
3706        assert_eq!(round("SELECT E'\\x41'"), "SELECT 'A'");
3707        assert_eq!(round("SELECT E'\\x4142'"), "SELECT 'A42'", "two digits at the most");
3708        assert_eq!(
3709            round("SELECT E'a\\x'"),
3710            "SELECT 'ax'",
3711            "and one at the least, or it is a letter"
3712        );
3713        assert_eq!(round("SELECT E'\\101'"), "SELECT 'A'");
3714        assert_eq!(round("SELECT E'\\1011'"), "SELECT 'A1'", "three digits at the most");
3715        assert_eq!(round("SELECT E'\\8'"), "SELECT '8'", "8 is not an octal digit");
3716        // Bytes and not characters, so two of them make one character and one of them makes none.
3717        assert_eq!(round("SELECT E'\\xc3\\xa9'"), "SELECT 'é'");
3718        assert_eq!(round("SELECT E'\\u00e9'"), "SELECT 'é'");
3719        assert_eq!(round("SELECT E'a\\u41'"), "SELECT 'au41'", "four digits or it is a letter");
3720        assert_eq!(round("SELECT E'a\\uZZZZ'"), "SELECT 'auZZZZ'");
3721        assert_eq!(
3722            round("SELECT E'\\ud83d\\ude00'"),
3723            "SELECT 'ud83dude00'",
3724            "surrogates are not it"
3725        );
3726    }
3727
3728    /// The two ways an escape string is not a string at all, both with the message upstream gives.
3729    #[test]
3730    fn an_escape_string_that_is_not_a_string_raises() {
3731        let error = parse_ast("SELECT E'a\\x00'").unwrap_err().to_string();
3732        assert_eq!(error, "Parser Error: Null character not permitted in escape string literal");
3733        let error = parse_ast("SELECT E'a\\377'").unwrap_err().to_string();
3734        assert_eq!(
3735            error,
3736            "Parser Error: Invalid UTF-8 in escape string literal at byte offset 1: byte mismatch",
3737            "the offset is where the bytes stop being a string, not where the escape was written"
3738        );
3739    }
3740
3741    /// The other prefixes, all of them measured against the pinned binary rather than assumed.
3742    #[test]
3743    fn the_other_string_prefixes_are_what_upstream_makes_of_them() {
3744        // N is the string and a cast of it to VARCHAR, which is where the column name comes from.
3745        assert_eq!(round("SELECT N'abc'"), "SELECT CAST('abc' AS VARCHAR)");
3746        assert_eq!(round("SELECT n'abc'"), "SELECT CAST('abc' AS VARCHAR)");
3747        // B is not a bit string. It is the letter b in front of the body, untouched.
3748        assert_eq!(round("SELECT B'101'"), "SELECT 'b101'");
3749        assert_eq!(round("SELECT b'abc'"), "SELECT 'babc'");
3750        assert_eq!(round("SELECT B''"), "SELECT 'b'", "an empty one is the letter on its own");
3751    }
3752
3753    /// X is the prefix that is not a string at all, per #329.
3754    ///
3755    /// What is kept is the text the blob prints as, because that is the text the column is named
3756    /// after and the text the cast reads the bytes back from, and one text that does both is one
3757    /// text that cannot disagree with itself.
3758    #[test]
3759    fn a_hex_string_is_a_blob_and_not_a_string() {
3760        assert_eq!(round("SELECT x'4142'"), "SELECT 'AB'::BLOB");
3761        assert_eq!(round("SELECT X'4142'"), "SELECT 'AB'::BLOB");
3762        assert_eq!(round("SELECT x'ff41'"), "SELECT '\\xFFA'::BLOB", "a byte that does not print");
3763        assert_eq!(round("SELECT x''"), "SELECT ''::BLOB", "an empty one is an empty blob");
3764        // A quote and a backslash are bytes that do not print either, which is what keeps the text
3765        // something the cast can read back.
3766        assert_eq!(round("SELECT x'2741'"), "SELECT '\\x27A'::BLOB");
3767        assert_eq!(round("SELECT x'5c7834314141'"), "SELECT '\\x5Cx41AA'::BLOB");
3768        // An odd number of digits is a parser error and a digit that is not one is not, because
3769        // upstream writes the pairs out without looking at them and the cast is what looks.
3770        let error = parse_ast("SELECT x'4'").unwrap_err().to_string();
3771        assert_eq!(
3772            error,
3773            "Parser Error: Hex string literal must have an even number of hex digits"
3774        );
3775        assert_eq!(round("SELECT x'41zz'"), "SELECT '\\x41\\xzz'::BLOB");
3776    }
3777
3778    #[test]
3779    fn the_null_and_boolean_tests_are_postfix_unary_operators() {
3780        assert_eq!(round("SELECT x IS NULL"), "SELECT (IsNull x)");
3781        assert_eq!(round("SELECT x IS NOT NULL"), "SELECT (IsNotNull x)");
3782        assert_eq!(round("SELECT x ISNULL"), "SELECT (IsNull x)");
3783        assert_eq!(round("SELECT x NOTNULL"), "SELECT (IsNotNull x)");
3784        assert_eq!(round("SELECT x IS TRUE"), "SELECT (IsTrue x)");
3785        assert_eq!(round("SELECT x IS NOT FALSE"), "SELECT (IsNotFalse x)");
3786        assert_eq!(round("SELECT x IS DISTINCT FROM y"), "SELECT (x IsDistinctFrom y)");
3787        assert_eq!(round("SELECT x IS NOT DISTINCT FROM y"), "SELECT (x IsNotDistinctFrom y)");
3788    }
3789
3790    #[test]
3791    fn the_like_family_folds_its_negation_into_the_operator() {
3792        assert_eq!(round("SELECT x LIKE 'a'"), "SELECT (x Like 'a')");
3793        assert_eq!(round("SELECT x NOT LIKE 'a'"), "SELECT (x NotLike 'a')");
3794        assert_eq!(round("SELECT x ILIKE 'a'"), "SELECT (x ILike 'a')");
3795        assert_eq!(round("SELECT x ~~ 'a'"), "SELECT (x Like 'a')", "the operator spelling");
3796        assert_eq!(round("SELECT x !~~ 'a'"), "SELECT (x NotLike 'a')");
3797        assert_eq!(round("SELECT x SIMILAR TO 'a'"), "SELECT (x SimilarTo 'a')");
3798        // Glob has no negated operator to fold into, so the negation stays where it was written.
3799        assert_eq!(round("SELECT x NOT GLOB 'a'"), "SELECT (Not (x Glob 'a'))");
3800    }
3801
3802    #[test]
3803    fn between_and_in_carry_their_negation_as_a_flag() {
3804        assert_eq!(round("SELECT x BETWEEN 1 AND 2"), "SELECT (x BETWEEN 1 AND 2)");
3805        assert_eq!(round("SELECT x NOT BETWEEN 1 AND 2"), "SELECT (NOT x BETWEEN 1 AND 2)");
3806        assert_eq!(round("SELECT x IN (1, 2)"), "SELECT (x IN [1, 2])");
3807        assert_eq!(round("SELECT x NOT IN (1, 2)"), "SELECT (NOT x IN [1, 2])");
3808    }
3809
3810    #[test]
3811    fn both_spellings_of_a_cast_are_the_same_node() {
3812        assert_eq!(round("SELECT CAST(x AS BIGINT)"), "SELECT CAST(x AS BIGINT)");
3813        assert_eq!(round("SELECT x::BIGINT"), "SELECT CAST(x AS BIGINT)");
3814        assert_eq!(round("SELECT TRY_CAST(x AS BIGINT)"), "SELECT TRY_CAST(x AS BIGINT)");
3815        assert_eq!(
3816            round("SELECT x::DECIMAL(18, 3)"),
3817            "SELECT CAST(x AS DECIMAL(18, 3))",
3818            "the type is kept as text because parsing it is the type system's job"
3819        );
3820    }
3821
3822    #[test]
3823    fn a_typed_literal_is_a_third_spelling_of_the_same_cast() {
3824        assert_eq!(round("SELECT DATE '1995-09-01'"), "SELECT CAST('1995-09-01' AS DATE)");
3825        assert_eq!(
3826            round("SELECT date '1995-09-01'"),
3827            "SELECT CAST('1995-09-01' AS date)",
3828            "the type is kept as written, the same as it is in the other two spellings"
3829        );
3830        assert_eq!(
3831            round("SELECT TIMESTAMP '2020-01-01 03:04:05'"),
3832            "SELECT CAST('2020-01-01 03:04:05' AS TIMESTAMP)"
3833        );
3834        assert_eq!(
3835            round("SELECT DECIMAL(5, 2) '1.5'"),
3836            "SELECT CAST('1.5' AS DECIMAL(5, 2))",
3837            "any type the cast takes is a typed literal, parameters and all"
3838        );
3839        assert_eq!(
3840            round("SELECT VARCHAR 'hi' FROM t"),
3841            "SELECT CAST('hi' AS VARCHAR) FROM t",
3842            "including the ones where the cast has nothing to do"
3843        );
3844    }
3845
3846    #[test]
3847    fn a_case_keeps_its_arms_in_order() {
3848        assert_eq!(
3849            round("SELECT CASE WHEN a THEN 1 WHEN b THEN 2 ELSE 3 END"),
3850            "SELECT CASE - WHEN a THEN 1 WHEN b THEN 2 ELSE 3 END"
3851        );
3852        assert_eq!(
3853            round("SELECT CASE x WHEN 1 THEN 'a' END"),
3854            "SELECT CASE x WHEN 1 THEN 'a' ELSE - END",
3855            "a simple case keeps the operand and a missing else is not an implicit null yet"
3856        );
3857    }
3858
3859    #[test]
3860    fn a_field_access_and_a_method_call_are_ordinary_function_calls() {
3861        // Which is what DuckDB makes of them too. Giving each its own AST node would mean the
3862        // binder needs a rule for something the function resolver already handles.
3863        assert_eq!(round("SELECT (f(x)).y"), "SELECT struct_extract(f(x), 'y')");
3864        assert_eq!(round("SELECT a[1]"), "SELECT array_extract(a, 1)");
3865    }
3866
3867    /// The four ways of leaving a bound out, all of which upstream fills in the same way.
3868    #[test]
3869    fn a_range_gets_the_bounds_the_query_left_out() {
3870        assert_eq!(round("SELECT a[1:2]"), "SELECT array_slice(a, 1, 2)");
3871        assert_eq!(round("SELECT a[:2]"), "SELECT array_slice(a, 1, 2)");
3872        assert_eq!(round("SELECT a[2:]"), "SELECT array_slice(a, 2, -1)");
3873        assert_eq!(round("SELECT a[:]"), "SELECT array_slice(a, 1, -1)");
3874        // `EndSliceMinus`, which is a range with no end rather than a subtraction of nothing.
3875        assert_eq!(round("SELECT a[1:-]"), "SELECT array_slice(a, 1, -1)");
3876        assert_eq!(round("SELECT a[1:2:3]"), "SELECT array_slice(a, 1, 2, 3)");
3877        // A step that was written and left empty, which upstream fills with a list so that the call
3878        // fails to bind. Answering a row here would be answering where the reference refuses.
3879        assert_eq!(round("SELECT a[1:2:]"), "SELECT array_slice(a, 1, 2, [])");
3880    }
3881
3882    /// `[]` is the one subscript the parser takes and the transformer refuses, in upstream's words.
3883    #[test]
3884    fn an_empty_subscript_is_not_a_subscript() {
3885        let error = parse_ast("SELECT a[]").expect_err("an empty subscript");
3886        assert_eq!(error.message(), "Empty subscript '[]' is not allowed");
3887    }
3888
3889    /// A rule that wrote a keyword is not a rule that said nothing, however few children it has.
3890    /// Per #313.
3891    #[test]
3892    fn a_keyword_is_not_stepped_through_on_the_way_to_its_one_argument() {
3893        for (sql, rule) in [
3894            ("SELECT row(1)", "RowExpression"),
3895            ("SELECT try(1)", "TryExpression"),
3896            ("SELECT unpack([1])", "UnpackExpression"),
3897            ("SELECT columns('a')", "ColumnsExpression"),
3898        ] {
3899            let error = parse_ast(sql).expect_err(sql);
3900            assert!(error.message().ends_with(rule), "{sql}: {error}");
3901        }
3902        // Grouping brackets really do say nothing, and that is the one rule of this shape that is
3903        // stepped through rather than refused.
3904        assert_eq!(round("SELECT (1 + 2) * 3"), "SELECT ((1 Add 2) Multiply 3)");
3905        assert_eq!(round("SELECT -(7)"), "SELECT (Negate 7)");
3906    }
3907
3908    /// The three spellings of a null check, two of which are their own grammar rule. Per #306.
3909    #[test]
3910    fn the_null_checks_are_calls_by_the_names_duckdb_prints() {
3911        // The keyword is the name, so the call is written with the canonical spelling of it whichever
3912        // case the query used. What the column is called is the binder's to decide.
3913        assert_eq!(round("SELECT COALESCE(a, b, 1)"), "SELECT coalesce(a, b, 1)");
3914        assert_eq!(round("SELECT coalesce(a)"), "SELECT coalesce(a)");
3915        assert_eq!(round("SELECT NULLIF(a, 1)"), "SELECT nullif(a, 1)");
3916        // `IFNULL` is a plain call that upstream's parser turns into the operator, qualifier and all.
3917        assert_eq!(round("SELECT ifnull(a, 1)"), "SELECT coalesce(a, 1)");
3918        assert_eq!(round("SELECT main.ifnull(a, 1)"), "SELECT coalesce(a, 1)");
3919        let error = parse_ast("SELECT ifnull(a)").expect_err("one argument to ifnull");
3920        assert_eq!(error.message(), "Wrong number of arguments to IFNULL.");
3921        let error = parse_ast("SELECT ifnull(a, b, c)").expect_err("three arguments to ifnull");
3922        assert_eq!(error.message(), "Wrong number of arguments to IFNULL.");
3923    }
3924
3925    /// The four string functions with a grammar rule of their own, written back out as the calls
3926    /// DuckDB's parser writes them as. Per #314.
3927    #[test]
3928    fn the_string_keywords_are_the_calls_duckdb_prints() {
3929        assert_eq!(round("SELECT substring(s, 2, 3)"), "SELECT substring(s, 2, 3)");
3930        assert_eq!(round("SELECT SUBSTRING(s FROM 2 FOR 3)"), "SELECT substring(s, 2, 3)");
3931        assert_eq!(round("SELECT substring(s FROM 2)"), "SELECT substring(s, 2)");
3932        // The `FOR` on its own is three arguments and not two, with the start filled in.
3933        assert_eq!(round("SELECT substring(s FOR 3)"), "SELECT substring(s, 1, 3)");
3934        // The haystack comes first in the call and second in the query.
3935        assert_eq!(round("SELECT position('c' IN s)"), "SELECT position(s, 'c')");
3936        assert_eq!(round("SELECT trim(s)"), "SELECT trim(s)");
3937        assert_eq!(round("SELECT trim(BOTH 'x' FROM s)"), "SELECT trim(s, 'x')");
3938        assert_eq!(round("SELECT trim(BOTH FROM s)"), "SELECT trim(s)");
3939        assert_eq!(round("SELECT trim(s, 'xy')"), "SELECT trim(s, 'xy')");
3940        // A direction is a different function and not a different argument.
3941        assert_eq!(round("SELECT trim(LEADING FROM s)"), "SELECT ltrim(s)");
3942        assert_eq!(round("SELECT trim(TRAILING FROM s)"), "SELECT rtrim(s)");
3943        assert_eq!(round("SELECT trim(LEADING 'x' FROM s)"), "SELECT ltrim(s, 'x')");
3944        assert_eq!(round("SELECT trim(TRAILING 'x' FROM s)"), "SELECT rtrim(s, 'x')");
3945        assert_eq!(
3946            round("SELECT overlay(s PLACING 'X' FROM 2 FOR 1)"),
3947            "SELECT overlay(s, 'X', 2, 1)"
3948        );
3949        assert_eq!(round("SELECT overlay(s PLACING 'X' FROM 2)"), "SELECT overlay(s, 'X', 2)");
3950        assert_eq!(round("SELECT overlay(s, 'X', 2, 1)"), "SELECT overlay(s, 'X', 2, 1)");
3951    }
3952
3953    #[test]
3954    fn an_aggregate_keeps_its_distinct() {
3955        assert_eq!(round("SELECT count(*)"), "SELECT count(*)");
3956        assert_eq!(round("SELECT count(DISTINCT x)"), "SELECT count(DISTINCT x)");
3957        assert_eq!(round("SELECT count(ALL x)"), "SELECT count(x)");
3958        assert_eq!(round("SELECT main.count(x)"), "SELECT main.count(x)");
3959    }
3960
3961    #[test]
3962    fn the_modifiers_hang_off_the_query_and_not_off_the_select() {
3963        // `a UNION b ORDER BY x` sorts the union. Putting the order by on the select would have
3964        // made that unrepresentable, which is why the grammar puts it outside the chain and why
3965        // the AST follows.
3966        assert_eq!(
3967            round("SELECT 1 UNION ALL SELECT 2 ORDER BY 1"),
3968            "(SELECT 1 Union All SELECT 2) ORDER BY 1 Unstated Unstated"
3969        );
3970        assert_eq!(
3971            round("SELECT a FROM t UNION SELECT b FROM u EXCEPT SELECT c FROM v"),
3972            "((SELECT a FROM t Union Unstated SELECT b FROM u) Except Unstated SELECT c FROM v)",
3973            "set operators are left associative"
3974        );
3975        assert_eq!(
3976            round("SELECT 1 UNION SELECT 2 INTERSECT SELECT 3"),
3977            "(SELECT 1 Union Unstated (SELECT 2 Intersect Unstated SELECT 3))",
3978            "and intersect binds tighter than the other two"
3979        );
3980    }
3981
3982    #[test]
3983    fn the_sort_and_limit_clauses_keep_what_was_written() {
3984        assert_eq!(
3985            round("SELECT a FROM t ORDER BY a"),
3986            "SELECT a FROM t ORDER BY a Unstated Unstated"
3987        );
3988        assert_eq!(
3989            round("SELECT a FROM t ORDER BY a DESC NULLS LAST"),
3990            "SELECT a FROM t ORDER BY a Descending Last"
3991        );
3992        assert_eq!(round("SELECT a FROM t ORDER BY ALL"), "SELECT a FROM t ORDER BY ALL");
3993        assert_eq!(round("SELECT a FROM t GROUP BY ALL"), "SELECT a FROM t GROUP BY ALL");
3994        assert_eq!(round("SELECT a FROM t LIMIT 10 OFFSET 5"), "SELECT a FROM t LIMIT 10 OFFSET 5");
3995        assert_eq!(round("SELECT a FROM t OFFSET 5 LIMIT 10"), "SELECT a FROM t LIMIT 10 OFFSET 5");
3996        assert_eq!(round("SELECT a FROM t LIMIT 10%"), "SELECT a FROM t LIMIT 10%");
3997        assert_eq!(round("SELECT a FROM t LIMIT ALL"), "SELECT a FROM t", "which is no limit");
3998    }
3999
4000    #[test]
4001    fn a_subquery_appears_in_both_places_it_can() {
4002        assert_eq!(
4003            round("SELECT * FROM (SELECT x FROM t) AS s"),
4004            "SELECT * FROM (SELECT x FROM t) AS s"
4005        );
4006        assert_eq!(round("SELECT (SELECT 1)"), "SELECT (SELECT 1)");
4007    }
4008
4009    #[test]
4010    fn distinct_on_keeps_its_expressions() {
4011        assert_eq!(round("SELECT DISTINCT a"), "SELECT DISTINCT a");
4012        assert_eq!(round("SELECT ALL a"), "SELECT a", "which is the default written out");
4013        assert_eq!(round("SELECT DISTINCT ON (a, b) a"), "SELECT DISTINCT ON (a, b) a");
4014    }
4015
4016    #[test]
4017    fn an_operator_the_dialect_does_not_name_is_kept_by_name() {
4018        // The grammar text says `OperatorLiteral <- Identifier`, which reads as though any bare
4019        // word could be written infix. It cannot. That rule is one of the 24 the matcher overrides
4020        // and it is overridden to the bare operator matcher, so what it takes is a run of operator
4021        // characters. Believing the body here would have produced a transformer that accepted
4022        // `a foo b`, which DuckDB rejects.
4023        assert_eq!(round("SELECT a <=> b"), "SELECT (a <=> b)");
4024        assert!(parse_ast("SELECT a foo b").is_err(), "a bare word is not an operator");
4025    }
4026
4027    #[test]
4028    fn a_script_is_a_list_of_statements() {
4029        let ast = parse_ast("SELECT 1; SELECT 2;").unwrap();
4030        assert_eq!(ast.statements.len(), 2);
4031        // A trailing semicolon makes an empty top level statement in the parse tree, because the
4032        // grammar's `Statement? (';'+ / EndOfInput)` is happy with nothing on both sides. It is
4033        // dropped here rather than pretended away in the matcher.
4034        let Statement::Query(second) = ast.statements[1] else {
4035            panic!("the second statement is a query");
4036        };
4037        assert_eq!(show_query(&ast, second), "SELECT 2");
4038    }
4039
4040    #[test]
4041    fn an_unsupported_construct_names_itself_and_what_was_written() {
4042        let error = parse_ast("ALTER TABLE t ADD COLUMN a INTEGER").unwrap_err().to_string();
4043        assert!(error.starts_with("Not implemented Error"), "{error}");
4044        assert!(error.contains("ALTER TABLE t ADD COLUMN a INTEGER"), "{error}");
4045        assert!(error.contains("AlterStatement"), "{error}");
4046    }
4047
4048    #[test]
4049    fn a_long_construct_is_cut_short_in_the_message() {
4050        let query = format!("ALTER TABLE t ADD COLUMN {} INTEGER", "a".repeat(80));
4051        let error = parse_ast(&query).unwrap_err().to_string();
4052        assert!(error.contains("..."), "{error}");
4053        assert!(error.len() < 200, "{error}");
4054    }
4055
4056    #[test]
4057    fn the_transformer_never_panics_on_anything_the_matcher_accepts() {
4058        // The matcher accepts a good deal that means nothing, because the grammar does. Every one
4059        // of these parses and none of them is a statement this milestone covers, and the contract
4060        // is that the answer is an error either way.
4061        for query in [
4062            "SELECT",
4063            "FROM t SELECT",
4064            "SELECT * FROM t WHERE",
4065            "SELECT ()",
4066            "SELECT a FROM t GROUP BY ()",
4067        ] {
4068            let answer = parse_ast(query);
4069            if let Err(error) = answer {
4070                let message = error.to_string();
4071                assert!(
4072                    message.starts_with("Not implemented Error")
4073                        || message.starts_with("Parser Error"),
4074                    "{query} failed with {message}"
4075                );
4076            }
4077        }
4078    }
4079
4080    #[test]
4081    fn a_file_name_in_a_from_clause_is_a_table_name_with_the_quotes_off() {
4082        // Both spellings have to arrive as the same name, because the binder decides whether it is
4083        // a file by looking at the name, and `'hits.parquet'` with the quotes still on it is not
4084        // a path that anything can open.
4085        assert_eq!(round("SELECT * FROM 'hits.parquet'"), "SELECT * FROM hits.parquet");
4086        assert_eq!(round("SELECT * FROM \"hits.parquet\""), "SELECT * FROM hits.parquet");
4087        assert_eq!(round("SELECT * FROM 'hits.parquet' AS h"), "SELECT * FROM hits.parquet AS h");
4088        assert_eq!(
4089            round_with_case("SELECT Mixed FROM 'NoSuch/Mixed/File.csv'", IdentifierCase::Lower),
4090            "SELECT mixed FROM NoSuch/Mixed/File.csv"
4091        );
4092        assert_eq!(
4093            round_with_case("SELECT Mixed FROM \"QuotedTable\"", IdentifierCase::Upper),
4094            "SELECT MIXED FROM QuotedTable"
4095        );
4096    }
4097
4098    #[test]
4099    fn a_function_call_in_a_from_clause_is_a_source_and_not_an_expression() {
4100        assert_eq!(round("SELECT * FROM range(3)"), "SELECT * FROM range(3)");
4101        assert_eq!(round("SELECT * FROM range(1, 10, 2)"), "SELECT * FROM range(1, 10, 2)");
4102        assert_eq!(round("SELECT * FROM main.range(3)"), "SELECT * FROM main.range(3)");
4103        assert_eq!(round("SELECT * FROM range(3) AS t"), "SELECT * FROM range(3) AS t");
4104        // The grammar allows a call with no arguments here and the transformer keeps it, because
4105        // whether a particular function takes none is the binder's question and not this one's.
4106        assert_eq!(round("SELECT * FROM some_function()"), "SELECT * FROM some_function()");
4107    }
4108
4109    #[test]
4110    fn the_forms_of_a_table_function_this_does_not_cover_are_turned_away_by_name() {
4111        for query in [
4112            "SELECT * FROM range(3) WITH ORDINALITY",
4113            "SELECT * FROM LATERAL range(3)",
4114            "SELECT * FROM t: range(3)",
4115        ] {
4116            let error = parse_ast(query).unwrap_err().to_string();
4117            assert!(error.contains("grammar rule"), "{query} failed with {error}");
4118        }
4119    }
4120
4121    #[test]
4122    fn a_pragma_is_the_call_it_stands_for_by_the_time_it_leaves_here() {
4123        assert_eq!(round("PRAGMA version"), "SELECT * FROM pragma_version()");
4124        assert_eq!(round("PRAGMA database_size"), "SELECT * FROM pragma_database_size()");
4125        // The case the user wrote survives, because the name goes back out in the message about a
4126        // pragma that does not exist and the pin prints it back as it was typed.
4127        assert_eq!(round("PRAGMA VERSION"), "SELECT * FROM pragma_VERSION()");
4128        assert_eq!(round("PRAGMA table_info('t')"), "SELECT * FROM pragma_table_info('t')");
4129    }
4130
4131    #[test]
4132    fn a_bare_name_in_a_pragmas_parentheses_is_a_name_and_not_a_column() {
4133        // There is no FROM clause here for a column to come out of, so both spellings have to
4134        // arrive as the same string, and a qualified one has to arrive as one string and not two.
4135        assert_eq!(round("PRAGMA table_info(t)"), "SELECT * FROM pragma_table_info('t')");
4136        assert_eq!(round("PRAGMA table_info(main.t)"), "SELECT * FROM pragma_table_info('main.t')");
4137        assert_eq!(round("PRAGMA table_info(\"T\")"), "SELECT * FROM pragma_table_info('T')");
4138        // Anything that is not a name is left alone, so the binder is the one that says there is
4139        // no overload taking an integer rather than a table called 1 being looked for.
4140        assert_eq!(round("PRAGMA table_info(1)"), "SELECT * FROM pragma_table_info(1)");
4141    }
4142
4143    #[test]
4144    fn a_pragma_with_an_equals_sign_is_a_set_and_nothing_else() {
4145        assert_eq!(round_statement("PRAGMA memory_limit = '1GB'"), "SET memory_limit = '1GB'");
4146        assert_eq!(round_statement("PRAGMA threads = 4"), "SET threads = 4");
4147    }
4148
4149    #[test]
4150    fn a_pragma_with_empty_parentheses_does_not_parse_on_either_engine() {
4151        // The rule is `PragmaParameters <- Parens(List(Expression))` and a list of no expressions
4152        // does not match, which is where the pin's parser error comes from as well.
4153        let error = parse_ast("PRAGMA version()").unwrap_err().to_string();
4154        assert!(error.contains("syntax error at or near \")\""), "{error}");
4155    }
4156
4157    #[test]
4158    fn interning_means_a_name_written_twice_is_stored_once() {
4159        let ast = parse_ast("SELECT a, a, a FROM t WHERE a = a").unwrap();
4160        assert_eq!(ast.strings.iter().filter(|text| *text == "a").count(), 1);
4161    }
4162}