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