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