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