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