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