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 },
683 /// A function call with an `OVER` on the end of it.
684 ///
685 /// Kept apart from [`Expr::Function`] rather than given an optional window, because the two
686 /// are different things by every rule that applies to them: a window call is refused in a
687 /// `WHERE` and in a `HAVING`, it may not appear inside an aggregate, and it resolves against a
688 /// different set of names. A variant that only some of the code has to remember to look at is
689 /// a variant the rest of the code gets wrong.
690 Window {
691 /// The name, as a run of [`StrRef`], so `main.sum` is two parts.
692 name: Slice,
693 /// The arguments, as a run of [`ExprRef`].
694 args: Slice,
695 /// Whether the call said `DISTINCT`.
696 distinct: bool,
697 /// Whether the call said `IGNORE NULLS`. `RESPECT NULLS` is the default and is not kept,
698 /// because the reference binary drops it: a view written with it comes back without it.
699 ignore_nulls: bool,
700 /// The window itself, into `Ast::windows`.
701 spec: WindowRef,
702 },
703 /// `CAST(x AS t)` or `TRY_CAST(x AS t)`.
704 Cast {
705 /// What is being cast.
706 operand: ExprRef,
707 /// The target type, as the text it was written with. Parsing it is `rudb-common`'s job and
708 /// doing it here would put the type system in the parser.
709 ty: StrRef,
710 /// Whether a failure yields null rather than an error.
711 try_cast: bool,
712 },
713 /// `CASE`, searched or simple.
714 Case {
715 /// The operand of a simple `CASE x WHEN`, or `NONE` for a searched one.
716 operand: ExprRef,
717 /// The arms, as a run of [`CaseArm`].
718 arms: Slice,
719 /// The `ELSE`, or `NONE`.
720 otherwise: ExprRef,
721 },
722 /// `x BETWEEN a AND b`.
723 Between {
724 /// What is being tested.
725 operand: ExprRef,
726 /// The lower bound.
727 low: ExprRef,
728 /// The upper bound.
729 high: ExprRef,
730 /// Whether it was written `NOT BETWEEN`.
731 negated: bool,
732 },
733 /// `x IN (a, b, c)`.
734 In {
735 /// What is being tested.
736 operand: ExprRef,
737 /// The list, as a run of [`ExprRef`].
738 list: Slice,
739 /// Whether it was written `NOT IN`.
740 negated: bool,
741 },
742 /// `x IN (SELECT ...)` or its negation.
743 InSubquery {
744 /// What is being tested.
745 operand: ExprRef,
746 /// The query producing the candidates.
747 query: QueryRef,
748 /// Whether it was written `NOT IN`.
749 negated: bool,
750 },
751 /// `x op ANY (SELECT ...)` or `x op ALL (SELECT ...)`.
752 QuantifiedSubquery {
753 /// The value on the left of the comparison.
754 operand: ExprRef,
755 /// The comparison applied to each candidate.
756 op: BinaryOp,
757 /// The query producing the candidates.
758 query: QueryRef,
759 /// Whether the quantifier was `ALL` rather than `ANY`.
760 all: bool,
761 },
762 /// A prepared statement parameter, written `?`, `?1`, `$1` or `$name`.
763 Parameter {
764 /// The identifier, which is the number for a positional one and the word for a named one.
765 /// A bare `?` is numbered by where it was written, so the identifier is there either way.
766 name: StrRef,
767 },
768 /// A bracketed list of expressions, `[a, b, c]`, which is a LIST value.
769 List {
770 /// The items, as a run of [`ExprRef`], in the order they were written.
771 items: Slice,
772 },
773 /// A parenthesised list of more than one expression, which is a row value.
774 Row {
775 /// The items, as a run of [`ExprRef`].
776 items: Slice,
777 },
778 /// A scalar subquery, `(SELECT ...)` where an expression is expected.
779 Subquery {
780 /// The query.
781 query: QueryRef,
782 },
783 /// `EXISTS (SELECT ...)` or its negation.
784 Exists {
785 /// The query whose cardinality is tested.
786 query: QueryRef,
787 /// Whether `NOT` was written before `EXISTS`.
788 negated: bool,
789 },
790}
791
792/// One `WHEN a THEN b`.
793#[derive(Debug, Clone, Copy, PartialEq, Eq)]
794pub struct CaseArm {
795 /// The `WHEN`.
796 pub when: ExprRef,
797 /// The `THEN`.
798 pub then: ExprRef,
799}
800
801/// Which literal.
802#[derive(Debug, Clone, Copy, PartialEq, Eq)]
803pub enum LiteralKind {
804 /// A number, kept as text because the width it wants depends on where it lands.
805 Number,
806 /// A string.
807 String,
808 /// A blob, kept as the text a blob prints as, which is the text a cast reads it back from.
809 Blob,
810 /// `NULL`.
811 Null,
812 /// `TRUE`.
813 True,
814 /// `FALSE`.
815 False,
816}
817
818/// A prefix or postfix operator.
819#[derive(Debug, Clone, Copy, PartialEq, Eq)]
820pub enum UnaryOp {
821 /// `NOT x`.
822 Not,
823 /// `-x`.
824 Negate,
825 /// `+x`, which is a no-op that still has to survive to the binder so that `+'a'` errors.
826 Plus,
827 /// `~x`.
828 BitNot,
829 /// `x!`.
830 Factorial,
831 /// `x IS NULL` or `x ISNULL`.
832 IsNull,
833 /// `x IS NOT NULL` or `x NOTNULL`.
834 IsNotNull,
835 /// `x IS TRUE`.
836 IsTrue,
837 /// `x IS NOT TRUE`.
838 IsNotTrue,
839 /// `x IS FALSE`.
840 IsFalse,
841 /// `x IS NOT FALSE`.
842 IsNotFalse,
843 /// `x IS UNKNOWN`.
844 IsUnknown,
845 /// `x IS NOT UNKNOWN`.
846 IsNotUnknown,
847}
848
849/// An infix operator.
850///
851/// The list is the dialect and not a general idea of what operators are. `Named` is the one open
852/// door, because `OperatorLiteral` in the grammar takes any run of operator characters that is not
853/// already a token, and rejecting that here would reject SQL DuckDB accepts.
854#[derive(Debug, Clone, Copy, PartialEq, Eq)]
855pub enum BinaryOp {
856 /// `OR`.
857 Or,
858 /// `AND`.
859 And,
860 /// `=` or `==`.
861 Eq,
862 /// `!=` or `<>`.
863 NotEq,
864 /// `<`.
865 Lt,
866 /// `>`.
867 Gt,
868 /// `<=`.
869 LtEq,
870 /// `>=`.
871 GtEq,
872 /// `IS DISTINCT FROM`.
873 IsDistinctFrom,
874 /// `IS NOT DISTINCT FROM`.
875 IsNotDistinctFrom,
876 /// `+`.
877 Add,
878 /// `-`.
879 Subtract,
880 /// `*`.
881 Multiply,
882 /// `/`.
883 Divide,
884 /// `//`, integer division.
885 IntegerDivide,
886 /// `%`.
887 Modulo,
888 /// `^` or `**`.
889 Power,
890 /// `&`.
891 BitAnd,
892 /// `|`.
893 BitOr,
894 /// `<<`.
895 ShiftLeft,
896 /// `>>`.
897 ShiftRight,
898 /// `||`.
899 Concat,
900 /// `LIKE` or `~~`.
901 Like,
902 /// `NOT LIKE` or `!~~`.
903 NotLike,
904 /// `ILIKE` or `~~*`.
905 ILike,
906 /// `NOT ILIKE` or `!~~*`.
907 NotILike,
908 /// `GLOB` or `~~~`.
909 Glob,
910 /// `SIMILAR TO`.
911 SimilarTo,
912 /// `NOT SIMILAR TO`.
913 NotSimilarTo,
914 /// `~`, a regex match.
915 Regex,
916 /// `!~`, a negated regex match.
917 NotRegex,
918 /// `~*`, a case insensitive regex match.
919 RegexInsensitive,
920 /// `!~*`, a negated case insensitive regex match.
921 NotRegexInsensitive,
922 /// `COLLATE`.
923 Collate,
924 /// `AT TIME ZONE`.
925 AtTimeZone,
926 /// `->`.
927 Arrow,
928 /// `->>`.
929 LongArrow,
930 /// `@>`, contains.
931 Contains,
932 /// `<@`, contained by.
933 ContainedBy,
934 /// `&&`, overlaps.
935 Overlaps,
936 /// `^@`, starts with.
937 StartsWith,
938 /// `<<=`, an inet operator.
939 InetContainedByOrEq,
940 /// `>>=`, an inet operator.
941 InetContainsOrEq,
942 /// An operator the dialect does not name, which DuckDB resolves as a binary function of that
943 /// name. `a <=> b` is the shape.
944 Named(StrRef),
945}
946
947/// A parsed statement or script, with every arena it points into.
948///
949/// Cheap to clone, cheap to send, and self contained: no index in here refers to anything outside
950/// it, and nothing in here borrows the query text. The text is copied into `strings` on the way in,
951/// which costs one allocation per distinct identifier and buys an `Ast` that outlives the string it
952/// came from.
953#[derive(Debug, Clone, Default, PartialEq, Eq)]
954pub struct Ast {
955 /// The statements in the script, in order.
956 pub statements: Vec<Statement>,
957 /// The query arena.
958 pub queries: Vec<Query>,
959 /// Source ranges parallel to `queries`.
960 pub query_spans: Vec<Span>,
961 /// The select arena.
962 pub selects: Vec<Select>,
963 /// The expression arena.
964 pub exprs: Vec<Expr>,
965 /// Source ranges parallel to `exprs`.
966 pub expr_spans: Vec<Span>,
967 /// The from-item arena.
968 pub sources: Vec<Source>,
969 /// Interned text. Identifiers keep the case they were written in, because DuckDB does not fold
970 /// it at any point, including for quoted identifiers.
971 pub strings: Vec<String>,
972 /// Backing store for every [`Slice`] of names.
973 pub parts: Vec<StrRef>,
974 /// Backing store for every [`Slice`] of expressions.
975 pub expr_lists: Vec<ExprRef>,
976 /// Backing store for every [`Slice`] of from items.
977 pub source_lists: Vec<SourceRef>,
978 /// Backing store for every [`Slice`] of target list entries.
979 pub targets: Vec<Target>,
980 /// Backing store for every [`Slice`] of order by entries.
981 pub order_items: Vec<OrderItem>,
982 /// Backing store for every [`Slice`] of case arms.
983 pub case_arms: Vec<CaseArm>,
984 /// The `CREATE TABLE` arena.
985 pub create_tables: Vec<CreateTable>,
986 /// The `CREATE VIEW` arena.
987 pub create_views: Vec<CreateView>,
988 /// The `DROP TABLE` arena.
989 pub drop_tables: Vec<DropTable>,
990 /// The `INSERT` arena.
991 pub inserts: Vec<Insert>,
992 /// The `SET` and `RESET` arena.
993 pub settings: Vec<Setting>,
994 /// Backing store for every [`Slice`] of column definitions.
995 pub column_defs: Vec<ColumnDef>,
996 /// Backing store for every [`Slice`] of names, which is a name list rather than a name.
997 pub name_lists: Vec<Slice>,
998 /// Backing store for the rows of a `VALUES`, each of which is a run of expressions.
999 pub rows: Vec<Slice>,
1000 /// The window arena, holding what was inside the parentheses of every `OVER`.
1001 pub windows: Vec<WindowSpec>,
1002}
1003
1004impl Ast {
1005 /// The source range of an expression.
1006 pub fn expr_span(&self, expr: ExprRef) -> Span {
1007 self.expr_spans[expr as usize]
1008 }
1009
1010 /// The source range of a query.
1011 pub fn query_span(&self, query: QueryRef) -> Span {
1012 self.query_spans[query as usize]
1013 }
1014
1015 /// The text behind a [`StrRef`], or the empty string for `NONE`.
1016 pub fn string(&self, index: StrRef) -> &str {
1017 if index == NONE { "" } else { &self.strings[index as usize] }
1018 }
1019
1020 /// Every parameter identifier the statement uses, once each, in the order they were written.
1021 ///
1022 /// The arena is built as the walk goes, so its order is the written order, and a parameter used
1023 /// twice is one identifier here because it is one value to provide.
1024 pub fn parameters(&self) -> Vec<&str> {
1025 let mut found: Vec<&str> = Vec::new();
1026 for expr in &self.exprs {
1027 if let Expr::Parameter { name } = *expr {
1028 let name = self.string(name);
1029 if !found.contains(&name) {
1030 found.push(name);
1031 }
1032 }
1033 }
1034 found
1035 }
1036
1037 /// The parts of a name, outermost first.
1038 pub fn name(&self, slice: Slice) -> impl Iterator<Item = &str> {
1039 self.parts[slice.range()].iter().map(|&part| self.string(part))
1040 }
1041
1042 /// A name written back out with dots between the parts, for error messages and tests.
1043 pub fn name_text(&self, slice: Slice) -> String {
1044 self.name(slice).collect::<Vec<_>>().join(".")
1045 }
1046
1047 /// One expression.
1048 pub fn expr(&self, index: ExprRef) -> Expr {
1049 self.exprs[index as usize]
1050 }
1051
1052 /// One from item.
1053 pub fn source(&self, index: SourceRef) -> Source {
1054 self.sources[index as usize]
1055 }
1056
1057 /// One query.
1058 pub fn query(&self, index: QueryRef) -> Query {
1059 self.queries[index as usize]
1060 }
1061
1062 /// One select block.
1063 pub fn select(&self, index: SelectRef) -> Select {
1064 self.selects[index as usize]
1065 }
1066
1067 /// One window.
1068 pub fn window(&self, index: WindowRef) -> WindowSpec {
1069 self.windows[index as usize]
1070 }
1071
1072 /// The expressions of a list.
1073 pub fn expr_list(&self, slice: Slice) -> &[ExprRef] {
1074 &self.expr_lists[slice.range()]
1075 }
1076
1077 /// The from items of a list.
1078 pub fn source_list(&self, slice: Slice) -> &[SourceRef] {
1079 &self.source_lists[slice.range()]
1080 }
1081
1082 /// The entries of a target list.
1083 pub fn target_list(&self, slice: Slice) -> &[Target] {
1084 &self.targets[slice.range()]
1085 }
1086
1087 /// The entries of an order by list.
1088 pub fn order_list(&self, slice: Slice) -> &[OrderItem] {
1089 &self.order_items[slice.range()]
1090 }
1091
1092 /// The arms of a case.
1093 pub fn arm_list(&self, slice: Slice) -> &[CaseArm] {
1094 &self.case_arms[slice.range()]
1095 }
1096
1097 /// One `CREATE TABLE`.
1098 pub fn create_table(&self, index: CreateTableRef) -> CreateTable {
1099 self.create_tables[index as usize]
1100 }
1101
1102 /// One `CREATE VIEW`.
1103 pub fn create_view(&self, index: CreateViewRef) -> CreateView {
1104 self.create_views[index as usize]
1105 }
1106
1107 /// One `DROP TABLE`.
1108 pub fn drop_table(&self, index: DropTableRef) -> DropTable {
1109 self.drop_tables[index as usize]
1110 }
1111
1112 /// One `INSERT`.
1113 pub fn insert(&self, index: InsertRef) -> Insert {
1114 self.inserts[index as usize]
1115 }
1116
1117 /// One `SET` or `RESET`.
1118 pub fn setting(&self, index: SettingRef) -> Setting {
1119 self.settings[index as usize]
1120 }
1121
1122 /// The column definitions of a `CREATE TABLE`.
1123 pub fn column_defs(&self, slice: Slice) -> &[ColumnDef] {
1124 &self.column_defs[slice.range()]
1125 }
1126
1127 /// The names of a name list, each of which is itself a run of parts.
1128 pub fn name_list(&self, slice: Slice) -> &[Slice] {
1129 &self.name_lists[slice.range()]
1130 }
1131
1132 /// The rows of a `VALUES`, each of which is itself a run of expressions.
1133 pub fn rows(&self, slice: Slice) -> &[Slice] {
1134 &self.rows[slice.range()]
1135 }
1136
1137 /// How many nodes the whole tree is, across every arena.
1138 ///
1139 /// The number to watch when the transformer changes. A parse tree of five thousand nodes that
1140 /// becomes an AST of thirty is the twenty precedence levels being thrown away, which is the
1141 /// whole reason this module exists.
1142 pub fn node_count(&self) -> usize {
1143 self.queries.len() + self.selects.len() + self.exprs.len() + self.sources.len()
1144 }
1145}