Skip to main content

rudb_parse/
ast.rs

1//! rudb's abstract syntax tree.
2//!
3//! The parse tree the matcher produces is DuckDB's grammar, faithfully. That is the point of it and
4//! it is also why nothing downstream should read it: a bump of the vendored grammar is allowed to
5//! rename `BetweenInLikeExpression`, and if the binder is matching on that name then the bump is a
6//! rewrite. This module is the boundary. It is ours, it changes when we decide it changes, and
7//! `transform` is the one place that knows both shapes.
8//!
9//! Everything is an arena with `u32` indices, per `spec/04-architecture.md` section 4.5. There is
10//! no `Box` and no `Vec` inside a node. A list of children is a [`Slice`] into a side vector, which
11//! means a node is a fixed size, the whole tree is a handful of allocations, and walking it is a
12//! sequential read rather than a pointer chase per node. It also means an `Ast` is `Clone` and
13//! `Send` without any thought, and that a subtree can be addressed by a `u32` in a plan or an
14//! error without borrowing anything.
15//!
16//! The one cost is that you cannot hold a reference to a node and index the arena at the same time,
17//! so the code reads a node out by value first. Nodes are small and `Copy`, so that is a register
18//! move.
19
20use rudb_common::Span;
21
22use crate::matcher::NONE;
23
24/// A run of items in one of the side vectors.
25///
26/// Empty is `len == 0`, and `start` is then meaningless rather than wrong. There is no `Option`
27/// wrapper because an absent list and an empty list are the same thing everywhere this is used.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
29pub struct Slice {
30    /// The first item.
31    pub start: u32,
32    /// How many items.
33    pub len: u32,
34}
35
36impl Slice {
37    /// Whether the run is empty.
38    pub const fn is_empty(self) -> bool {
39        self.len == 0
40    }
41
42    /// The run as a range, for indexing the backing vector.
43    pub const fn range(self) -> std::ops::Range<usize> {
44        self.start as usize..(self.start + self.len) as usize
45    }
46}
47
48/// An index into `Ast::strings`.
49pub type StrRef = u32;
50/// An index into `Ast::exprs`.
51pub type ExprRef = u32;
52/// An index into `Ast::sources`.
53pub type SourceRef = u32;
54/// An index into `Ast::queries`.
55pub type QueryRef = u32;
56/// An index into `Ast::selects`.
57pub type SelectRef = u32;
58/// An index into `Ast::create_tables`.
59pub type CreateTableRef = u32;
60/// An index into `Ast::create_views`.
61pub type CreateViewRef = u32;
62/// An index into `Ast::drop_tables`.
63pub type DropTableRef = u32;
64/// Index into [`Ast::schemas`].
65pub type SchemaRef = u32;
66/// Index into [`Ast::sequences`].
67pub type SequenceRef = u32;
68/// Index into [`Ast::types`].
69pub type TypeRef = u32;
70/// Index into [`Ast::alters`].
71pub type AlterRef = u32;
72/// Index into [`Ast::indexes`].
73pub type IndexRef = u32;
74/// An index into `Ast::inserts`.
75pub type InsertRef = u32;
76/// An index into `Ast::settings`.
77pub type SettingRef = u32;
78/// An index into `Ast::windows`.
79pub type WindowRef = u32;
80
81/// One statement.
82///
83/// Seven of the twenty seven the grammar reaches. The rest are a transform error naming the rule
84/// rather than a variant that nothing fills in, so that adding one is a compile error somewhere
85/// useful rather than a silent `todo!()`.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum Statement {
88    /// A query, meaning a `SELECT` or a set operation over two of them.
89    Query(QueryRef),
90    /// `CREATE TABLE`.
91    CreateTable(CreateTableRef),
92    /// `CREATE VIEW`.
93    CreateView(CreateViewRef),
94    /// `DROP TABLE` or `DROP VIEW`, which are one rule in the grammar and one statement here.
95    DropTable(DropTableRef),
96    /// `CREATE SCHEMA` or `DROP SCHEMA`.
97    Schema(SchemaRef),
98    /// `CREATE SEQUENCE` or `DROP SEQUENCE`.
99    Sequence(SequenceRef),
100    /// `CREATE TYPE` or `DROP TYPE`.
101    Type(TypeRef),
102    /// `ALTER TABLE` or `ALTER VIEW`.
103    Alter(AlterRef),
104    /// `CREATE INDEX` or `DROP INDEX`.
105    Index(IndexRef),
106    /// `INSERT INTO`.
107    Insert(InsertRef),
108    /// `UPDATE`, held as an [`Insert`] whose columns are the ones `SET` names and whose source is
109    /// `SELECT *, condition, value, ... FROM table`, one value per named column.
110    ///
111    /// The binder knows how wide the table is and the transform does not, so the source carries
112    /// the table's columns, whether the row matched, and the new values side by side, and the
113    /// binder picks each column's new value or its old one out of them.
114    Update(InsertRef),
115    /// `DELETE FROM` and `TRUNCATE`, held the same way as [`Statement::Update`] with no columns.
116    Delete(InsertRef),
117    /// `SET name = value`.
118    Set(SettingRef),
119    /// `RESET name`, which is the same shape with nothing on the right of it.
120    Reset(SettingRef),
121    /// `CHECKPOINT` or `FORCE CHECKPOINT`.
122    Checkpoint,
123    /// `BEGIN`, `COMMIT` or `ROLLBACK`, under any of the spellings the grammar takes for each.
124    Transaction(Transaction),
125    /// `EXPLAIN` over a query, and whether `ANALYZE` was asked for.
126    ///
127    /// The query rather than a statement, because the grammar lets every statement be explained
128    /// and a plan is the only thing there is to show. `EXPLAIN INSERT` is a refusal rather than a
129    /// plan of the source, since the source is not what the statement does.
130    ///
131    /// `ANALYZE` means the query is run and the plan is printed with what happened on it, so it is
132    /// a flag on the same statement rather than a statement of its own. Everything between the
133    /// parser and the printer is the same either way, which is the point: the analyzed plan has to
134    /// be the plan that ran.
135    ///
136    /// `STATISTICS` asks for the section that says what the planner knew, which is what
137    /// `spec/stats/05-every-query.md` section 5.1.1 asks `EXPLAIN` to print. It is a flag for the
138    /// same reason `ANALYZE` is: it changes what goes on the end of the output and nothing before
139    /// it.
140    Explain { query: QueryRef, analyze: bool, statistics: bool },
141}
142
143/// `SET name = value` and `RESET name`.
144///
145/// One struct for the two, because `RESET name` is `SET name` with no value and giving it its own
146/// arena would mean two of everything to say the same thing twice.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub struct Setting {
149    /// The setting name, as written.
150    pub name: StrRef,
151    /// The scope word, if one was written.
152    pub scope: Scope,
153    /// The value, or `NONE` for a `RESET`.
154    ///
155    /// An expression rather than text. `SET memory_limit = '1GB'` writes a string and `SET threads
156    /// = 4` writes a number, and what a setting does with either is the setting's business.
157    pub value: ExprRef,
158    /// Whether the statement was written as a bare `PRAGMA name`.
159    ///
160    /// `PRAGMA disable_optimizer` is a `SET` with the name and the value both folded into one word,
161    /// and which word means what is the catalog's business rather than the parser's, so it arrives
162    /// here as a name with no value and this flag to say that no value is not a `RESET`.
163    pub pragma: bool,
164}
165
166/// Which copy of a setting a statement means.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
168pub enum Scope {
169    /// No scope word, which every setting reads as the one it has.
170    #[default]
171    Unwritten,
172    /// `GLOBAL`.
173    Global,
174    /// `SESSION`.
175    Session,
176    /// `LOCAL`.
177    Local,
178}
179
180impl Scope {
181    /// The word that was written, for the sentence an error prints.
182    #[must_use]
183    pub const fn keyword(self) -> &'static str {
184        match self {
185            Self::Unwritten => "",
186            Self::Global => "GLOBAL",
187            Self::Session => "SESSION",
188            Self::Local => "LOCAL",
189        }
190    }
191}
192
193/// `CREATE TABLE name (columns)` or `CREATE TABLE name AS query`.
194///
195/// Exactly one of `columns` and `query` says what the table is. A column list is the ordinary form
196/// and `query` is `CREATE TABLE AS`, where the columns come from what the query produced and the
197/// only thing the syntax contributes is optionally renaming them, which is `columns` with the types
198/// left as `NONE`.
199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
200pub struct CreateTable {
201    /// The table name, as a run of [`Slice`] parts, outermost first.
202    pub name: Slice,
203    /// The column definitions, as a run of [`ColumnDef`].
204    pub columns: Slice,
205    /// The `AS` query, or `NONE`.
206    pub query: QueryRef,
207    /// Whether `IF NOT EXISTS` was written.
208    pub if_not_exists: bool,
209    /// Whether `OR REPLACE` was written.
210    pub or_replace: bool,
211    /// Whether `TEMP` or `TEMPORARY` was written.
212    pub temporary: bool,
213    /// The column names of each `PRIMARY KEY` and `UNIQUE`, as a run of name lists in the order
214    /// they were written, whether on a column or on the table.
215    pub keys: Slice,
216    /// Which of `keys` is the primary key, or `NONE`.
217    pub primary: u32,
218    /// Every `CHECK` expression, as a run of expressions in the order they were written, whether on
219    /// a column or on the table.
220    pub checks: Slice,
221    /// The columns of each `FOREIGN KEY`, as a run of name lists in the order written, whether on
222    /// a column or on the table.
223    pub foreign: Slice,
224    /// The table each of `foreign` references, as a run of name lists of its parts.
225    pub foreign_tables: Slice,
226    /// The referenced columns of each of `foreign`, as a run of name lists, an empty one when the
227    /// constraint named none and so means the referenced table's primary key.
228    pub foreign_referenced: Slice,
229    /// Every constraint in the order written, as a run of [`Constraint`], which is the order the pin
230    /// lists them in. A `NOT NULL` a primary key implies is not here, since nobody wrote it.
231    pub order: Slice,
232}
233
234/// One constraint of a `CREATE TABLE`, by its place in the list of its kind.
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub enum Constraint {
237    /// One of `CreateTable::keys`.
238    Key(u32),
239    /// One of `CreateTable::checks`.
240    Check(u32),
241    /// One of `CreateTable::foreign`.
242    Foreign(u32),
243    /// A `NOT NULL` written on the column at this place.
244    NotNull(u32),
245}
246
247/// One column of a `CREATE TABLE`.
248///
249/// The type is the text as written rather than a resolved type, because resolving a type is the
250/// binder's job and this crate is syntax. `VARCHAR(10)` and `STRUCT(a INTEGER)` reach the binder
251/// as themselves.
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub struct ColumnDef {
254    /// The column name.
255    pub name: StrRef,
256    /// The type as written, or `NONE` when the definition had none, which only `CREATE TABLE AS`
257    /// allows.
258    pub ty: StrRef,
259    /// Whether `NOT NULL` was written.
260    pub not_null: bool,
261    /// The `DEFAULT` expression, or `NONE` when the definition had none.
262    pub default: ExprRef,
263}
264
265/// `CREATE VIEW name (columns) AS query`.
266///
267/// The body is kept twice over, as a bound reference into this same arena and as the text that was
268/// written. Both are needed and they are needed for different things. The reference is what binds
269/// the body at creation, which is where a view over a table that is not there is refused. The text
270/// is what the catalog keeps, because a view is bound again at every reference rather than frozen
271/// at creation: a view over `SELECT * FROM t` follows `t` when a column is added to it, which was
272/// measured, and the only way to follow it is to have the query to bind again.
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
274pub struct CreateView {
275    /// The view name, as a run of [`Slice`] parts, outermost first.
276    pub name: Slice,
277    /// The column aliases, as a run of parts, empty when the statement wrote no list.
278    pub columns: Slice,
279    /// The body.
280    pub query: QueryRef,
281    /// The body as it was written, which is what the catalog keeps.
282    pub sql: StrRef,
283    /// Whether `IF NOT EXISTS` was written.
284    pub if_not_exists: bool,
285    /// Whether `OR REPLACE` was written.
286    pub or_replace: bool,
287    /// Whether `TEMP` or `TEMPORARY` was written.
288    pub temporary: bool,
289}
290
291/// `DROP TABLE a, b` or `DROP VIEW a, b`.
292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
293pub struct DropTable {
294    /// The names, as a run of [`Slice`] into `Ast::name_lists`, each of which is a run of parts.
295    pub names: Slice,
296    /// Whether `IF EXISTS` was written.
297    pub if_exists: bool,
298    /// Whether `VIEW` was written where `TABLE` could have been. Dropping one as the other is an
299    /// error rather than a synonym, so which word was written has to survive the transform.
300    pub view: bool,
301}
302
303/// `CREATE SCHEMA name` or `DROP SCHEMA name`.
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub struct Schema {
306    /// The name, as a run of parts, outermost first.
307    pub name: Slice,
308    /// Whether this is a `DROP` rather than a `CREATE`.
309    pub drop: bool,
310    /// Whether `IF NOT EXISTS` was written on a create or `IF EXISTS` on a drop.
311    pub quiet: bool,
312    /// Whether `OR REPLACE` was written, which only a create can have.
313    pub or_replace: bool,
314    /// Whether `TEMP` or `TEMPORARY` was written, which only a create can have.
315    pub temporary: bool,
316    /// Whether `CASCADE` was written, which only a drop can have.
317    pub cascade: bool,
318}
319
320/// `CREATE SEQUENCE name options` or `DROP SEQUENCE name`.
321///
322/// The options are settled here rather than in the binder, defaults and all, because that is where
323/// the pin settles them and every refusal of a bad combination is a parser error there.
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub struct Sequence {
326    /// The name, as a run of parts, outermost first.
327    pub name: Slice,
328    /// Whether this is a `DROP` rather than a `CREATE`.
329    pub drop: bool,
330    /// Whether `IF NOT EXISTS` was written on a create or `IF EXISTS` on a drop.
331    pub quiet: bool,
332    /// Whether `OR REPLACE` was written, which only a create can have.
333    pub or_replace: bool,
334    /// Whether `TEMP` or `TEMPORARY` was written, which only a create can have.
335    pub temporary: bool,
336    /// Whether `CASCADE` was written, which only a drop can have.
337    pub cascade: bool,
338    /// What a create settled, and the defaults on a drop.
339    pub options: rudb_common::sequence::Options,
340    /// The table or view an `ALTER SEQUENCE ... OWNED BY` names, as a run of parts, and empty for
341    /// anything else. An alter is a statement that is neither a drop nor has this empty.
342    pub owner: Slice,
343}
344
345/// `CREATE TYPE name AS type` or `DROP TYPE name`.
346#[derive(Debug, Clone, Copy, PartialEq, Eq)]
347pub struct TypeDef {
348    /// The name, as a run of parts, outermost first.
349    pub name: Slice,
350    /// Whether this is a `DROP` rather than a `CREATE`.
351    pub drop: bool,
352    /// Whether `IF NOT EXISTS` was written on a create or `IF EXISTS` on a drop.
353    pub quiet: bool,
354    /// Whether `OR REPLACE` was written, which only a create can have.
355    pub or_replace: bool,
356    /// Whether `TEMP` or `TEMPORARY` was written, which only a create can have.
357    pub temporary: bool,
358    /// Whether `CASCADE` was written, which only a drop can have.
359    pub cascade: bool,
360    /// The type the name stands for, as it was written, and `NONE` on a drop.
361    pub ty: StrRef,
362}
363
364/// `CREATE [UNIQUE] INDEX name ON table (elements)` or `DROP INDEX name`.
365#[derive(Debug, Clone, Copy, PartialEq, Eq)]
366pub struct Index {
367    /// The index, as a run of parts. One part on a create, where the grammar allows no more.
368    pub name: Slice,
369    /// The table a create is over, as a run of parts, and empty on a drop.
370    pub table: Slice,
371    /// Whether this is a `DROP` rather than a `CREATE`.
372    pub drop: bool,
373    /// Whether `IF NOT EXISTS` was written on a create or `IF EXISTS` on a drop.
374    pub quiet: bool,
375    /// Whether `UNIQUE` was written.
376    pub unique: bool,
377    /// Whether `OR REPLACE` was written.
378    pub or_replace: bool,
379    /// The kind after `USING`, or `NONE` when none was written.
380    pub using: StrRef,
381    /// The elements, each a column or an expression, in the order written.
382    pub elements: Slice,
383}
384
385/// `ALTER TABLE name action` or `ALTER VIEW name RENAME TO other`.
386///
387/// One action a statement, because the pin refuses a list of them in the parser.
388#[derive(Debug, Clone, Copy, PartialEq, Eq)]
389pub struct Alter {
390    /// The table or view, as a run of parts, outermost first.
391    pub name: Slice,
392    /// Whether `IF EXISTS` was written, which makes a missing table no error.
393    pub quiet: bool,
394    /// Whether this is `ALTER VIEW` rather than `ALTER TABLE`.
395    pub view: bool,
396    /// What it does.
397    pub action: AlterAction,
398}
399
400/// What one `ALTER TABLE` does. A column is named as written.
401#[derive(Debug, Clone, Copy, PartialEq, Eq)]
402pub enum AlterAction {
403    /// `RENAME TO name`.
404    Rename {
405        /// The new name.
406        to: StrRef,
407    },
408    /// `RENAME COLUMN column TO name`.
409    RenameColumn {
410        /// The column.
411        column: StrRef,
412        /// The new name.
413        to: StrRef,
414    },
415    /// `ADD COLUMN definition`, where only the type, `NOT NULL` and `DEFAULT` count, since the pin
416    /// drops every other constraint written on an added column.
417    AddColumn {
418        /// The column as written.
419        column: ColumnDef,
420        /// Whether `IF NOT EXISTS` was written.
421        quiet: bool,
422    },
423    /// `DROP COLUMN column`.
424    DropColumn {
425        /// The column.
426        column: StrRef,
427        /// Whether `IF EXISTS` was written.
428        quiet: bool,
429    },
430    /// `ALTER COLUMN column SET DEFAULT expression`, or `DROP DEFAULT` when the expression is
431    /// `NONE`.
432    Default {
433        /// The column.
434        column: StrRef,
435        /// The new default.
436        default: ExprRef,
437    },
438    /// `ALTER COLUMN column SET NOT NULL` or `DROP NOT NULL`.
439    NotNull {
440        /// The column.
441        column: StrRef,
442        /// Whether it is `SET`.
443        set: bool,
444    },
445    /// `ALTER COLUMN column SET DATA TYPE type USING expression`, either of which can be left out,
446    /// though not both. `NONE` for a missing one.
447    Type {
448        /// The column.
449        column: StrRef,
450        /// The type as written.
451        ty: StrRef,
452        /// The expression the new values are worked out by.
453        using: ExprRef,
454    },
455}
456
457/// `INSERT INTO name (columns) query`.
458#[derive(Debug, Clone, Copy, PartialEq, Eq)]
459pub struct Insert {
460    /// The table name, as a run of parts, outermost first.
461    pub name: Slice,
462    /// The column list, as a run of parts, empty when the statement did not write one.
463    pub columns: Slice,
464    /// What produces the rows, which is a `VALUES` clause or any other query, or `NONE` for
465    /// `DEFAULT VALUES`, which is one row of every column's default.
466    pub source: QueryRef,
467    /// The `RETURNING` list, held as `SELECT list FROM table [AS alias]` and run over the rows the
468    /// statement wrote rather than over the table.
469    pub returning: Option<QueryRef>,
470    /// What an `INSERT` does with a row whose key the table already holds, when it said.
471    pub conflict: Option<Conflict>,
472}
473
474/// `ON CONFLICT`, `INSERT OR REPLACE` or `INSERT OR IGNORE`.
475#[derive(Debug, Clone, Copy, PartialEq, Eq)]
476pub struct Conflict {
477    /// The columns of the key the statement named, as a run of parts, empty when it named none.
478    pub target: Slice,
479    /// What happens to a row that clashes.
480    pub action: ConflictAction,
481}
482
483/// What happens to a row whose key is already held.
484#[derive(Debug, Clone, Copy, PartialEq, Eq)]
485pub enum ConflictAction {
486    /// `DO NOTHING` or `OR IGNORE`: the row is dropped.
487    Nothing,
488    /// `OR REPLACE`: the held row takes the new row's values in the columns the statement wrote.
489    Replace,
490    /// `DO UPDATE SET`, held as `SELECT values..., condition FROM table AS alias POSITIONAL JOIN
491    /// table AS excluded`, which the write runs with the held rows on the left and the new rows on
492    /// the right.
493    Update {
494        /// The columns that are set, as a run of parts, one for each value.
495        columns: Slice,
496        /// The query that works out the values and whether the row is updated at all.
497        query: QueryRef,
498    },
499}
500
501/// A `WITH name AS MATERIALIZED (query)`, which is run once and read wherever it is named.
502///
503/// Only the materialised ones are here. A plain `WITH` and a `NOT MATERIALIZED` one are put into
504/// every place they are named while the tree is being built, the way the reference binary does it,
505/// so by the time anything reads an [`Ast`] there is no name left to resolve.
506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
507pub struct Cte {
508    /// The name it was written with.
509    pub name: StrRef,
510    /// What produces its rows.
511    pub query: QueryRef,
512    /// The column names from `AS name(a, b)`, as a run of [`StrRef`], empty when there were none.
513    pub columns: Slice,
514}
515
516/// A query: a body, plus the modifiers that apply to whatever the body produced.
517///
518/// The split is the grammar's, not an invention. `SelectStatementInternal <- WithClause?
519/// SelectSetOpChain ResultModifiers?` puts `ORDER BY` and `LIMIT` outside the set operator chain,
520/// which is the only place they can go and be right: `a UNION b ORDER BY x` sorts the union and not
521/// the second half of it. Hanging them off `Select` instead would have made that unrepresentable.
522#[derive(Debug, Clone, Copy, PartialEq, Eq)]
523pub struct Query {
524    /// The materialised `WITH` definitions this query introduces, as a run of indexes into
525    /// `Ast::ctes` held in `Ast::cte_lists`, outermost first.
526    ///
527    /// A list of indexes rather than a run of the arena itself, because a materialised `WITH`
528    /// inside another one is pushed while the outer one is still being built, so what one query
529    /// owns is not a contiguous stretch of the arena.
530    pub ctes: Slice,
531    /// What produces the rows.
532    pub body: QueryBody,
533    /// The `ORDER BY` list, as a run of [`OrderItem`].
534    pub order_by: Slice,
535    /// Whether the clause was `ORDER BY ALL`.
536    pub order_by_all: bool,
537    /// The `LIMIT` expression, or `NONE`.
538    pub limit: ExprRef,
539    /// Whether the limit was a percentage rather than a row count.
540    pub limit_percent: bool,
541    /// The `OFFSET` expression, or `NONE`.
542    pub offset: ExprRef,
543}
544
545impl Query {
546    /// A query with no modifiers on it.
547    pub const fn bare(body: QueryBody) -> Self {
548        Self {
549            ctes: Slice { start: 0, len: 0 },
550            body,
551            order_by: Slice { start: 0, len: 0 },
552            order_by_all: false,
553            limit: NONE,
554            limit_percent: false,
555            offset: NONE,
556        }
557    }
558}
559
560/// What produces the rows of a query.
561#[derive(Debug, Clone, Copy, PartialEq, Eq)]
562pub enum QueryBody {
563    /// One `SELECT ... FROM ... WHERE ...` block.
564    Select(SelectRef),
565    /// `UNION`, `EXCEPT` or `INTERSECT` over two queries.
566    SetOp {
567        /// Which operator.
568        op: SetOp,
569        /// Whether duplicates survive.
570        quantifier: Quantifier,
571        /// Whether the columns are matched up by name rather than by position.
572        by_name: bool,
573        /// The query on the left.
574        left: QueryRef,
575        /// The query on the right.
576        right: QueryRef,
577    },
578    /// `VALUES (1, 'a'), (2, 'b')`, as a run of [`Slice`] in `Ast::rows`.
579    ///
580    /// A row count and a column count and nothing else, so it is a query body rather than a
581    /// statement of its own. That is also what makes `INSERT INTO t VALUES (1)` and
582    /// `INSERT INTO t SELECT 1` the same shape by the time anything downstream sees them, which is
583    /// the reason the insert walker does not have two arms.
584    Values(Slice),
585    /// `DESCRIBE SELECT ...`, `DESCRIBE t` and `DESCRIBE 'file.parquet'`.
586    ///
587    /// A query body rather than a statement, because that is where the grammar puts it:
588    /// `SelectStatementType <- ... / DescribeStatement / ...`, so `FROM (DESCRIBE SELECT 1)` is a
589    /// subquery over one and needs no rule of its own. The two spellings that name something
590    /// instead of writing a query arrive here as `DESCRIBE SELECT * FROM that`, which is not a
591    /// shortcut: on the reference binary `DESCRIBE t` and `DESCRIBE SELECT * FROM t` produce the
592    /// same six columns and the same rows, down to the primary key and the default.
593    Describe(QueryRef),
594    /// `SHOW name`, resolved as a setting or a deprecated table description while binding.
595    Show { name: Slice, relation: QueryRef },
596}
597
598/// Which set operator.
599#[derive(Debug, Clone, Copy, PartialEq, Eq)]
600pub enum SetOp {
601    /// `UNION`.
602    Union,
603    /// `EXCEPT`.
604    Except,
605    /// `INTERSECT`.
606    Intersect,
607}
608
609/// Whether a set operator or an aggregate keeps duplicates.
610///
611/// `Unstated` is not the same as `All` even though the two agree for `UNION`, because they disagree
612/// for `INTERSECT` in some dialects and because an error message that says what was written is
613/// better than one that says what it was taken to mean.
614#[derive(Debug, Clone, Copy, PartialEq, Eq)]
615pub enum Quantifier {
616    /// Neither word was written.
617    Unstated,
618    /// `ALL`.
619    All,
620    /// `DISTINCT`.
621    Distinct,
622}
623
624/// What the `DISTINCT` clause of a select said.
625#[derive(Debug, Clone, Copy, PartialEq, Eq)]
626pub enum Distinct {
627    /// No clause, or the no-op `SELECT ALL`.
628    No,
629    /// `SELECT DISTINCT`.
630    Yes,
631    /// `SELECT DISTINCT ON (a, b)`, holding the expressions in the parentheses.
632    On(Slice),
633}
634
635/// One select block.
636///
637/// Every optional expression is `NONE` when it is absent rather than an `Option<u32>`, which keeps
638/// the struct at forty bytes and keeps the absent case spelled the same way it is spelled in the
639/// parse tree arena.
640#[derive(Debug, Clone, Copy, PartialEq, Eq)]
641pub struct Select {
642    /// The `DISTINCT` clause.
643    pub distinct: Distinct,
644    /// The target list, as a run of [`Target`].
645    pub targets: Slice,
646    /// The `FROM` list, as a run of [`SourceRef`]. Several entries mean a cross product.
647    pub from: Slice,
648    /// The `WHERE` expression, or `NONE`.
649    pub filter: ExprRef,
650    /// The `GROUP BY` list, as a run of [`ExprRef`].
651    pub group_by: Slice,
652    /// Whether the clause was `GROUP BY ALL`.
653    pub group_by_all: bool,
654    /// The `HAVING` expression, or `NONE`.
655    pub having: ExprRef,
656}
657
658impl Select {
659    /// An empty select, which is what the transformer fills in from.
660    pub const fn empty() -> Self {
661        Self {
662            distinct: Distinct::No,
663            targets: Slice { start: 0, len: 0 },
664            from: Slice { start: 0, len: 0 },
665            filter: NONE,
666            group_by: Slice { start: 0, len: 0 },
667            group_by_all: false,
668            having: NONE,
669        }
670    }
671}
672
673/// One entry of a target list.
674#[derive(Debug, Clone, Copy, PartialEq, Eq)]
675pub struct Target {
676    /// What is being selected.
677    pub expr: ExprRef,
678    /// The alias, or `NONE`. The binder invents one when there is none, because what it invents
679    /// depends on the expression and that is a binder question rather than a parser question.
680    pub alias: StrRef,
681}
682
683/// One entry of an order by list.
684#[derive(Debug, Clone, Copy, PartialEq, Eq)]
685pub struct OrderItem {
686    /// What to sort on.
687    pub expr: ExprRef,
688    /// The direction.
689    pub order: Order,
690    /// Where nulls go.
691    pub nulls: Nulls,
692}
693
694/// Sort direction, with the unwritten case kept apart from the default it resolves to.
695#[derive(Debug, Clone, Copy, PartialEq, Eq)]
696pub enum Order {
697    /// Nothing was written.
698    Unstated,
699    /// `ASC` or `ASCENDING`.
700    Ascending,
701    /// `DESC` or `DESCENDING`.
702    Descending,
703}
704
705/// Null placement in a sort.
706#[derive(Debug, Clone, Copy, PartialEq, Eq)]
707pub enum Nulls {
708    /// Nothing was written, so the session default applies.
709    Unstated,
710    /// `NULLS FIRST`.
711    First,
712    /// `NULLS LAST`.
713    Last,
714}
715
716/// How a window frame measures the distance to its bounds.
717#[derive(Debug, Clone, Copy, PartialEq, Eq)]
718pub enum WindowUnit {
719    /// `ROWS`, so a bound counts rows.
720    Rows,
721    /// `RANGE`, so a bound is a value offset from the current row's sort key.
722    Range,
723    /// `GROUPS`, so a bound counts runs of rows that tie on the sort key.
724    Groups,
725}
726
727/// One end of a window frame.
728#[derive(Debug, Clone, Copy, PartialEq, Eq)]
729pub enum WindowBound {
730    /// `UNBOUNDED PRECEDING`, the first row of the partition.
731    UnboundedPreceding,
732    /// `n PRECEDING`, holding the offset expression.
733    Preceding(ExprRef),
734    /// `CURRENT ROW`.
735    CurrentRow,
736    /// `n FOLLOWING`, holding the offset expression.
737    Following(ExprRef),
738    /// `UNBOUNDED FOLLOWING`, the last row of the partition.
739    UnboundedFollowing,
740}
741
742/// Which peers of the current row the frame drops once its bounds have been applied.
743#[derive(Debug, Clone, Copy, PartialEq, Eq)]
744pub enum WindowExclude {
745    /// `EXCLUDE NO OTHERS`, which is also what an unwritten clause means.
746    NoOthers,
747    /// `EXCLUDE CURRENT ROW`.
748    CurrentRow,
749    /// `EXCLUDE GROUP`, dropping the current row and everything that ties with it.
750    Group,
751    /// `EXCLUDE TIES`, dropping everything that ties with the current row but keeping it.
752    Ties,
753}
754
755/// Everything inside the parentheses of an `OVER`.
756///
757/// A named window is resolved here rather than downstream, because the resolution is a parser
758/// question on the reference binary: a reference to a window nobody defined is a `Parser Error`
759/// there, and a view written with `OVER w` comes back out of the catalog with the definition
760/// inlined. So nothing after the transform ever sees a name, and there is no window clause on
761/// [`Select`] for it to see one in.
762#[derive(Debug, Clone, Copy, PartialEq, Eq)]
763pub struct WindowSpec {
764    /// The `PARTITION BY` list, as a run of [`ExprRef`], empty when there was no clause.
765    pub partition: Slice,
766    /// The `ORDER BY` list, as a run of [`OrderItem`], empty when there was no clause.
767    pub order: Slice,
768    /// Which of the three units the bounds are measured in.
769    pub unit: WindowUnit,
770    /// Where the frame starts.
771    pub start: WindowBound,
772    /// Where the frame ends.
773    pub end: WindowBound,
774    /// Which peers the frame drops.
775    pub exclude: WindowExclude,
776}
777
778impl WindowSpec {
779    /// The frame a window with no frame clause gets, which the standard fixes and DuckDB follows.
780    pub const DEFAULT_UNIT: WindowUnit = WindowUnit::Range;
781    /// The start a window with no frame clause gets.
782    pub const DEFAULT_START: WindowBound = WindowBound::UnboundedPreceding;
783    /// The end a window with no frame clause gets.
784    pub const DEFAULT_END: WindowBound = WindowBound::CurrentRow;
785
786    /// A window with no clauses at all, which is what `OVER ()` means.
787    pub const fn empty() -> Self {
788        Self {
789            partition: Slice { start: 0, len: 0 },
790            order: Slice { start: 0, len: 0 },
791            unit: Self::DEFAULT_UNIT,
792            start: Self::DEFAULT_START,
793            end: Self::DEFAULT_END,
794            exclude: WindowExclude::NoOthers,
795        }
796    }
797
798    /// Whether the frame is the one an unwritten frame clause means.
799    ///
800    /// This is what decides whether the frame is printed, which is not a matter of taste: the
801    /// printed form is the column name a window target gets when the query wrote no alias, so
802    /// `SELECT sum(x) OVER (ORDER BY x)` has to be named without a frame in it to agree with the
803    /// reference binary.
804    pub fn frame_is_default(&self) -> bool {
805        self.unit == Self::DEFAULT_UNIT
806            && self.start == Self::DEFAULT_START
807            && self.end == Self::DEFAULT_END
808            && self.exclude == WindowExclude::NoOthers
809    }
810}
811
812/// One entry in a `FROM` clause, which is a tree because joins nest.
813#[derive(Debug, Clone, Copy, PartialEq, Eq)]
814pub enum Source {
815    /// A named table, possibly qualified by schema and catalog.
816    Table {
817        /// The name, as a run of [`StrRef`] in `Ast::parts`, outermost first.
818        name: Slice,
819        /// The alias, or `NONE`.
820        alias: StrRef,
821        /// Column aliases from `AS t(a, b)`, as a run of [`StrRef`].
822        columns: Slice,
823    },
824    /// A materialised `WITH` named where a table goes.
825    ///
826    /// Which definition it reads is settled here rather than left as a name, because shadowing is
827    /// a question about where the name was written and this is the only place that still knows.
828    Cte {
829        /// Which definition, as an index into `Ast::ctes`.
830        cte: u32,
831        /// The alias, or `NONE`, which for a bare name is the name itself.
832        alias: StrRef,
833        /// Column aliases from `AS c(a, b)`, as a run of [`StrRef`].
834        columns: Slice,
835    },
836    /// A parenthesised query in the `FROM` clause.
837    Subquery {
838        /// The query.
839        query: QueryRef,
840        /// The alias, or `NONE`.
841        alias: StrRef,
842        /// Column aliases, as a run of [`StrRef`].
843        columns: Slice,
844    },
845    /// A function call where a table goes, such as `range(10)`.
846    ///
847    /// Held with the name as a qualified run rather than a single string, because `main.range(10)`
848    /// is legal and a function in a schema that does not exist has to say so rather than being
849    /// looked up unqualified and found.
850    Function {
851        /// The name, as a run of [`StrRef`] in `Ast::parts`, outermost first.
852        name: Slice,
853        /// The arguments, as a run of [`Target`] where the alias is the parameter name and is
854        /// `NONE` for a positional one.
855        args: Slice,
856        /// The alias, or `NONE`.
857        alias: StrRef,
858        /// Column aliases from `AS t(a, b)`, as a run of [`StrRef`].
859        columns: Slice,
860        /// Whether the call was written as `PRAGMA name` rather than as a function call.
861        ///
862        /// The two are the same query, because `PRAGMA table_info('t')` is rewritten to
863        /// `SELECT * FROM pragma_table_info('t')` here the way upstream rewrites it, and the
864        /// rewritten form is what the plan and the deparser see. What the flag is for is the two
865        /// messages a bad call produces, which upstream writes in the spelling the user used:
866        /// `table_info()` rather than `pragma_table_info()`, and a candidate line reading
867        /// `PRAGMA "table_info"(VARCHAR)`. A user who wrote a pragma and is told about a function
868        /// they did not name has been handed the rewrite to debug rather than their own statement.
869        pragma: bool,
870    },
871    /// A `VALUES` in the `FROM` clause.
872    Values {
873        /// The rows, as a run of [`Slice`] in `Ast::rows`.
874        rows: Slice,
875        /// The alias, or `NONE`.
876        alias: StrRef,
877        /// Column aliases, as a run of [`StrRef`].
878        columns: Slice,
879    },
880    /// Two sources joined.
881    Join {
882        /// The left side.
883        left: SourceRef,
884        /// The right side.
885        right: SourceRef,
886        /// Which join.
887        kind: JoinKind,
888        /// Whether it was written `NATURAL`.
889        natural: bool,
890        /// The `ON` expression, or `NONE`.
891        on: ExprRef,
892        /// The `USING` column list, as a run of [`StrRef`].
893        using: Slice,
894    },
895}
896
897/// Which join.
898#[derive(Debug, Clone, Copy, PartialEq, Eq)]
899pub enum JoinKind {
900    /// `[INNER] JOIN`.
901    Inner,
902    /// `LEFT [OUTER] JOIN`.
903    Left,
904    /// `RIGHT [OUTER] JOIN`.
905    Right,
906    /// `FULL [OUTER] JOIN`.
907    Full,
908    /// `SEMI JOIN`.
909    Semi,
910    /// `ANTI JOIN`.
911    Anti,
912    /// `CROSS JOIN`.
913    Cross,
914    /// `POSITIONAL JOIN`, which is DuckDB's own and pairs rows by ordinal.
915    Positional,
916}
917
918/// One expression.
919///
920/// Twenty four bytes, which is the widest variant rounded up. The precedence chain in the grammar
921/// does not survive into here: twenty levels of `X <- Y Tail*` become one [`Expr::Binary`] tree,
922/// because the levels exist to make the grammar unambiguous and mean nothing afterwards.
923#[derive(Debug, Clone, Copy, PartialEq, Eq)]
924pub enum Expr {
925    /// `*`, or `t.*` with a qualifier.
926    Star {
927        /// The qualifier, as a run of [`StrRef`], empty for a bare star.
928        qualifier: Slice,
929        /// `REPLACE (expression AS column)`, as a run of [`Target`] where the alias is the column
930        /// being replaced, empty for a star with no replace list.
931        ///
932        /// A [`Target`] rather than a type of its own because a replacement is an expression and a
933        /// name, which is exactly what a target is, and because that puts it in the arena every
934        /// other expression and name pair already lives in.
935        replacements: Slice,
936    },
937    /// A column reference, qualified or not.
938    Column {
939        /// The name, as a run of [`StrRef`], outermost first, so `s.t.a` is three parts.
940        name: Slice,
941    },
942    /// A literal, kept as the text that was written.
943    Literal {
944        /// Which kind.
945        kind: LiteralKind,
946        /// The text, with quotes stripped and escapes resolved for a string, `NONE` for a keyword
947        /// literal like `NULL` where the kind already says everything.
948        text: StrRef,
949    },
950    /// A prefix or postfix operator.
951    Unary {
952        /// Which operator.
953        op: UnaryOp,
954        /// What it applies to.
955        operand: ExprRef,
956    },
957    /// An infix operator.
958    Binary {
959        /// Which operator.
960        op: BinaryOp,
961        /// The left operand.
962        left: ExprRef,
963        /// The right operand.
964        right: ExprRef,
965    },
966    /// A function call.
967    Function {
968        /// The name, as a run of [`StrRef`], so `main.count` is two parts.
969        name: Slice,
970        /// The arguments, as a run of [`ExprRef`].
971        args: Slice,
972        /// Whether the call said `DISTINCT`.
973        distinct: bool,
974        /// The `FILTER (WHERE ...)` predicate, or `NONE`. Kept on every call and not only on the
975        /// ones that can carry it, because which names can carry it is a question about the
976        /// function catalog and the parser does not have one.
977        filter: ExprRef,
978    },
979    /// A function call with an `OVER` on the end of it.
980    ///
981    /// Kept apart from [`Expr::Function`] rather than given an optional window, because the two
982    /// are different things by every rule that applies to them: a window call is refused in a
983    /// `WHERE` and in a `HAVING`, it may not appear inside an aggregate, and it resolves against a
984    /// different set of names. A variant that only some of the code has to remember to look at is
985    /// a variant the rest of the code gets wrong.
986    Window {
987        /// The name, as a run of [`StrRef`], so `main.sum` is two parts.
988        name: Slice,
989        /// The arguments, as a run of [`ExprRef`].
990        args: Slice,
991        /// Whether the call said `DISTINCT`.
992        distinct: bool,
993        /// The `FILTER (WHERE ...)` predicate, or `NONE`. It is written before the `OVER` and not
994        /// after it, which is a rule of the grammar rather than of the binder.
995        filter: ExprRef,
996        /// Whether the call said `IGNORE NULLS`. `RESPECT NULLS` is the default and is not kept,
997        /// because the reference binary drops it: a view written with it comes back without it.
998        ignore_nulls: bool,
999        /// The `ORDER BY` written inside the brackets, as a run of [`OrderItem`], empty when there
1000        /// was none. This is the order the call reads the rows of its frame in, and it has nothing
1001        /// to do with the `ORDER BY` in the `OVER`, which lays the partition out.
1002        order: Slice,
1003        /// The window itself, into `Ast::windows`.
1004        spec: WindowRef,
1005    },
1006    /// `CAST(x AS t)` or `TRY_CAST(x AS t)`.
1007    Cast {
1008        /// What is being cast.
1009        operand: ExprRef,
1010        /// The target type, as the text it was written with. Parsing it is `rudb-common`'s job and
1011        /// doing it here would put the type system in the parser.
1012        ty: StrRef,
1013        /// Whether a failure yields null rather than an error.
1014        try_cast: bool,
1015    },
1016    /// `CASE`, searched or simple.
1017    Case {
1018        /// The operand of a simple `CASE x WHEN`, or `NONE` for a searched one.
1019        operand: ExprRef,
1020        /// The arms, as a run of [`CaseArm`].
1021        arms: Slice,
1022        /// The `ELSE`, or `NONE`.
1023        otherwise: ExprRef,
1024    },
1025    /// `x BETWEEN a AND b`.
1026    Between {
1027        /// What is being tested.
1028        operand: ExprRef,
1029        /// The lower bound.
1030        low: ExprRef,
1031        /// The upper bound.
1032        high: ExprRef,
1033        /// Whether it was written `NOT BETWEEN`.
1034        negated: bool,
1035    },
1036    /// `x IN (a, b, c)`.
1037    In {
1038        /// What is being tested.
1039        operand: ExprRef,
1040        /// The list, as a run of [`ExprRef`].
1041        list: Slice,
1042        /// Whether it was written `NOT IN`.
1043        negated: bool,
1044    },
1045    /// `x IN (SELECT ...)` or its negation.
1046    InSubquery {
1047        /// What is being tested.
1048        operand: ExprRef,
1049        /// The query producing the candidates.
1050        query: QueryRef,
1051        /// Whether it was written `NOT IN`.
1052        negated: bool,
1053    },
1054    /// `x op ANY (SELECT ...)` or `x op ALL (SELECT ...)`.
1055    QuantifiedSubquery {
1056        /// The value on the left of the comparison.
1057        operand: ExprRef,
1058        /// The comparison applied to each candidate.
1059        op: BinaryOp,
1060        /// The query producing the candidates.
1061        query: QueryRef,
1062        /// Whether the quantifier was `ALL` rather than `ANY`.
1063        all: bool,
1064    },
1065    /// `DEFAULT` where a value is written, which is the column's default and only means something
1066    /// as a whole item of an `INSERT`'s `VALUES` row.
1067    Default,
1068    /// A prepared statement parameter, written `?`, `?1`, `$1` or `$name`.
1069    Parameter {
1070        /// The identifier, which is the number for a positional one and the word for a named one.
1071        /// A bare `?` is numbered by where it was written, so the identifier is there either way.
1072        name: StrRef,
1073    },
1074    /// A bracketed list of expressions, `[a, b, c]`, which is a LIST value.
1075    List {
1076        /// The items, as a run of [`ExprRef`], in the order they were written.
1077        items: Slice,
1078    },
1079    /// `LAMBDA x, i: body`, a function written inline as the argument of one that takes it.
1080    ///
1081    /// It is an expression only so that it can sit in an argument list. Anywhere else it means
1082    /// nothing, and the binder says so in upstream's words rather than the parser refusing it,
1083    /// because upstream's parser accepts it anywhere too.
1084    Lambda {
1085        /// The parameter names, as a run of [`StrRef`], in the order they were written.
1086        params: Slice,
1087        /// What the function computes from them.
1088        body: ExprRef,
1089    },
1090    /// A braced struct, `{'a': 1, b: 2}`, which is a STRUCT value with the field names written.
1091    Struct {
1092        /// The field names, as a run of [`StrRef`], in the order they were written.
1093        names: Slice,
1094        /// The values, as a run of [`ExprRef`], one for each name.
1095        values: Slice,
1096    },
1097    /// A parenthesised list of more than one expression, which is a row value.
1098    Row {
1099        /// The items, as a run of [`ExprRef`].
1100        items: Slice,
1101    },
1102    /// A scalar subquery, `(SELECT ...)` where an expression is expected.
1103    Subquery {
1104        /// The query.
1105        query: QueryRef,
1106    },
1107    /// `EXISTS (SELECT ...)` or its negation.
1108    Exists {
1109        /// The query whose cardinality is tested.
1110        query: QueryRef,
1111        /// Whether `NOT` was written before `EXISTS`.
1112        negated: bool,
1113    },
1114}
1115
1116/// One `WHEN a THEN b`.
1117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1118pub struct CaseArm {
1119    /// The `WHEN`.
1120    pub when: ExprRef,
1121    /// The `THEN`.
1122    pub then: ExprRef,
1123}
1124
1125/// What a transaction statement asks for.
1126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1127pub enum Transaction {
1128    /// `BEGIN` or `START TRANSACTION`, and whether `READ ONLY` was written after it.
1129    Begin {
1130        /// Whether the transaction may not write.
1131        read_only: bool,
1132    },
1133    /// `COMMIT` or `END`.
1134    Commit,
1135    /// `ROLLBACK` or `ABORT`.
1136    Rollback,
1137}
1138
1139/// Which literal.
1140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1141pub enum LiteralKind {
1142    /// A number, kept as text because the width it wants depends on where it lands.
1143    Number,
1144    /// A string.
1145    String,
1146    /// A blob, kept as the text a blob prints as, which is the text a cast reads it back from.
1147    Blob,
1148    /// `NULL`.
1149    Null,
1150    /// `TRUE`.
1151    True,
1152    /// `FALSE`.
1153    False,
1154}
1155
1156/// A prefix or postfix operator.
1157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1158pub enum UnaryOp {
1159    /// `NOT x`.
1160    Not,
1161    /// `-x`.
1162    Negate,
1163    /// `+x`, which is a no-op that still has to survive to the binder so that `+'a'` errors.
1164    Plus,
1165    /// `~x`.
1166    BitNot,
1167    /// `x!`.
1168    Factorial,
1169    /// `x IS NULL` or `x ISNULL`.
1170    IsNull,
1171    /// `x IS NOT NULL` or `x NOTNULL`.
1172    IsNotNull,
1173    /// `x IS TRUE`.
1174    IsTrue,
1175    /// `x IS NOT TRUE`.
1176    IsNotTrue,
1177    /// `x IS FALSE`.
1178    IsFalse,
1179    /// `x IS NOT FALSE`.
1180    IsNotFalse,
1181    /// `x IS UNKNOWN`.
1182    IsUnknown,
1183    /// `x IS NOT UNKNOWN`.
1184    IsNotUnknown,
1185}
1186
1187/// An infix operator.
1188///
1189/// The list is the dialect and not a general idea of what operators are. `Named` is the one open
1190/// door, because `OperatorLiteral` in the grammar takes any run of operator characters that is not
1191/// already a token, and rejecting that here would reject SQL DuckDB accepts.
1192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1193pub enum BinaryOp {
1194    /// `OR`.
1195    Or,
1196    /// `AND`.
1197    And,
1198    /// `=` or `==`.
1199    Eq,
1200    /// `!=` or `<>`.
1201    NotEq,
1202    /// `<`.
1203    Lt,
1204    /// `>`.
1205    Gt,
1206    /// `<=`.
1207    LtEq,
1208    /// `>=`.
1209    GtEq,
1210    /// `IS DISTINCT FROM`.
1211    IsDistinctFrom,
1212    /// `IS NOT DISTINCT FROM`.
1213    IsNotDistinctFrom,
1214    /// `+`.
1215    Add,
1216    /// `-`.
1217    Subtract,
1218    /// `*`.
1219    Multiply,
1220    /// `/`.
1221    Divide,
1222    /// `//`, integer division.
1223    IntegerDivide,
1224    /// `%`.
1225    Modulo,
1226    /// `^` or `**`.
1227    Power,
1228    /// `&`.
1229    BitAnd,
1230    /// `|`.
1231    BitOr,
1232    /// `<<`.
1233    ShiftLeft,
1234    /// `>>`.
1235    ShiftRight,
1236    /// `||`.
1237    Concat,
1238    /// `LIKE` or `~~`.
1239    Like,
1240    /// `NOT LIKE` or `!~~`.
1241    NotLike,
1242    /// `ILIKE` or `~~*`.
1243    ILike,
1244    /// `NOT ILIKE` or `!~~*`.
1245    NotILike,
1246    /// `GLOB` or `~~~`.
1247    Glob,
1248    /// `SIMILAR TO`.
1249    SimilarTo,
1250    /// `NOT SIMILAR TO`.
1251    NotSimilarTo,
1252    /// `~`, a regex match.
1253    Regex,
1254    /// `!~`, a negated regex match.
1255    NotRegex,
1256    /// `~*`, a case insensitive regex match.
1257    RegexInsensitive,
1258    /// `!~*`, a negated case insensitive regex match.
1259    NotRegexInsensitive,
1260    /// `COLLATE`.
1261    Collate,
1262    /// `AT TIME ZONE`.
1263    AtTimeZone,
1264    /// `->`.
1265    Arrow,
1266    /// `->>`.
1267    LongArrow,
1268    /// `@>`, contains.
1269    Contains,
1270    /// `<@`, contained by.
1271    ContainedBy,
1272    /// `&&`, overlaps.
1273    Overlaps,
1274    /// `^@`, starts with.
1275    StartsWith,
1276    /// `<<=`, an inet operator.
1277    InetContainedByOrEq,
1278    /// `>>=`, an inet operator.
1279    InetContainsOrEq,
1280    /// An operator the dialect does not name, which DuckDB resolves as a binary function of that
1281    /// name. `a <=> b` is the shape.
1282    Named(StrRef),
1283}
1284
1285/// A parsed statement or script, with every arena it points into.
1286///
1287/// Cheap to clone, cheap to send, and self contained: no index in here refers to anything outside
1288/// it, and nothing in here borrows the query text. The text is copied into `strings` on the way in,
1289/// which costs one allocation per distinct identifier and buys an `Ast` that outlives the string it
1290/// came from.
1291#[derive(Debug, Clone, Default, PartialEq, Eq)]
1292pub struct Ast {
1293    /// The statements in the script, in order.
1294    pub statements: Vec<Statement>,
1295    /// The query arena.
1296    pub queries: Vec<Query>,
1297    /// Source ranges parallel to `queries`.
1298    pub query_spans: Vec<Span>,
1299    /// The select arena.
1300    pub selects: Vec<Select>,
1301    /// The expression arena.
1302    pub exprs: Vec<Expr>,
1303    /// Source ranges parallel to `exprs`.
1304    pub expr_spans: Vec<Span>,
1305    /// The from-item arena.
1306    pub sources: Vec<Source>,
1307    /// Interned text. Identifiers keep the case they were written in, because DuckDB does not fold
1308    /// it at any point, including for quoted identifiers.
1309    pub strings: Vec<String>,
1310    /// Backing store for every [`Slice`] of names.
1311    pub parts: Vec<StrRef>,
1312    /// Backing store for every [`Slice`] of expressions.
1313    pub expr_lists: Vec<ExprRef>,
1314    /// Backing store for every [`Slice`] of from items.
1315    pub source_lists: Vec<SourceRef>,
1316    /// Backing store for every [`Slice`] of target list entries.
1317    pub targets: Vec<Target>,
1318    /// Backing store for every [`Slice`] of order by entries.
1319    pub order_items: Vec<OrderItem>,
1320    /// Backing store for every [`Slice`] of case arms.
1321    pub case_arms: Vec<CaseArm>,
1322    /// The `CREATE TABLE` arena.
1323    pub create_tables: Vec<CreateTable>,
1324    /// Backing store for every [`Slice`] of constraints.
1325    pub constraints: Vec<Constraint>,
1326    /// The `CREATE VIEW` arena.
1327    pub create_views: Vec<CreateView>,
1328    /// The `DROP TABLE` arena.
1329    pub drop_tables: Vec<DropTable>,
1330    /// The `CREATE SCHEMA` and `DROP SCHEMA` arena.
1331    pub schemas: Vec<Schema>,
1332    /// The `CREATE SEQUENCE` and `DROP SEQUENCE` arena.
1333    pub sequences: Vec<Sequence>,
1334    /// The `CREATE TYPE` and `DROP TYPE` arena.
1335    pub types: Vec<TypeDef>,
1336    /// The `ALTER TABLE` and `ALTER VIEW` arena.
1337    pub alters: Vec<Alter>,
1338    /// The `CREATE INDEX` and `DROP INDEX` arena.
1339    pub indexes: Vec<Index>,
1340    /// The `INSERT` arena.
1341    pub inserts: Vec<Insert>,
1342    /// The `SET` and `RESET` arena.
1343    pub settings: Vec<Setting>,
1344    /// Backing store for every [`Slice`] of column definitions.
1345    pub column_defs: Vec<ColumnDef>,
1346    /// Backing store for every [`Slice`] of names, which is a name list rather than a name.
1347    pub name_lists: Vec<Slice>,
1348    /// Backing store for the rows of a `VALUES`, each of which is a run of expressions.
1349    pub rows: Vec<Slice>,
1350    /// The window arena, holding what was inside the parentheses of every `OVER`.
1351    pub windows: Vec<WindowSpec>,
1352    /// The materialised `WITH` arena.
1353    pub ctes: Vec<Cte>,
1354    /// Backing store for every [`Slice`] of materialised `WITH` indexes.
1355    pub cte_lists: Vec<u32>,
1356}
1357
1358impl Ast {
1359    /// The source range of an expression.
1360    pub fn expr_span(&self, expr: ExprRef) -> Span {
1361        self.expr_spans[expr as usize]
1362    }
1363
1364    /// The source range of a query.
1365    pub fn query_span(&self, query: QueryRef) -> Span {
1366        self.query_spans[query as usize]
1367    }
1368
1369    /// The text behind a [`StrRef`], or the empty string for `NONE`.
1370    pub fn string(&self, index: StrRef) -> &str {
1371        if index == NONE { "" } else { &self.strings[index as usize] }
1372    }
1373
1374    /// Every parameter identifier the statement uses, once each, in the order they were written.
1375    ///
1376    /// The arena is built as the walk goes, so its order is the written order, and a parameter used
1377    /// twice is one identifier here because it is one value to provide.
1378    pub fn parameters(&self) -> Vec<&str> {
1379        let mut found: Vec<&str> = Vec::new();
1380        for expr in &self.exprs {
1381            if let Expr::Parameter { name } = *expr {
1382                let name = self.string(name);
1383                if !found.contains(&name) {
1384                    found.push(name);
1385                }
1386            }
1387        }
1388        found
1389    }
1390
1391    /// The parts of a name, outermost first.
1392    pub fn name(&self, slice: Slice) -> impl Iterator<Item = &str> {
1393        self.parts[slice.range()].iter().map(|&part| self.string(part))
1394    }
1395
1396    /// A name written back out with dots between the parts, for error messages and tests.
1397    pub fn name_text(&self, slice: Slice) -> String {
1398        self.name(slice).collect::<Vec<_>>().join(".")
1399    }
1400
1401    /// One expression.
1402    pub fn expr(&self, index: ExprRef) -> Expr {
1403        self.exprs[index as usize]
1404    }
1405
1406    /// One from item.
1407    pub fn source(&self, index: SourceRef) -> Source {
1408        self.sources[index as usize]
1409    }
1410
1411    /// One query.
1412    pub fn query(&self, index: QueryRef) -> Query {
1413        self.queries[index as usize]
1414    }
1415
1416    /// One select block.
1417    pub fn select(&self, index: SelectRef) -> Select {
1418        self.selects[index as usize]
1419    }
1420
1421    /// One window.
1422    pub fn window(&self, index: WindowRef) -> WindowSpec {
1423        self.windows[index as usize]
1424    }
1425
1426    /// One materialised `WITH` definition.
1427    pub fn cte(&self, index: u32) -> Cte {
1428        self.ctes[index as usize]
1429    }
1430
1431    /// The materialised `WITH` definitions a query introduces, outermost first.
1432    pub fn cte_list(&self, slice: Slice) -> &[u32] {
1433        &self.cte_lists[slice.range()]
1434    }
1435
1436    /// The expressions of a list.
1437    pub fn expr_list(&self, slice: Slice) -> &[ExprRef] {
1438        &self.expr_lists[slice.range()]
1439    }
1440
1441    /// The from items of a list.
1442    pub fn source_list(&self, slice: Slice) -> &[SourceRef] {
1443        &self.source_lists[slice.range()]
1444    }
1445
1446    /// The entries of a target list.
1447    pub fn target_list(&self, slice: Slice) -> &[Target] {
1448        &self.targets[slice.range()]
1449    }
1450
1451    /// The entries of an order by list.
1452    pub fn order_list(&self, slice: Slice) -> &[OrderItem] {
1453        &self.order_items[slice.range()]
1454    }
1455
1456    /// The arms of a case.
1457    pub fn arm_list(&self, slice: Slice) -> &[CaseArm] {
1458        &self.case_arms[slice.range()]
1459    }
1460
1461    /// One `CREATE TABLE`.
1462    pub fn create_table(&self, index: CreateTableRef) -> CreateTable {
1463        self.create_tables[index as usize]
1464    }
1465
1466    /// One `CREATE VIEW`.
1467    pub fn create_view(&self, index: CreateViewRef) -> CreateView {
1468        self.create_views[index as usize]
1469    }
1470
1471    /// One `DROP TABLE`.
1472    pub fn drop_table(&self, index: DropTableRef) -> DropTable {
1473        self.drop_tables[index as usize]
1474    }
1475
1476    /// One `CREATE SCHEMA` or `DROP SCHEMA`.
1477    pub fn schema(&self, index: SchemaRef) -> Schema {
1478        self.schemas[index as usize]
1479    }
1480
1481    /// One `CREATE SEQUENCE` or `DROP SEQUENCE`.
1482    pub fn sequence(&self, index: SequenceRef) -> Sequence {
1483        self.sequences[index as usize]
1484    }
1485
1486    /// One `CREATE TYPE` or `DROP TYPE`.
1487    #[must_use]
1488    pub fn type_def(&self, index: TypeRef) -> TypeDef {
1489        self.types[index as usize]
1490    }
1491
1492    /// The `CREATE INDEX` or `DROP INDEX` at an index.
1493    #[must_use]
1494    pub fn index(&self, index: IndexRef) -> Index {
1495        self.indexes[index as usize]
1496    }
1497
1498    /// One `ALTER TABLE` or `ALTER VIEW`.
1499    pub fn alter(&self, index: AlterRef) -> Alter {
1500        self.alters[index as usize]
1501    }
1502
1503    /// One `INSERT`.
1504    pub fn insert(&self, index: InsertRef) -> Insert {
1505        self.inserts[index as usize]
1506    }
1507
1508    /// One `SET` or `RESET`.
1509    pub fn setting(&self, index: SettingRef) -> Setting {
1510        self.settings[index as usize]
1511    }
1512
1513    /// The column definitions of a `CREATE TABLE`.
1514    pub fn column_defs(&self, slice: Slice) -> &[ColumnDef] {
1515        &self.column_defs[slice.range()]
1516    }
1517
1518    /// The constraints of a run, in the order written.
1519    #[must_use]
1520    pub fn constraint_list(&self, slice: Slice) -> &[Constraint] {
1521        &self.constraints[slice.range()]
1522    }
1523
1524    /// The names of a name list, each of which is itself a run of parts.
1525    pub fn name_list(&self, slice: Slice) -> &[Slice] {
1526        &self.name_lists[slice.range()]
1527    }
1528
1529    /// The rows of a `VALUES`, each of which is itself a run of expressions.
1530    pub fn rows(&self, slice: Slice) -> &[Slice] {
1531        &self.rows[slice.range()]
1532    }
1533
1534    /// How many nodes the whole tree is, across every arena.
1535    ///
1536    /// The number to watch when the transformer changes. A parse tree of five thousand nodes that
1537    /// becomes an AST of thirty is the twenty precedence levels being thrown away, which is the
1538    /// whole reason this module exists.
1539    pub fn node_count(&self) -> usize {
1540        self.queries.len() + self.selects.len() + self.exprs.len() + self.sources.len()
1541    }
1542}