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