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