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