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