Skip to main content

kumosql_sql/
ast.rs

1//! The GoogleSQL (BigQuery) syntax tree.
2//!
3//! Every node derives `Clone`, `PartialEq`, `Eq`, `Hash` and serde. Equality is structural and
4//! ignores pure spelling: an identifier's quoting and a string literal's quote style do not take
5//! part, so `` `a` `` equals `a` and `'x'` equals `"x"`.
6
7use serde::{Deserialize, Serialize};
8use std::hash::{Hash, Hasher};
9
10use crate::token::QuoteStyle;
11
12// ------------------------------------------------------------------------- names
13
14/// One identifier. `quoted` records whether it was written in backticks.
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct Ident {
17    pub value: String,
18    pub quoted: bool,
19}
20
21impl Ident {
22    pub fn new(value: impl Into<String>) -> Self {
23        Ident {
24            value: value.into(),
25            quoted: false,
26        }
27    }
28
29    pub fn quoted(value: impl Into<String>) -> Self {
30        Ident {
31            value: value.into(),
32            quoted: true,
33        }
34    }
35
36    /// Case-insensitive comparison, as BigQuery compares column names.
37    pub fn matches(&self, other: &str) -> bool {
38        self.value.eq_ignore_ascii_case(other)
39    }
40}
41
42impl PartialEq for Ident {
43    fn eq(&self, other: &Self) -> bool {
44        self.value == other.value
45    }
46}
47
48impl Eq for Ident {}
49
50impl Hash for Ident {
51    fn hash<H: Hasher>(&self, state: &mut H) {
52        self.value.hash(state);
53    }
54}
55
56impl From<&str> for Ident {
57    fn from(value: &str) -> Self {
58        Ident::new(value)
59    }
60}
61
62/// A dotted name: a table, routine or column path (`` `p.d.t` ``, `p.d.t`, `SAFE.DIVIDE`).
63#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
64pub struct ObjectName(pub Vec<Ident>);
65
66impl ObjectName {
67    pub fn new<I: Into<Ident>>(parts: impl IntoIterator<Item = I>) -> Self {
68        ObjectName(parts.into_iter().map(Into::into).collect())
69    }
70
71    /// The name split into its logical parts: a backtick-quoted part holding dots (`` `p.d.t` ``) is
72    /// several parts.
73    pub fn parts(&self) -> Vec<String> {
74        let mut parts = Vec::new();
75        for ident in &self.0 {
76            if ident.quoted && ident.value.contains('.') {
77                parts.extend(
78                    ident
79                        .value
80                        .split('.')
81                        .filter(|p| !p.is_empty())
82                        .map(str::to_string),
83                );
84            } else {
85                parts.push(ident.value.clone());
86            }
87        }
88        parts
89    }
90
91    /// The last part (a table's own name).
92    pub fn base_name(&self) -> String {
93        self.parts().pop().unwrap_or_default()
94    }
95
96    /// `p.d.t` with no quotes.
97    pub fn dotted(&self) -> String {
98        self.parts().join(".")
99    }
100
101    /// The name as a [`TableName`] (project, dataset, table).
102    pub fn table_name(&self) -> TableName {
103        TableName::from_parts(self.parts())
104    }
105}
106
107/// A table identity: `project.dataset.name`, with the leading parts optional.
108#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
109pub struct TableName {
110    pub project: Option<String>,
111    pub dataset: Option<String>,
112    pub name: String,
113}
114
115impl TableName {
116    pub fn new(name: impl Into<String>) -> Self {
117        TableName {
118            project: None,
119            dataset: None,
120            name: name.into(),
121        }
122    }
123
124    /// From parts as written; more than three parts keep the extra leading ones in `project`.
125    pub fn from_parts(mut parts: Vec<String>) -> Self {
126        let name = parts.pop().unwrap_or_default();
127        let dataset = parts.pop();
128        let project = if parts.is_empty() {
129            None
130        } else {
131            Some(parts.join("."))
132        };
133        TableName {
134            project,
135            dataset,
136            name,
137        }
138    }
139
140    /// Parse `a.b.c`, `` `a.b.c` `` or `` `a`.b ``.
141    pub fn parse(text: &str) -> Self {
142        let mut parts = Vec::new();
143        let mut current = String::new();
144        let mut quoted = false;
145        for ch in text.trim().chars() {
146            match ch {
147                '`' => quoted = !quoted,
148                '.' => {
149                    if !current.is_empty() {
150                        parts.push(std::mem::take(&mut current));
151                    }
152                }
153                c if c.is_whitespace() && !quoted => {}
154                c => current.push(c),
155            }
156        }
157        if !current.is_empty() {
158            parts.push(current);
159        }
160        TableName::from_parts(parts)
161    }
162
163    /// `project.dataset.name` without the missing parts.
164    pub fn dotted(&self) -> String {
165        let mut out = Vec::new();
166        if let Some(p) = &self.project {
167            out.push(p.as_str());
168        }
169        if let Some(d) = &self.dataset {
170            out.push(d.as_str());
171        }
172        out.push(self.name.as_str());
173        out.join(".")
174    }
175
176    /// The lower-cased dotted name: the key tables are compared by.
177    pub fn key(&self) -> String {
178        self.dotted().to_lowercase()
179    }
180
181    /// A name with no dataset, or in `_SESSION`: possibly a temporary table.
182    pub fn is_temp_name(&self) -> bool {
183        self.project.is_none()
184            && self
185                .dataset
186                .as_deref()
187                .is_none_or(|d| d.eq_ignore_ascii_case("_session"))
188    }
189}
190
191impl std::fmt::Display for TableName {
192    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193        f.write_str(&self.dotted())
194    }
195}
196
197// ------------------------------------------------------------------------ statements
198
199/// One GoogleSQL statement.
200#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
201pub enum Statement {
202    Query(Box<Query>),
203    CreateTable(Box<CreateTable>),
204    CreateView(Box<CreateView>),
205    CreateFunction(Box<CreateFunction>),
206    CreateTableFunction(Box<CreateTableFunction>),
207    CreateProcedure(Box<CreateProcedure>),
208    CreateSchema(Box<CreateSchema>),
209    Insert(Box<Insert>),
210    Update(Box<Update>),
211    Delete(Box<Delete>),
212    Merge(Box<Merge>),
213    Drop(Box<Drop>),
214    AlterTable(Box<AlterTable>),
215    Truncate {
216        name: ObjectName,
217    },
218    Declare {
219        names: Vec<Ident>,
220        data_type: Option<DataType>,
221        default: Option<Expr>,
222    },
223    Set {
224        targets: Vec<Expr>,
225        value: Expr,
226    },
227    BeginEnd {
228        label: Option<Ident>,
229        body: Vec<Statement>,
230        exception: Option<Vec<Statement>>,
231    },
232    If {
233        branches: Vec<ConditionalBlock>,
234        else_branch: Option<Vec<Statement>>,
235    },
236    Case {
237        operand: Option<Expr>,
238        branches: Vec<ConditionalBlock>,
239        else_branch: Option<Vec<Statement>>,
240    },
241    Loop {
242        label: Option<Ident>,
243        body: Vec<Statement>,
244    },
245    While {
246        label: Option<Ident>,
247        condition: Expr,
248        body: Vec<Statement>,
249    },
250    ForIn {
251        label: Option<Ident>,
252        variable: Ident,
253        query: Box<Query>,
254        body: Vec<Statement>,
255    },
256    Repeat {
257        label: Option<Ident>,
258        body: Vec<Statement>,
259        until: Expr,
260    },
261    /// `BREAK`, `LEAVE`, `CONTINUE`, `ITERATE` with an optional label.
262    Control {
263        kind: ControlKind,
264        label: Option<Ident>,
265    },
266    Return,
267    Raise {
268        message: Option<Expr>,
269    },
270    Call {
271        procedure: ObjectName,
272        args: Vec<Expr>,
273    },
274    ExecuteImmediate {
275        sql: Expr,
276        into: Vec<Ident>,
277        using: Vec<ExprWithAlias>,
278    },
279    Assert {
280        condition: Expr,
281        description: Option<Expr>,
282    },
283    Transaction(TransactionKind),
284    ExportData(Box<ExportData>),
285    LoadData(Box<LoadData>),
286    /// A statement this parser does not model (`GRANT`, `CREATE MODEL`, ...), kept as written.
287    Raw(String),
288}
289
290/// `cond THEN statements` of an `IF`/`ELSEIF` or a `CASE` statement's `WHEN`.
291#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
292pub struct ConditionalBlock {
293    pub condition: Expr,
294    pub body: Vec<Statement>,
295}
296
297#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
298pub enum ControlKind {
299    Break,
300    Leave,
301    Continue,
302    Iterate,
303}
304
305#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
306pub enum TransactionKind {
307    Begin,
308    Commit,
309    Rollback,
310}
311
312/// An expression with an optional `AS name`.
313#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
314pub struct ExprWithAlias {
315    pub expr: Expr,
316    pub alias: Option<Ident>,
317}
318
319/// `name = value` inside `OPTIONS(...)`.
320#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
321pub struct SqlOption {
322    pub name: Ident,
323    pub value: Expr,
324}
325
326#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
327pub enum TableKind {
328    Table,
329    External,
330    Snapshot,
331}
332
333/// `LIKE`, `COPY` or `CLONE` a table in `CREATE TABLE`.
334#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
335pub enum CopyKind {
336    Like,
337    Copy,
338    Clone,
339}
340
341#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
342pub struct TableCopy {
343    pub kind: CopyKind,
344    pub source: ObjectName,
345    pub system_time: Option<Expr>,
346}
347
348#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
349pub struct CreateTable {
350    pub or_replace: bool,
351    pub temporary: bool,
352    pub kind: TableKind,
353    pub if_not_exists: bool,
354    pub name: ObjectName,
355    pub columns: Vec<ColumnDef>,
356    pub constraints: Vec<TableConstraint>,
357    pub copy: Option<TableCopy>,
358    pub with_connection: Option<ObjectName>,
359    pub default_collate: Option<Expr>,
360    pub partition_by: Option<Expr>,
361    pub cluster_by: Vec<Expr>,
362    pub options: Vec<SqlOption>,
363    pub query: Option<Box<Query>>,
364}
365
366#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
367pub struct ColumnDef {
368    pub name: Ident,
369    pub data_type: DataType,
370    pub collate: Option<Expr>,
371    pub not_null: bool,
372    pub default: Option<Expr>,
373    pub primary_key: bool,
374    pub options: Vec<SqlOption>,
375}
376
377#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
378pub enum TableConstraint {
379    PrimaryKey {
380        columns: Vec<Ident>,
381        not_enforced: bool,
382    },
383    ForeignKey {
384        name: Option<Ident>,
385        columns: Vec<Ident>,
386        foreign_table: ObjectName,
387        referred_columns: Vec<Ident>,
388        not_enforced: bool,
389    },
390}
391
392#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
393pub struct ViewColumn {
394    pub name: Ident,
395    pub options: Vec<SqlOption>,
396}
397
398#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
399pub struct CreateView {
400    pub or_replace: bool,
401    pub materialized: bool,
402    pub if_not_exists: bool,
403    pub name: ObjectName,
404    pub columns: Vec<ViewColumn>,
405    pub partition_by: Option<Expr>,
406    pub cluster_by: Vec<Expr>,
407    pub options: Vec<SqlOption>,
408    pub query: Box<Query>,
409}
410
411/// A routine parameter type: a data type, `ANY TYPE`, `TABLE<...>` or `ANY TABLE`.
412#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
413pub enum ParamType {
414    Type(DataType),
415    AnyType,
416    Table(Vec<StructField>),
417    AnyTable,
418}
419
420#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
421pub struct FunctionParam {
422    pub name: Ident,
423    pub param_type: ParamType,
424    pub not_aggregate: bool,
425}
426
427#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
428pub enum FunctionBody {
429    /// `AS (expr)`
430    Expr(Expr),
431    /// `AS r"""js code"""` (with `LANGUAGE js`)
432    Code(Literal),
433    /// `REMOTE WITH CONNECTION c`
434    Remote(ObjectName),
435    /// No body (`LANGUAGE js OPTIONS(library=...)` only).
436    None,
437}
438
439#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
440pub struct CreateFunction {
441    pub or_replace: bool,
442    pub temporary: bool,
443    pub aggregate: bool,
444    pub if_not_exists: bool,
445    pub name: ObjectName,
446    pub params: Vec<FunctionParam>,
447    pub returns: Option<DataType>,
448    pub determinism: Option<bool>,
449    pub language: Option<Ident>,
450    pub options: Vec<SqlOption>,
451    pub body: FunctionBody,
452}
453
454#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
455pub struct CreateTableFunction {
456    pub or_replace: bool,
457    pub temporary: bool,
458    pub if_not_exists: bool,
459    pub name: ObjectName,
460    pub params: Vec<FunctionParam>,
461    pub returns: Option<Vec<StructField>>,
462    pub options: Vec<SqlOption>,
463    pub query: Box<Query>,
464}
465
466#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
467pub enum ParamMode {
468    In,
469    Out,
470    InOut,
471}
472
473#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
474pub struct ProcedureParam {
475    pub mode: Option<ParamMode>,
476    pub name: Ident,
477    pub param_type: ParamType,
478}
479
480#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
481pub struct CreateProcedure {
482    pub or_replace: bool,
483    pub if_not_exists: bool,
484    pub name: ObjectName,
485    pub params: Vec<ProcedureParam>,
486    pub options: Vec<SqlOption>,
487    pub body: Vec<Statement>,
488    pub exception: Option<Vec<Statement>>,
489}
490
491#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
492pub struct CreateSchema {
493    pub if_not_exists: bool,
494    pub name: ObjectName,
495    pub default_collate: Option<Expr>,
496    pub options: Vec<SqlOption>,
497}
498
499#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
500pub enum InsertSource {
501    Values(Vec<Vec<Expr>>),
502    Query(Box<Query>),
503}
504
505#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
506pub struct Insert {
507    pub table: ObjectName,
508    pub columns: Vec<Ident>,
509    pub source: InsertSource,
510}
511
512/// `target = value` in `UPDATE ... SET` and `MERGE ... UPDATE SET`; the target is a path (`a.b`).
513#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
514pub struct Assignment {
515    pub target: Vec<Ident>,
516    pub value: Expr,
517}
518
519#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
520pub struct Update {
521    pub table: ObjectName,
522    pub alias: Option<Ident>,
523    pub assignments: Vec<Assignment>,
524    pub from: Vec<TableWithJoins>,
525    pub selection: Option<Expr>,
526}
527
528#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
529pub struct Delete {
530    pub table: ObjectName,
531    pub alias: Option<Ident>,
532    pub selection: Option<Expr>,
533}
534
535#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
536pub enum MergeMatch {
537    Matched,
538    NotMatchedByTarget,
539    NotMatchedBySource,
540}
541
542#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
543pub enum MergeAction {
544    Update(Vec<Assignment>),
545    Delete,
546    /// `INSERT [(cols)] VALUES (...)`; `values` empty with `row` set is `INSERT ROW`.
547    Insert {
548        columns: Vec<Ident>,
549        values: Vec<Expr>,
550        row: bool,
551    },
552}
553
554#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
555pub struct MergeClause {
556    pub kind: MergeMatch,
557    /// `BY TARGET` was written.
558    pub explicit_by_target: bool,
559    pub condition: Option<Expr>,
560    pub action: MergeAction,
561}
562
563#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
564pub struct Merge {
565    pub target: ObjectName,
566    pub target_alias: Option<Ident>,
567    pub source: TableFactor,
568    pub on: Expr,
569    pub clauses: Vec<MergeClause>,
570}
571
572#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
573pub enum ObjectType {
574    Table,
575    ExternalTable,
576    SnapshotTable,
577    View,
578    MaterializedView,
579    Schema,
580    Function,
581    TableFunction,
582    Procedure,
583    Model,
584}
585
586impl ObjectType {
587    pub fn keyword(self) -> &'static str {
588        match self {
589            ObjectType::Table => "TABLE",
590            ObjectType::ExternalTable => "EXTERNAL TABLE",
591            ObjectType::SnapshotTable => "SNAPSHOT TABLE",
592            ObjectType::View => "VIEW",
593            ObjectType::MaterializedView => "MATERIALIZED VIEW",
594            ObjectType::Schema => "SCHEMA",
595            ObjectType::Function => "FUNCTION",
596            ObjectType::TableFunction => "TABLE FUNCTION",
597            ObjectType::Procedure => "PROCEDURE",
598            ObjectType::Model => "MODEL",
599        }
600    }
601
602    /// A table or a view: something that holds or shows rows.
603    pub fn is_relation(self) -> bool {
604        matches!(
605            self,
606            ObjectType::Table
607                | ObjectType::ExternalTable
608                | ObjectType::SnapshotTable
609                | ObjectType::View
610                | ObjectType::MaterializedView
611        )
612    }
613}
614
615#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
616pub struct Drop {
617    pub object_type: ObjectType,
618    pub if_exists: bool,
619    pub name: ObjectName,
620    /// `CASCADE` (true) or `RESTRICT` (false).
621    pub cascade: Option<bool>,
622}
623
624#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
625pub enum AlterColumnAction {
626    SetOptions(Vec<SqlOption>),
627    DropNotNull,
628    SetDataType(DataType),
629    SetDefault(Expr),
630    DropDefault,
631}
632
633#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
634pub enum AlterAction {
635    AddColumn {
636        if_not_exists: bool,
637        column: ColumnDef,
638    },
639    DropColumn {
640        if_exists: bool,
641        name: Ident,
642    },
643    RenameTo(ObjectName),
644    RenameColumn {
645        if_exists: bool,
646        from: Ident,
647        to: Ident,
648    },
649    SetOptions(Vec<SqlOption>),
650    SetDefaultCollate(Expr),
651    AlterColumn {
652        if_exists: bool,
653        name: Ident,
654        action: AlterColumnAction,
655    },
656}
657
658#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
659pub struct AlterTable {
660    pub object_type: ObjectType,
661    pub if_exists: bool,
662    pub name: ObjectName,
663    pub actions: Vec<AlterAction>,
664}
665
666#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
667pub struct ExportData {
668    pub connection: Option<ObjectName>,
669    pub options: Vec<SqlOption>,
670    pub query: Box<Query>,
671}
672
673/// `LOAD DATA {INTO|OVERWRITE} [TEMP TABLE] name ...`; the clauses after the name are kept as text.
674#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
675pub struct LoadData {
676    pub overwrite: bool,
677    pub temporary: bool,
678    pub table: ObjectName,
679    pub rest: String,
680}
681
682// --------------------------------------------------------------------------- queries
683
684/// A query: an optional `WITH`, a body, `ORDER BY`/`LIMIT`, then any pipe operators.
685#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
686pub struct Query {
687    pub with: Option<With>,
688    pub body: SetExpr,
689    pub order_by: Vec<OrderByExpr>,
690    pub limit: Option<Limit>,
691    pub pipes: Vec<PipeOperator>,
692}
693
694impl Query {
695    /// A query that is just `body`.
696    pub fn from_body(body: SetExpr) -> Self {
697        Query {
698            with: None,
699            body,
700            order_by: Vec::new(),
701            limit: None,
702            pipes: Vec::new(),
703        }
704    }
705
706    pub fn from_select(select: Select) -> Self {
707        Query::from_body(SetExpr::Select(Box::new(select)))
708    }
709
710    /// Whether the query uses pipe syntax (`FROM t |> ...`).
711    pub fn is_pipe(&self) -> bool {
712        !self.pipes.is_empty() || matches!(self.body, SetExpr::From(_))
713    }
714}
715
716#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
717pub struct With {
718    pub recursive: bool,
719    pub ctes: Vec<Cte>,
720}
721
722#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
723pub struct Cte {
724    pub name: Ident,
725    pub query: Box<Query>,
726}
727
728#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
729pub struct Limit {
730    pub count: Expr,
731    pub offset: Option<Expr>,
732}
733
734#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
735pub enum SetOperator {
736    Union,
737    Intersect,
738    Except,
739}
740
741impl SetOperator {
742    pub fn keyword(self) -> &'static str {
743        match self {
744            SetOperator::Union => "UNION",
745            SetOperator::Intersect => "INTERSECT",
746            SetOperator::Except => "EXCEPT",
747        }
748    }
749}
750
751#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
752pub enum SetQuantifier {
753    All,
754    Distinct,
755    /// Neither was written (only valid for some forms).
756    None,
757}
758
759/// `FULL`/`LEFT`/`INNER` before a set operator (column matching mode).
760#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
761pub enum SetOpMode {
762    Full,
763    Left,
764    Inner,
765}
766
767/// How a set operation lines up columns.
768#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
769pub enum Corresponding {
770    /// `BY NAME [ON (cols)]`
771    ByName(Vec<Ident>),
772    /// `[STRICT] CORRESPONDING [BY (cols)]`
773    Corresponding { strict: bool, by: Vec<Ident> },
774}
775
776#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
777pub enum SetExpr {
778    Select(Box<Select>),
779    /// A parenthesized query.
780    Query(Box<Query>),
781    SetOperation {
782        op: SetOperator,
783        quantifier: SetQuantifier,
784        mode: Option<SetOpMode>,
785        corresponding: Option<Corresponding>,
786        left: Box<SetExpr>,
787        right: Box<SetExpr>,
788    },
789    /// The `FROM ...` that starts a pipe query.
790    From(Vec<TableWithJoins>),
791}
792
793#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
794pub enum SelectAs {
795    Struct,
796    Value,
797}
798
799#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
800pub struct Select {
801    pub distinct: bool,
802    pub select_as: Option<SelectAs>,
803    pub projection: Vec<SelectItem>,
804    pub from: Vec<TableWithJoins>,
805    pub where_clause: Option<Expr>,
806    pub group_by: Option<GroupBy>,
807    pub having: Option<Expr>,
808    pub qualify: Option<Expr>,
809    pub window: Vec<NamedWindow>,
810}
811
812impl Select {
813    pub fn new(projection: Vec<SelectItem>) -> Self {
814        Select {
815            distinct: false,
816            select_as: None,
817            projection,
818            from: Vec::new(),
819            where_clause: None,
820            group_by: None,
821            having: None,
822            qualify: None,
823            window: Vec::new(),
824        }
825    }
826}
827
828#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
829pub struct WildcardOptions {
830    pub except: Vec<Ident>,
831    pub replace: Vec<ExprWithAlias>,
832}
833
834#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
835pub enum SelectItem {
836    Expr {
837        expr: Expr,
838        alias: Option<Ident>,
839    },
840    Wildcard(WildcardOptions),
841    /// `t.*`, `s.f.*`, `(expr).*`
842    QualifiedWildcard {
843        qualifier: Expr,
844        options: WildcardOptions,
845    },
846}
847
848impl SelectItem {
849    pub fn expr(expr: Expr, alias: Option<&str>) -> Self {
850        SelectItem::Expr {
851            expr,
852            alias: alias.map(Ident::new),
853        }
854    }
855
856    /// The name this item gives its column: the alias, or the last part of a column reference.
857    pub fn output_name(&self) -> Option<String> {
858        match self {
859            SelectItem::Expr {
860                alias: Some(alias), ..
861            } => Some(alias.value.clone()),
862            SelectItem::Expr { expr, .. } => expr.implicit_name(),
863            _ => None,
864        }
865    }
866
867    pub fn is_star(&self) -> bool {
868        matches!(
869            self,
870            SelectItem::Wildcard(_) | SelectItem::QualifiedWildcard { .. }
871        )
872    }
873}
874
875#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
876pub enum GroupBy {
877    All,
878    Items(Vec<GroupByItem>),
879}
880
881#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
882pub enum GroupByItem {
883    Expr(Expr),
884    Rollup(Vec<Expr>),
885    Cube(Vec<Expr>),
886    GroupingSets(Vec<GroupByItem>),
887    /// `()`: the grand total grouping set.
888    Empty,
889}
890
891#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
892pub struct NamedWindow {
893    pub name: Ident,
894    pub spec: WindowSpec,
895}
896
897#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
898pub struct OrderByExpr {
899    pub expr: Expr,
900    pub collate: Option<Expr>,
901    /// `Some(true)` ASC, `Some(false)` DESC.
902    pub asc: Option<bool>,
903    /// `Some(true)` NULLS FIRST, `Some(false)` NULLS LAST.
904    pub nulls_first: Option<bool>,
905}
906
907impl OrderByExpr {
908    pub fn new(expr: Expr) -> Self {
909        OrderByExpr {
910            expr,
911            collate: None,
912            asc: None,
913            nulls_first: None,
914        }
915    }
916}
917
918// ------------------------------------------------------------------------ FROM items
919
920#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
921pub struct TableWithJoins {
922    pub relation: TableFactor,
923    pub joins: Vec<Join>,
924}
925
926impl TableWithJoins {
927    pub fn table(name: ObjectName) -> Self {
928        TableWithJoins {
929            relation: TableFactor::table(name, None),
930            joins: Vec::new(),
931        }
932    }
933}
934
935#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
936pub enum JoinKind {
937    Inner,
938    Left,
939    Right,
940    Full,
941    Cross,
942}
943
944#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
945pub enum JoinConstraint {
946    On(Expr),
947    Using(Vec<Ident>),
948    None,
949}
950
951#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
952pub struct Join {
953    pub kind: JoinKind,
954    pub natural: bool,
955    pub relation: TableFactor,
956    pub constraint: JoinConstraint,
957}
958
959#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
960pub enum SampleUnit {
961    Percent,
962    Rows,
963}
964
965#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
966pub struct TableSample {
967    pub method: Ident,
968    pub size: Expr,
969    pub unit: SampleUnit,
970}
971
972#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
973pub struct UnpivotColumns {
974    pub columns: Vec<Ident>,
975    pub alias: Option<Expr>,
976}
977
978#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
979pub enum TableFactor {
980    Table {
981        name: ObjectName,
982        alias: Option<Ident>,
983        system_time: Option<Expr>,
984        sample: Option<TableSample>,
985    },
986    Derived {
987        subquery: Box<Query>,
988        alias: Option<Ident>,
989        sample: Option<TableSample>,
990    },
991    Unnest {
992        array: Box<Expr>,
993        alias: Option<Ident>,
994        /// `WITH OFFSET [AS name]`: `Some(None)` without a name.
995        with_offset: Option<Option<Ident>>,
996    },
997    /// A table-valued function call (`ML.PREDICT(MODEL m, TABLE t)`, `tvf(1, TABLE t)`).
998    TableFunction {
999        function: Function,
1000        alias: Option<Ident>,
1001    },
1002    NestedJoin {
1003        table: Box<TableWithJoins>,
1004        alias: Option<Ident>,
1005    },
1006    Pivot {
1007        table: Box<TableFactor>,
1008        aggregates: Vec<ExprWithAlias>,
1009        value_column: Box<Expr>,
1010        values: Vec<ExprWithAlias>,
1011        alias: Option<Ident>,
1012    },
1013    Unpivot {
1014        table: Box<TableFactor>,
1015        include_nulls: Option<bool>,
1016        value_columns: Vec<Ident>,
1017        name_column: Ident,
1018        columns: Vec<UnpivotColumns>,
1019        alias: Option<Ident>,
1020    },
1021    /// `table MATCH_RECOGNIZE (...)`
1022    MatchRecognize {
1023        table: Box<TableFactor>,
1024        spec: Box<MatchRecognize>,
1025        alias: Option<Ident>,
1026    },
1027    /// `table ALIGN (...)`
1028    Align {
1029        table: Box<TableFactor>,
1030        spec: Box<Align>,
1031        alias: Option<Ident>,
1032    },
1033}
1034
1035impl TableFactor {
1036    pub fn table(name: ObjectName, alias: Option<Ident>) -> Self {
1037        TableFactor::Table {
1038            name,
1039            alias,
1040            system_time: None,
1041            sample: None,
1042        }
1043    }
1044
1045    pub fn alias(&self) -> Option<&Ident> {
1046        match self {
1047            TableFactor::Table { alias, .. }
1048            | TableFactor::Derived { alias, .. }
1049            | TableFactor::Unnest { alias, .. }
1050            | TableFactor::TableFunction { alias, .. }
1051            | TableFactor::NestedJoin { alias, .. }
1052            | TableFactor::Pivot { alias, .. }
1053            | TableFactor::Unpivot { alias, .. }
1054            | TableFactor::MatchRecognize { alias, .. }
1055            | TableFactor::Align { alias, .. } => alias.as_ref(),
1056        }
1057    }
1058
1059    pub fn set_alias(&mut self, new: Option<Ident>) {
1060        match self {
1061            TableFactor::Table { alias, .. }
1062            | TableFactor::Derived { alias, .. }
1063            | TableFactor::Unnest { alias, .. }
1064            | TableFactor::TableFunction { alias, .. }
1065            | TableFactor::NestedJoin { alias, .. }
1066            | TableFactor::Pivot { alias, .. }
1067            | TableFactor::Unpivot { alias, .. }
1068            | TableFactor::MatchRecognize { alias, .. }
1069            | TableFactor::Align { alias, .. } => *alias = new,
1070        }
1071    }
1072}
1073
1074// ------------------------------------------------------------------------ pipe syntax
1075
1076/// An expression item of `|> AGGREGATE` or its `GROUP BY`, with optional alias and order.
1077#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1078pub struct PipeExprItem {
1079    pub expr: Expr,
1080    pub alias: Option<Ident>,
1081    /// `Some(true)` ASC, `Some(false)` DESC.
1082    pub asc: Option<bool>,
1083    pub nulls_first: Option<bool>,
1084}
1085
1086#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1087pub enum PipeOperator {
1088    Where(Expr),
1089    Select {
1090        distinct: bool,
1091        select_as: Option<SelectAs>,
1092        items: Vec<SelectItem>,
1093    },
1094    Extend(Vec<SelectItem>),
1095    Set(Vec<Assignment>),
1096    Drop(Vec<Ident>),
1097    Rename(Vec<(Ident, Ident)>),
1098    As(Ident),
1099    Aggregate {
1100        items: Vec<PipeExprItem>,
1101        group_by: Vec<PipeExprItem>,
1102        /// `GROUP AND ORDER BY`
1103        group_and_order: bool,
1104    },
1105    Join(Join),
1106    OrderBy(Vec<OrderByExpr>),
1107    Limit(Limit),
1108    SetOperation {
1109        op: SetOperator,
1110        quantifier: SetQuantifier,
1111        mode: Option<SetOpMode>,
1112        corresponding: Option<Corresponding>,
1113        queries: Vec<Query>,
1114    },
1115    Call {
1116        function: Function,
1117        alias: Option<Ident>,
1118    },
1119    Distinct,
1120    TableSample(TableSample),
1121    Pivot {
1122        aggregates: Vec<ExprWithAlias>,
1123        value_column: Box<Expr>,
1124        values: Vec<ExprWithAlias>,
1125        alias: Option<Ident>,
1126    },
1127    Unpivot {
1128        include_nulls: Option<bool>,
1129        value_columns: Vec<Ident>,
1130        name_column: Ident,
1131        columns: Vec<UnpivotColumns>,
1132        alias: Option<Ident>,
1133    },
1134    Window(Vec<SelectItem>),
1135    Assert {
1136        condition: Expr,
1137        payload: Vec<Expr>,
1138    },
1139    /// `|> MATCH_RECOGNIZE (...) [AS alias]`
1140    MatchRecognize {
1141        spec: Box<MatchRecognize>,
1142        alias: Option<Ident>,
1143    },
1144    /// `|> ALIGN (...) [AS alias]`
1145    Align {
1146        spec: Box<Align>,
1147        alias: Option<Ident>,
1148    },
1149}
1150
1151// ------------------------------------------------------------------------ MATCH_RECOGNIZE and ALIGN
1152
1153/// `MATCH_RECOGNIZE (...)`: row pattern recognition over an ordered input. BigQuery returns one row per match:
1154/// the `PARTITION BY` columns, then the `MEASURES`.
1155#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1156pub struct MatchRecognize {
1157    pub partition_by: Vec<Expr>,
1158    pub order_by: Vec<OrderByExpr>,
1159    /// `MEASURES expr AS name, ...`: every measure is named.
1160    pub measures: Vec<(Expr, Ident)>,
1161    pub after_match: Option<AfterMatchSkip>,
1162    pub pattern: RowPattern,
1163    /// `DEFINE symbol AS condition, ...`; a symbol the pattern uses without a definition matches every row.
1164    pub define: Vec<(Ident, Expr)>,
1165    pub options: Vec<SqlOption>,
1166}
1167
1168impl MatchRecognize {
1169    /// The pattern variables: those of `PATTERN` in order of first use, then any only `DEFINE` names.
1170    pub fn variables(&self) -> Vec<Ident> {
1171        let mut out: Vec<Ident> = Vec::new();
1172        let mut push = |i: &Ident| {
1173            if !out.iter().any(|o| o.value.eq_ignore_ascii_case(&i.value)) {
1174                out.push(i.clone());
1175            }
1176        };
1177        self.pattern.symbols().into_iter().for_each(&mut push);
1178        self.define.iter().for_each(|(i, _)| push(i));
1179        out
1180    }
1181
1182    /// Every expression of the clause, in source order.
1183    pub fn exprs(&self) -> Vec<&Expr> {
1184        let mut out: Vec<&Expr> = self.partition_by.iter().collect();
1185        out.extend(self.order_by.iter().map(|o| &o.expr));
1186        out.extend(self.measures.iter().map(|(e, _)| e));
1187        out.extend(self.define.iter().map(|(_, e)| e));
1188        out.extend(self.options.iter().map(|o| &o.value));
1189        out
1190    }
1191
1192    pub fn exprs_mut(&mut self) -> Vec<&mut Expr> {
1193        let mut out: Vec<&mut Expr> = self.partition_by.iter_mut().collect();
1194        out.extend(self.order_by.iter_mut().map(|o| &mut o.expr));
1195        out.extend(self.measures.iter_mut().map(|(e, _)| e));
1196        out.extend(self.define.iter_mut().map(|(_, e)| e));
1197        out.extend(self.options.iter_mut().map(|o| &mut o.value));
1198        out
1199    }
1200}
1201
1202/// `AFTER MATCH SKIP ...`
1203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1204pub enum AfterMatchSkip {
1205    /// `PAST LAST ROW` (the default)
1206    PastLastRow,
1207    /// `TO NEXT ROW`
1208    ToNextRow,
1209}
1210
1211/// A `PATTERN` of `MATCH_RECOGNIZE`.
1212#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1213pub enum RowPattern {
1214    /// `()`
1215    Empty,
1216    Symbol(Ident),
1217    /// `^`: the start of the partition.
1218    Start,
1219    Concat(Vec<RowPattern>),
1220    Alternation(Vec<RowPattern>),
1221    Group(Box<RowPattern>),
1222    Quantified {
1223        pattern: Box<RowPattern>,
1224        quantifier: PatternQuantifier,
1225        /// A trailing `?`: as few repetitions as possible.
1226        reluctant: bool,
1227    },
1228}
1229
1230impl RowPattern {
1231    /// The symbols in order of first appearance (each once, compared case-insensitively).
1232    pub fn symbols(&self) -> Vec<&Ident> {
1233        fn walk<'a>(p: &'a RowPattern, out: &mut Vec<&'a Ident>) {
1234            match p {
1235                RowPattern::Empty | RowPattern::Start => {}
1236                RowPattern::Symbol(i) => {
1237                    if !out.iter().any(|o| o.value.eq_ignore_ascii_case(&i.value)) {
1238                        out.push(i);
1239                    }
1240                }
1241                RowPattern::Concat(items) | RowPattern::Alternation(items) => {
1242                    items.iter().for_each(|i| walk(i, out))
1243                }
1244                RowPattern::Group(inner) => walk(inner, out),
1245                RowPattern::Quantified { pattern, .. } => walk(pattern, out),
1246            }
1247        }
1248        let mut out = Vec::new();
1249        walk(self, &mut out);
1250        out
1251    }
1252}
1253
1254/// A row pattern quantifier.
1255#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1256pub enum PatternQuantifier {
1257    /// `*`
1258    ZeroOrMore,
1259    /// `+`
1260    OneOrMore,
1261    /// `?`
1262    ZeroOrOne,
1263    /// `{n}`
1264    Exactly(u64),
1265    /// `{n,}`, `{,m}` or `{n,m}`
1266    Range { min: Option<u64>, max: Option<u64> },
1267}
1268
1269/// `ALIGN (...)`: time-series alignment of an input to a regular grid of periods. The output is the `PARTITION BY`
1270/// columns, then the `METRICS`, then the aligned timestamp column.
1271#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1272pub struct Align {
1273    /// `TIMESTAMP column`: the input column to align (`timestamp` when not given).
1274    pub timestamp: Option<Ident>,
1275    /// `TIMESTAMP column AS name`
1276    pub timestamp_alias: Option<Ident>,
1277    /// `PERIOD interval`
1278    pub period: Expr,
1279    /// `ORIGIN EPOCH` or `ORIGIN timestamp`
1280    pub origin: Option<Expr>,
1281    /// `OUTPUT ...`, kept as written.
1282    pub output: Option<String>,
1283    pub partition_by: Vec<ExprWithAlias>,
1284    pub metrics: Vec<AlignMetric>,
1285}
1286
1287impl Align {
1288    /// The name of the aligned timestamp column of the output.
1289    pub fn output_timestamp_name(&self) -> String {
1290        self.timestamp_alias
1291            .as_ref()
1292            .or(self.timestamp.as_ref())
1293            .map(|i| i.value.clone())
1294            .unwrap_or_else(|| "timestamp".to_string())
1295    }
1296
1297    pub fn exprs(&self) -> Vec<&Expr> {
1298        let mut out = vec![&self.period];
1299        out.extend(self.origin.iter());
1300        out.extend(self.partition_by.iter().map(|p| &p.expr));
1301        out.extend(self.metrics.iter().map(|m| &m.expr));
1302        out
1303    }
1304
1305    pub fn exprs_mut(&mut self) -> Vec<&mut Expr> {
1306        let mut out = vec![&mut self.period];
1307        out.extend(self.origin.iter_mut());
1308        out.extend(self.partition_by.iter_mut().map(|p| &mut p.expr));
1309        out.extend(self.metrics.iter_mut().map(|m| &mut m.expr));
1310        out
1311    }
1312}
1313
1314/// One `METRICS` item of `ALIGN`.
1315#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1316pub struct AlignMetric {
1317    pub expr: Expr,
1318    /// `WITHIN (...)` after the metric's aggregate, kept as written without its parentheses.
1319    pub within: Option<String>,
1320    pub alias: Option<Ident>,
1321}
1322
1323// ------------------------------------------------------------------------ expressions
1324
1325#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1326pub enum UnaryOperator {
1327    Not,
1328    Minus,
1329    Plus,
1330    BitNot,
1331}
1332
1333#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1334pub enum BinaryOperator {
1335    Or,
1336    And,
1337    Eq,
1338    NotEq,
1339    Lt,
1340    LtEq,
1341    Gt,
1342    GtEq,
1343    BitOr,
1344    BitXor,
1345    BitAnd,
1346    ShiftLeft,
1347    ShiftRight,
1348    Plus,
1349    Minus,
1350    Multiply,
1351    Divide,
1352    Concat,
1353}
1354
1355impl BinaryOperator {
1356    pub fn as_str(self) -> &'static str {
1357        match self {
1358            BinaryOperator::Or => "OR",
1359            BinaryOperator::And => "AND",
1360            BinaryOperator::Eq => "=",
1361            BinaryOperator::NotEq => "!=",
1362            BinaryOperator::Lt => "<",
1363            BinaryOperator::LtEq => "<=",
1364            BinaryOperator::Gt => ">",
1365            BinaryOperator::GtEq => ">=",
1366            BinaryOperator::BitOr => "|",
1367            BinaryOperator::BitXor => "^",
1368            BinaryOperator::BitAnd => "&",
1369            BinaryOperator::ShiftLeft => "<<",
1370            BinaryOperator::ShiftRight => ">>",
1371            BinaryOperator::Plus => "+",
1372            BinaryOperator::Minus => "-",
1373            BinaryOperator::Multiply => "*",
1374            BinaryOperator::Divide => "/",
1375            BinaryOperator::Concat => "||",
1376        }
1377    }
1378
1379    /// Binding power: higher binds tighter.
1380    pub fn precedence(self) -> u8 {
1381        match self {
1382            BinaryOperator::Or => 1,
1383            BinaryOperator::And => 2,
1384            BinaryOperator::Eq
1385            | BinaryOperator::NotEq
1386            | BinaryOperator::Lt
1387            | BinaryOperator::LtEq
1388            | BinaryOperator::Gt
1389            | BinaryOperator::GtEq => 4,
1390            BinaryOperator::BitOr => 5,
1391            BinaryOperator::BitXor => 6,
1392            BinaryOperator::BitAnd => 7,
1393            BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => 8,
1394            BinaryOperator::Plus | BinaryOperator::Minus => 9,
1395            BinaryOperator::Multiply | BinaryOperator::Divide | BinaryOperator::Concat => 10,
1396        }
1397    }
1398}
1399
1400/// Precedence of comparison-level predicates (`IS`, `IN`, `LIKE`, `BETWEEN`).
1401pub const COMPARISON_PRECEDENCE: u8 = 4;
1402/// Precedence of prefix `NOT`.
1403pub const NOT_PRECEDENCE: u8 = 3;
1404/// Precedence of unary `-`, `+`, `~`.
1405pub const UNARY_PRECEDENCE: u8 = 11;
1406
1407#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1408pub enum Parameter {
1409    /// `@name`
1410    Named(String),
1411    /// `?`
1412    Positional,
1413    /// `@@name`
1414    System(String),
1415}
1416
1417/// A string or bytes literal. Equality compares the value only, not the quotes used.
1418#[derive(Debug, Clone, Serialize, Deserialize)]
1419pub struct StringLiteral {
1420    pub value: String,
1421    pub raw: bool,
1422    pub quote: QuoteStyle,
1423}
1424
1425impl StringLiteral {
1426    pub fn new(value: impl Into<String>) -> Self {
1427        StringLiteral {
1428            value: value.into(),
1429            raw: false,
1430            quote: QuoteStyle::Single,
1431        }
1432    }
1433}
1434
1435impl PartialEq for StringLiteral {
1436    fn eq(&self, other: &Self) -> bool {
1437        self.value == other.value
1438    }
1439}
1440
1441impl Eq for StringLiteral {}
1442
1443impl Hash for StringLiteral {
1444    fn hash<H: Hasher>(&self, state: &mut H) {
1445        self.value.hash(state);
1446    }
1447}
1448
1449#[derive(Debug, Clone, Serialize, Deserialize)]
1450pub struct BytesLiteral {
1451    pub value: Vec<u8>,
1452    pub raw: bool,
1453    pub quote: QuoteStyle,
1454}
1455
1456impl PartialEq for BytesLiteral {
1457    fn eq(&self, other: &Self) -> bool {
1458        self.value == other.value
1459    }
1460}
1461
1462impl Eq for BytesLiteral {}
1463
1464impl Hash for BytesLiteral {
1465    fn hash<H: Hasher>(&self, state: &mut H) {
1466        self.value.hash(state);
1467    }
1468}
1469
1470/// `INTERVAL value part [TO part]`.
1471#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1472pub struct IntervalLiteral {
1473    pub value: Box<Expr>,
1474    pub leading: String,
1475    pub trailing: Option<String>,
1476}
1477
1478#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1479pub enum Literal {
1480    Null,
1481    Bool(bool),
1482    /// As written (decimal or hexadecimal).
1483    Int(String),
1484    /// As written.
1485    Float(String),
1486    /// `NUMERIC '1.5'`
1487    Numeric(String),
1488    /// `BIGNUMERIC '1.5'`
1489    BigNumeric(String),
1490    String(StringLiteral),
1491    Bytes(BytesLiteral),
1492    Date(String),
1493    Datetime(String),
1494    Time(String),
1495    Timestamp(String),
1496    Interval(IntervalLiteral),
1497    Json(String),
1498    /// `RANGE<DATE> '[2020-01-01, 2021-01-01)'`
1499    Range {
1500        element: Box<DataType>,
1501        value: String,
1502    },
1503}
1504
1505impl Literal {
1506    pub fn string(value: impl Into<String>) -> Self {
1507        Literal::String(StringLiteral::new(value))
1508    }
1509
1510    pub fn int(value: i64) -> Self {
1511        Literal::Int(value.to_string())
1512    }
1513}
1514
1515#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1516pub enum SubscriptKind {
1517    /// `a[i]`
1518    Plain,
1519    Offset,
1520    Ordinal,
1521    SafeOffset,
1522    SafeOrdinal,
1523}
1524
1525impl SubscriptKind {
1526    pub fn keyword(self) -> Option<&'static str> {
1527        match self {
1528            SubscriptKind::Plain => None,
1529            SubscriptKind::Offset => Some("OFFSET"),
1530            SubscriptKind::Ordinal => Some("ORDINAL"),
1531            SubscriptKind::SafeOffset => Some("SAFE_OFFSET"),
1532            SubscriptKind::SafeOrdinal => Some("SAFE_ORDINAL"),
1533        }
1534    }
1535}
1536
1537#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1538pub enum LikeQuantifier {
1539    Any,
1540    Some,
1541    All,
1542}
1543
1544#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1545pub enum LikePatterns {
1546    /// `LIKE ANY ('a%', 'b%')`
1547    List(Vec<Expr>),
1548    /// `LIKE ALL UNNEST(array)`
1549    Unnest(Box<Expr>),
1550    /// `LIKE ANY (SELECT ...)`
1551    Subquery(Box<Query>),
1552}
1553
1554#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1555pub struct CaseWhen {
1556    pub condition: Expr,
1557    pub result: Expr,
1558}
1559
1560/// A field of `STRUCT(expr AS name)` or `(a, b)`.
1561#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1562pub struct StructExprField {
1563    pub expr: Expr,
1564    pub alias: Option<Ident>,
1565}
1566
1567#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1568pub enum NullTreatment {
1569    IgnoreNulls,
1570    RespectNulls,
1571}
1572
1573/// `HAVING MAX expr` / `HAVING MIN expr` in an aggregate.
1574#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1575pub struct HavingBound {
1576    pub max: bool,
1577    pub expr: Box<Expr>,
1578}
1579
1580#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1581pub enum FunctionArg {
1582    Expr(Expr),
1583    /// `COUNT(*)`
1584    Wildcard,
1585    /// `TABLE name` (table-valued function arguments)
1586    Table(ObjectName),
1587    /// `MODEL name` (`ML.*` functions)
1588    Model(ObjectName),
1589}
1590
1591#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1592pub struct Function {
1593    pub name: ObjectName,
1594    pub args: Vec<FunctionArg>,
1595    pub distinct: bool,
1596    pub null_treatment: Option<NullTreatment>,
1597    pub having: Option<HavingBound>,
1598    pub order_by: Vec<OrderByExpr>,
1599    pub limit: Option<Box<Expr>>,
1600    pub over: Option<WindowType>,
1601    /// Written without parentheses (`CURRENT_DATE`).
1602    pub no_parens: bool,
1603}
1604
1605impl Function {
1606    pub fn new(name: &str, args: Vec<Expr>) -> Self {
1607        Function {
1608            name: ObjectName::new([name]),
1609            args: args.into_iter().map(FunctionArg::Expr).collect(),
1610            distinct: false,
1611            null_treatment: None,
1612            having: None,
1613            order_by: Vec::new(),
1614            limit: None,
1615            over: None,
1616            no_parens: false,
1617        }
1618    }
1619
1620    /// The upper-cased dotted name (`SAFE.DIVIDE`).
1621    pub fn upper_name(&self) -> String {
1622        self.name.dotted().to_ascii_uppercase()
1623    }
1624}
1625
1626#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1627pub enum WindowType {
1628    Named(Ident),
1629    Spec(WindowSpec),
1630}
1631
1632#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
1633pub struct WindowSpec {
1634    pub base: Option<Ident>,
1635    pub partition_by: Vec<Expr>,
1636    pub order_by: Vec<OrderByExpr>,
1637    pub frame: Option<WindowFrame>,
1638}
1639
1640#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1641pub enum FrameUnits {
1642    Rows,
1643    Range,
1644}
1645
1646#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1647pub enum FrameBound {
1648    UnboundedPreceding,
1649    Preceding(Box<Expr>),
1650    CurrentRow,
1651    Following(Box<Expr>),
1652    UnboundedFollowing,
1653}
1654
1655#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1656pub struct WindowFrame {
1657    pub units: FrameUnits,
1658    pub start: FrameBound,
1659    pub end: Option<FrameBound>,
1660}
1661
1662/// A GoogleSQL expression.
1663#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1664pub enum Expr {
1665    Identifier(Ident),
1666    /// `a.b.c`: a column path, `table.column` or `struct.field`.
1667    CompoundIdentifier(Vec<Ident>),
1668    Literal(Literal),
1669    Parameter(Parameter),
1670    UnaryOp {
1671        op: UnaryOperator,
1672        expr: Box<Expr>,
1673    },
1674    BinaryOp {
1675        left: Box<Expr>,
1676        op: BinaryOperator,
1677        right: Box<Expr>,
1678    },
1679    IsNull {
1680        expr: Box<Expr>,
1681        negated: bool,
1682    },
1683    /// `IS [NOT] TRUE|FALSE|UNKNOWN` (`value` is `None` for UNKNOWN).
1684    IsBool {
1685        expr: Box<Expr>,
1686        value: Option<bool>,
1687        negated: bool,
1688    },
1689    IsDistinctFrom {
1690        left: Box<Expr>,
1691        right: Box<Expr>,
1692        negated: bool,
1693    },
1694    InList {
1695        expr: Box<Expr>,
1696        list: Vec<Expr>,
1697        negated: bool,
1698    },
1699    InSubquery {
1700        expr: Box<Expr>,
1701        subquery: Box<Query>,
1702        negated: bool,
1703    },
1704    InUnnest {
1705        expr: Box<Expr>,
1706        array: Box<Expr>,
1707        negated: bool,
1708    },
1709    Between {
1710        expr: Box<Expr>,
1711        negated: bool,
1712        low: Box<Expr>,
1713        high: Box<Expr>,
1714    },
1715    Like {
1716        expr: Box<Expr>,
1717        negated: bool,
1718        pattern: Box<Expr>,
1719    },
1720    /// `LIKE ANY|SOME|ALL (...)`
1721    LikeQuantified {
1722        expr: Box<Expr>,
1723        negated: bool,
1724        quantifier: LikeQuantifier,
1725        patterns: LikePatterns,
1726    },
1727    Case {
1728        operand: Option<Box<Expr>>,
1729        branches: Vec<CaseWhen>,
1730        else_result: Option<Box<Expr>>,
1731    },
1732    Cast {
1733        expr: Box<Expr>,
1734        data_type: DataType,
1735        safe: bool,
1736        format: Option<Box<Expr>>,
1737        time_zone: Option<Box<Expr>>,
1738    },
1739    Extract {
1740        part: Box<Expr>,
1741        expr: Box<Expr>,
1742        time_zone: Option<Box<Expr>>,
1743    },
1744    /// `STRUCT(...)`, `STRUCT<a INT64>(...)`
1745    Struct {
1746        fields: Vec<StructExprField>,
1747        typed: Option<Vec<StructField>>,
1748    },
1749    /// `(a, b)`: a struct constructor without the keyword.
1750    Tuple(Vec<Expr>),
1751    /// `[a, b]`, `ARRAY[a, b]`, `ARRAY<T>[a, b]`
1752    Array {
1753        elements: Vec<Expr>,
1754        element_type: Option<Box<DataType>>,
1755        keyword: bool,
1756    },
1757    /// `ARRAY(SELECT ...)`
1758    ArraySubquery(Box<Query>),
1759    Subscript {
1760        expr: Box<Expr>,
1761        kind: SubscriptKind,
1762        index: Box<Expr>,
1763    },
1764    /// `(expr).field`
1765    FieldAccess {
1766        expr: Box<Expr>,
1767        field: Ident,
1768    },
1769    Function(Box<Function>),
1770    Subquery(Box<Query>),
1771    Exists(Box<Query>),
1772    /// `WITH(a AS 1, b AS a + 1, a + b)`
1773    ScalarWith {
1774        bindings: Vec<(Ident, Expr)>,
1775        body: Box<Expr>,
1776    },
1777    /// `x -> x + 1`, `(a, b) -> a + b`
1778    Lambda {
1779        params: Vec<Ident>,
1780        body: Box<Expr>,
1781    },
1782    /// `name => value`
1783    NamedArg {
1784        name: Ident,
1785        value: Box<Expr>,
1786    },
1787    /// `( expr )`
1788    Nested(Box<Expr>),
1789    /// `DEFAULT` in `INSERT VALUES` and `UPDATE SET`.
1790    Default,
1791}
1792
1793impl Expr {
1794    pub fn ident(name: &str) -> Expr {
1795        Expr::Identifier(Ident::new(name))
1796    }
1797
1798    pub fn compound(parts: &[&str]) -> Expr {
1799        Expr::CompoundIdentifier(parts.iter().map(|p| Ident::new(*p)).collect())
1800    }
1801
1802    pub fn null() -> Expr {
1803        Expr::Literal(Literal::Null)
1804    }
1805
1806    pub fn binary(left: Expr, op: BinaryOperator, right: Expr) -> Expr {
1807        Expr::BinaryOp {
1808            left: Box::new(left),
1809            op,
1810            right: Box::new(right),
1811        }
1812    }
1813
1814    pub fn function(name: &str, args: Vec<Expr>) -> Expr {
1815        Expr::Function(Box::new(Function::new(name, args)))
1816    }
1817
1818    /// The column name an unaliased select item gets: the last part of a path.
1819    pub fn implicit_name(&self) -> Option<String> {
1820        match self {
1821            Expr::Identifier(ident) => Some(ident.value.clone()),
1822            Expr::CompoundIdentifier(parts) => parts.last().map(|p| p.value.clone()),
1823            Expr::FieldAccess { field, .. } => Some(field.value.clone()),
1824            Expr::Nested(inner) => inner.implicit_name(),
1825            _ => None,
1826        }
1827    }
1828
1829    /// The expression without any wrapping parentheses.
1830    pub fn unnested(&self) -> &Expr {
1831        let mut expr = self;
1832        while let Expr::Nested(inner) = expr {
1833            expr = inner;
1834        }
1835        expr
1836    }
1837
1838    /// The direct sub-expressions of this expression at the same query level: nothing inside a
1839    /// subquery (`(SELECT ...)`, `EXISTS`, `IN (SELECT ...)`, `ARRAY(SELECT ...)`). A function's
1840    /// arguments come first, then its `HAVING`, `ORDER BY`, `LIMIT` and the `PARTITION BY` /
1841    /// `ORDER BY` of its `OVER (...)`.
1842    pub fn children(&self) -> Vec<&Expr> {
1843        let mut out: Vec<&Expr> = Vec::new();
1844        match self {
1845            Expr::Identifier(_)
1846            | Expr::CompoundIdentifier(_)
1847            | Expr::Parameter(_)
1848            | Expr::Default
1849            | Expr::Subquery(_)
1850            | Expr::Exists(_)
1851            | Expr::ArraySubquery(_) => {}
1852            Expr::Literal(Literal::Interval(i)) => out.push(&i.value),
1853            Expr::Literal(_) => {}
1854            Expr::UnaryOp { expr, .. }
1855            | Expr::IsNull { expr, .. }
1856            | Expr::IsBool { expr, .. }
1857            | Expr::Nested(expr)
1858            | Expr::FieldAccess { expr, .. }
1859            | Expr::InSubquery { expr, .. } => out.push(expr),
1860            Expr::NamedArg { value, .. } => out.push(value),
1861            Expr::BinaryOp { left, right, .. } | Expr::IsDistinctFrom { left, right, .. } => {
1862                out.push(left);
1863                out.push(right);
1864            }
1865            Expr::InList { expr, list, .. } => {
1866                out.push(expr);
1867                out.extend(list.iter());
1868            }
1869            Expr::InUnnest { expr, array, .. } => {
1870                out.push(expr);
1871                out.push(array);
1872            }
1873            Expr::Between {
1874                expr, low, high, ..
1875            } => {
1876                out.push(expr);
1877                out.push(low);
1878                out.push(high);
1879            }
1880            Expr::Like { expr, pattern, .. } => {
1881                out.push(expr);
1882                out.push(pattern);
1883            }
1884            Expr::LikeQuantified { expr, patterns, .. } => {
1885                out.push(expr);
1886                match patterns {
1887                    LikePatterns::List(list) => out.extend(list.iter()),
1888                    LikePatterns::Unnest(e) => out.push(e),
1889                    LikePatterns::Subquery(_) => {}
1890                }
1891            }
1892            Expr::Case {
1893                operand,
1894                branches,
1895                else_result,
1896            } => {
1897                if let Some(e) = operand {
1898                    out.push(e);
1899                }
1900                for b in branches {
1901                    out.push(&b.condition);
1902                    out.push(&b.result);
1903                }
1904                if let Some(e) = else_result {
1905                    out.push(e);
1906                }
1907            }
1908            Expr::Cast {
1909                expr,
1910                format,
1911                time_zone,
1912                ..
1913            } => {
1914                out.push(expr);
1915                out.extend(format.iter().map(|b| &**b));
1916                out.extend(time_zone.iter().map(|b| &**b));
1917            }
1918            Expr::Extract {
1919                part,
1920                expr,
1921                time_zone,
1922            } => {
1923                out.push(part);
1924                out.push(expr);
1925                out.extend(time_zone.iter().map(|b| &**b));
1926            }
1927            Expr::Struct { fields, .. } => out.extend(fields.iter().map(|f| &f.expr)),
1928            Expr::Tuple(items)
1929            | Expr::Array {
1930                elements: items, ..
1931            } => out.extend(items.iter()),
1932            Expr::Subscript { expr, index, .. } => {
1933                out.push(expr);
1934                out.push(index);
1935            }
1936            Expr::Function(f) => {
1937                for arg in &f.args {
1938                    if let FunctionArg::Expr(e) = arg {
1939                        out.push(e);
1940                    }
1941                }
1942                if let Some(h) = &f.having {
1943                    out.push(&h.expr);
1944                }
1945                out.extend(f.order_by.iter().map(|o| &o.expr));
1946                if let Some(l) = &f.limit {
1947                    out.push(l);
1948                }
1949                if let Some(WindowType::Spec(spec)) = &f.over {
1950                    out.extend(spec.partition_by.iter());
1951                    out.extend(spec.order_by.iter().map(|o| &o.expr));
1952                }
1953            }
1954            Expr::ScalarWith { bindings, body } => {
1955                out.extend(bindings.iter().map(|(_, e)| e));
1956                out.push(body);
1957            }
1958            Expr::Lambda { body, .. } => out.push(body),
1959        }
1960        out
1961    }
1962
1963    /// Visit this expression and, while `f` returns `true` for a node, its children at the same
1964    /// query level (see [`Expr::children`]), depth first.
1965    pub fn walk_shallow<'e>(&'e self, f: &mut dyn FnMut(&'e Expr) -> bool) {
1966        if f(self) {
1967            for child in self.children() {
1968                child.walk_shallow(f);
1969            }
1970        }
1971    }
1972
1973    /// The column path of an identifier or a dotted identifier (`a`, `t.a`, `t.s.f`).
1974    pub fn column_parts(&self) -> Option<Vec<&str>> {
1975        match self {
1976            Expr::Identifier(ident) => Some(vec![ident.value.as_str()]),
1977            Expr::CompoundIdentifier(parts) => {
1978                Some(parts.iter().map(|p| p.value.as_str()).collect())
1979            }
1980            _ => None,
1981        }
1982    }
1983}
1984
1985// ------------------------------------------------------------------------ data types
1986
1987/// A field of `STRUCT<name type>` or a column of `TABLE<...>`.
1988#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1989pub struct StructField {
1990    pub name: Option<Ident>,
1991    pub data_type: DataType,
1992    pub not_null: bool,
1993    pub options: Vec<SqlOption>,
1994}
1995
1996impl StructField {
1997    pub fn new(name: Option<&str>, data_type: DataType) -> Self {
1998        StructField {
1999            name: name.map(Ident::new),
2000            data_type,
2001            not_null: false,
2002            options: Vec::new(),
2003        }
2004    }
2005}
2006
2007/// A GoogleSQL data type. Aliases (`INT`, `INTEGER`, `DECIMAL`, ...) map to the canonical type.
2008#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
2009pub enum DataType {
2010    Int64,
2011    Float64,
2012    Numeric(Option<(u32, Option<u32>)>),
2013    BigNumeric(Option<(u32, Option<u32>)>),
2014    Bool,
2015    String(Option<u64>),
2016    Bytes(Option<u64>),
2017    Date,
2018    Datetime,
2019    Time,
2020    Timestamp,
2021    Interval,
2022    Json,
2023    Geography,
2024    Array(Box<DataType>),
2025    Struct(Vec<StructField>),
2026    Range(Box<DataType>),
2027    /// Any other name (a user-defined or future type), upper-cased as written.
2028    Other(String),
2029}
2030
2031impl DataType {
2032    /// The canonical type for a simple type name, if it is one.
2033    pub fn from_name(name: &str) -> Option<DataType> {
2034        Some(match name.to_ascii_uppercase().as_str() {
2035            "INT64" | "INT" | "INTEGER" | "BIGINT" | "SMALLINT" | "TINYINT" | "BYTEINT" => {
2036                DataType::Int64
2037            }
2038            "FLOAT64" | "FLOAT" | "DOUBLE" => DataType::Float64,
2039            "NUMERIC" | "DECIMAL" => DataType::Numeric(None),
2040            "BIGNUMERIC" | "BIGDECIMAL" => DataType::BigNumeric(None),
2041            "BOOL" | "BOOLEAN" => DataType::Bool,
2042            "STRING" => DataType::String(None),
2043            "BYTES" => DataType::Bytes(None),
2044            "DATE" => DataType::Date,
2045            "DATETIME" => DataType::Datetime,
2046            "TIME" => DataType::Time,
2047            "TIMESTAMP" => DataType::Timestamp,
2048            "INTERVAL" => DataType::Interval,
2049            "JSON" => DataType::Json,
2050            "GEOGRAPHY" => DataType::Geography,
2051            _ => return None,
2052        })
2053    }
2054
2055    /// Whether `name` starts a data type.
2056    pub fn is_type_name(name: &str) -> bool {
2057        DataType::from_name(name).is_some()
2058            || matches!(
2059                name.to_ascii_uppercase().as_str(),
2060                "ARRAY" | "STRUCT" | "RANGE"
2061            )
2062    }
2063}
2064
2065// --------------------------------------------------------------------- traversal
2066
2067/// Something a query walk can visit: queries, selects, expressions and table factors.
2068pub trait Visitor {
2069    fn visit_query(&mut self, _query: &Query) {}
2070    fn visit_select(&mut self, _select: &Select) {}
2071    fn visit_expr(&mut self, _expr: &Expr) {}
2072    fn visit_table_factor(&mut self, _factor: &TableFactor) {}
2073    fn visit_statement(&mut self, _statement: &Statement) {}
2074}
2075
2076/// Walk every node of a statement, calling the visitor before descending.
2077pub fn walk_statement<V: Visitor>(statement: &Statement, v: &mut V) {
2078    v.visit_statement(statement);
2079    match statement {
2080        Statement::Query(q) => walk_query(q, v),
2081        Statement::CreateTable(c) => {
2082            for col in &c.columns {
2083                walk_column_def(col, v);
2084            }
2085            if let Some(copy) = &c.copy {
2086                if let Some(e) = &copy.system_time {
2087                    walk_expr(e, v);
2088                }
2089            }
2090            for e in c
2091                .default_collate
2092                .iter()
2093                .chain(c.partition_by.iter())
2094                .chain(c.cluster_by.iter())
2095            {
2096                walk_expr(e, v);
2097            }
2098            walk_options(&c.options, v);
2099            if let Some(q) = &c.query {
2100                walk_query(q, v);
2101            }
2102        }
2103        Statement::CreateView(c) => {
2104            for e in c.partition_by.iter().chain(c.cluster_by.iter()) {
2105                walk_expr(e, v);
2106            }
2107            for col in &c.columns {
2108                walk_options(&col.options, v);
2109            }
2110            walk_options(&c.options, v);
2111            walk_query(&c.query, v);
2112        }
2113        Statement::CreateFunction(f) => {
2114            walk_options(&f.options, v);
2115            if let FunctionBody::Expr(e) = &f.body {
2116                walk_expr(e, v);
2117            }
2118        }
2119        Statement::CreateTableFunction(f) => {
2120            walk_options(&f.options, v);
2121            walk_query(&f.query, v);
2122        }
2123        Statement::CreateProcedure(p) => {
2124            walk_options(&p.options, v);
2125            for s in p.body.iter().chain(p.exception.iter().flatten()) {
2126                walk_statement(s, v);
2127            }
2128        }
2129        Statement::CreateSchema(s) => {
2130            if let Some(e) = &s.default_collate {
2131                walk_expr(e, v);
2132            }
2133            walk_options(&s.options, v);
2134        }
2135        Statement::Insert(i) => match &i.source {
2136            InsertSource::Values(rows) => {
2137                for e in rows.iter().flatten() {
2138                    walk_expr(e, v);
2139                }
2140            }
2141            InsertSource::Query(q) => walk_query(q, v),
2142        },
2143        Statement::Update(u) => {
2144            for a in &u.assignments {
2145                walk_expr(&a.value, v);
2146            }
2147            for t in &u.from {
2148                walk_table_with_joins(t, v);
2149            }
2150            if let Some(e) = &u.selection {
2151                walk_expr(e, v);
2152            }
2153        }
2154        Statement::Delete(d) => {
2155            if let Some(e) = &d.selection {
2156                walk_expr(e, v);
2157            }
2158        }
2159        Statement::Merge(m) => {
2160            walk_table_factor(&m.source, v);
2161            walk_expr(&m.on, v);
2162            for clause in &m.clauses {
2163                if let Some(e) = &clause.condition {
2164                    walk_expr(e, v);
2165                }
2166                match &clause.action {
2167                    MergeAction::Update(assignments) => {
2168                        for a in assignments {
2169                            walk_expr(&a.value, v);
2170                        }
2171                    }
2172                    MergeAction::Insert { values, .. } => {
2173                        for e in values {
2174                            walk_expr(e, v);
2175                        }
2176                    }
2177                    MergeAction::Delete => {}
2178                }
2179            }
2180        }
2181        Statement::AlterTable(a) => {
2182            for action in &a.actions {
2183                match action {
2184                    AlterAction::AddColumn { column, .. } => walk_column_def(column, v),
2185                    AlterAction::SetOptions(o) => walk_options(o, v),
2186                    AlterAction::SetDefaultCollate(e) => walk_expr(e, v),
2187                    AlterAction::AlterColumn { action, .. } => match action {
2188                        AlterColumnAction::SetOptions(o) => walk_options(o, v),
2189                        AlterColumnAction::SetDefault(e) => walk_expr(e, v),
2190                        _ => {}
2191                    },
2192                    _ => {}
2193                }
2194            }
2195        }
2196        Statement::Declare { default, .. } => {
2197            if let Some(e) = default {
2198                walk_expr(e, v);
2199            }
2200        }
2201        Statement::Set { targets, value } => {
2202            for e in targets {
2203                walk_expr(e, v);
2204            }
2205            walk_expr(value, v);
2206        }
2207        Statement::BeginEnd {
2208            body, exception, ..
2209        } => {
2210            for s in body.iter().chain(exception.iter().flatten()) {
2211                walk_statement(s, v);
2212            }
2213        }
2214        Statement::If {
2215            branches,
2216            else_branch,
2217        }
2218        | Statement::Case {
2219            branches,
2220            else_branch,
2221            ..
2222        } => {
2223            if let Statement::Case {
2224                operand: Some(e), ..
2225            } = statement
2226            {
2227                walk_expr(e, v);
2228            }
2229            for b in branches {
2230                walk_expr(&b.condition, v);
2231                for s in &b.body {
2232                    walk_statement(s, v);
2233                }
2234            }
2235            for s in else_branch.iter().flatten() {
2236                walk_statement(s, v);
2237            }
2238        }
2239        Statement::Loop { body, .. } => {
2240            for s in body {
2241                walk_statement(s, v);
2242            }
2243        }
2244        Statement::While {
2245            condition, body, ..
2246        } => {
2247            walk_expr(condition, v);
2248            for s in body {
2249                walk_statement(s, v);
2250            }
2251        }
2252        Statement::ForIn { query, body, .. } => {
2253            walk_query(query, v);
2254            for s in body {
2255                walk_statement(s, v);
2256            }
2257        }
2258        Statement::Repeat { body, until, .. } => {
2259            for s in body {
2260                walk_statement(s, v);
2261            }
2262            walk_expr(until, v);
2263        }
2264        Statement::Raise { message: Some(e) } => walk_expr(e, v),
2265        Statement::Call { args, .. } => {
2266            for e in args {
2267                walk_expr(e, v);
2268            }
2269        }
2270        Statement::ExecuteImmediate { sql, using, .. } => {
2271            walk_expr(sql, v);
2272            for u in using {
2273                walk_expr(&u.expr, v);
2274            }
2275        }
2276        Statement::Assert {
2277            condition,
2278            description,
2279        } => {
2280            walk_expr(condition, v);
2281            if let Some(e) = description {
2282                walk_expr(e, v);
2283            }
2284        }
2285        Statement::ExportData(e) => {
2286            walk_options(&e.options, v);
2287            walk_query(&e.query, v);
2288        }
2289        Statement::Truncate { .. }
2290        | Statement::Drop(_)
2291        | Statement::Control { .. }
2292        | Statement::Return
2293        | Statement::Raise { message: None }
2294        | Statement::Transaction(_)
2295        | Statement::LoadData(_)
2296        | Statement::Raw(_) => {}
2297    }
2298}
2299
2300fn walk_options<V: Visitor>(options: &[SqlOption], v: &mut V) {
2301    for o in options {
2302        walk_expr(&o.value, v);
2303    }
2304}
2305
2306fn walk_column_def<V: Visitor>(col: &ColumnDef, v: &mut V) {
2307    if let Some(e) = &col.default {
2308        walk_expr(e, v);
2309    }
2310    if let Some(e) = &col.collate {
2311        walk_expr(e, v);
2312    }
2313    walk_options(&col.options, v);
2314}
2315
2316/// Walk a query and everything inside it.
2317pub fn walk_query<V: Visitor>(query: &Query, v: &mut V) {
2318    v.visit_query(query);
2319    if let Some(with) = &query.with {
2320        for cte in &with.ctes {
2321            walk_query(&cte.query, v);
2322        }
2323    }
2324    walk_set_expr(&query.body, v);
2325    for o in &query.order_by {
2326        walk_order_by(o, v);
2327    }
2328    if let Some(limit) = &query.limit {
2329        walk_expr(&limit.count, v);
2330        if let Some(o) = &limit.offset {
2331            walk_expr(o, v);
2332        }
2333    }
2334    for pipe in &query.pipes {
2335        walk_pipe(pipe, v);
2336    }
2337}
2338
2339fn walk_order_by<V: Visitor>(o: &OrderByExpr, v: &mut V) {
2340    walk_expr(&o.expr, v);
2341    if let Some(c) = &o.collate {
2342        walk_expr(c, v);
2343    }
2344}
2345
2346fn walk_pipe<V: Visitor>(pipe: &PipeOperator, v: &mut V) {
2347    match pipe {
2348        PipeOperator::Where(e) => walk_expr(e, v),
2349        PipeOperator::Select { items, .. }
2350        | PipeOperator::Extend(items)
2351        | PipeOperator::Window(items) => {
2352            for item in items {
2353                walk_select_item(item, v);
2354            }
2355        }
2356        PipeOperator::Set(assignments) => {
2357            for a in assignments {
2358                walk_expr(&a.value, v);
2359            }
2360        }
2361        PipeOperator::Aggregate {
2362            items, group_by, ..
2363        } => {
2364            for item in items.iter().chain(group_by.iter()) {
2365                walk_expr(&item.expr, v);
2366            }
2367        }
2368        PipeOperator::Join(join) => walk_join(join, v),
2369        PipeOperator::OrderBy(items) => {
2370            for o in items {
2371                walk_order_by(o, v);
2372            }
2373        }
2374        PipeOperator::Limit(limit) => {
2375            walk_expr(&limit.count, v);
2376            if let Some(o) = &limit.offset {
2377                walk_expr(o, v);
2378            }
2379        }
2380        PipeOperator::SetOperation { queries, .. } => {
2381            for q in queries {
2382                walk_query(q, v);
2383            }
2384        }
2385        PipeOperator::Call { function, .. } => walk_function(function, v),
2386        PipeOperator::TableSample(s) => walk_expr(&s.size, v),
2387        PipeOperator::Pivot {
2388            aggregates,
2389            value_column,
2390            values,
2391            ..
2392        } => {
2393            for a in aggregates.iter().chain(values.iter()) {
2394                walk_expr(&a.expr, v);
2395            }
2396            walk_expr(value_column, v);
2397        }
2398        PipeOperator::Assert { condition, payload } => {
2399            walk_expr(condition, v);
2400            for e in payload {
2401                walk_expr(e, v);
2402            }
2403        }
2404        PipeOperator::MatchRecognize { spec, .. } => {
2405            for e in spec.exprs() {
2406                walk_expr(e, v);
2407            }
2408        }
2409        PipeOperator::Align { spec, .. } => {
2410            for e in spec.exprs() {
2411                walk_expr(e, v);
2412            }
2413        }
2414        PipeOperator::Drop(_)
2415        | PipeOperator::Rename(_)
2416        | PipeOperator::As(_)
2417        | PipeOperator::Distinct
2418        | PipeOperator::Unpivot { .. } => {}
2419    }
2420}
2421
2422fn walk_set_expr<V: Visitor>(body: &SetExpr, v: &mut V) {
2423    match body {
2424        SetExpr::Select(select) => walk_select(select, v),
2425        SetExpr::Query(q) => walk_query(q, v),
2426        SetExpr::SetOperation { left, right, .. } => {
2427            walk_set_expr(left, v);
2428            walk_set_expr(right, v);
2429        }
2430        SetExpr::From(from) => {
2431            for t in from {
2432                walk_table_with_joins(t, v);
2433            }
2434        }
2435    }
2436}
2437
2438fn walk_select_item<V: Visitor>(item: &SelectItem, v: &mut V) {
2439    match item {
2440        SelectItem::Expr { expr, .. } => walk_expr(expr, v),
2441        SelectItem::Wildcard(options) => {
2442            for r in &options.replace {
2443                walk_expr(&r.expr, v);
2444            }
2445        }
2446        SelectItem::QualifiedWildcard { qualifier, options } => {
2447            walk_expr(qualifier, v);
2448            for r in &options.replace {
2449                walk_expr(&r.expr, v);
2450            }
2451        }
2452    }
2453}
2454
2455/// Walk a select and everything inside it.
2456pub fn walk_select<V: Visitor>(select: &Select, v: &mut V) {
2457    v.visit_select(select);
2458    for item in &select.projection {
2459        walk_select_item(item, v);
2460    }
2461    for t in &select.from {
2462        walk_table_with_joins(t, v);
2463    }
2464    if let Some(e) = &select.where_clause {
2465        walk_expr(e, v);
2466    }
2467    if let Some(GroupBy::Items(items)) = &select.group_by {
2468        for item in items {
2469            walk_group_by_item(item, v);
2470        }
2471    }
2472    for e in select.having.iter().chain(select.qualify.iter()) {
2473        walk_expr(e, v);
2474    }
2475    for w in &select.window {
2476        walk_window_spec(&w.spec, v);
2477    }
2478}
2479
2480fn walk_group_by_item<V: Visitor>(item: &GroupByItem, v: &mut V) {
2481    match item {
2482        GroupByItem::Expr(e) => walk_expr(e, v),
2483        GroupByItem::Rollup(es) | GroupByItem::Cube(es) => {
2484            for e in es {
2485                walk_expr(e, v);
2486            }
2487        }
2488        GroupByItem::GroupingSets(items) => {
2489            for i in items {
2490                walk_group_by_item(i, v);
2491            }
2492        }
2493        GroupByItem::Empty => {}
2494    }
2495}
2496
2497fn walk_window_spec<V: Visitor>(spec: &WindowSpec, v: &mut V) {
2498    for e in &spec.partition_by {
2499        walk_expr(e, v);
2500    }
2501    for o in &spec.order_by {
2502        walk_order_by(o, v);
2503    }
2504    if let Some(frame) = &spec.frame {
2505        for bound in std::iter::once(&frame.start).chain(frame.end.iter()) {
2506            if let FrameBound::Preceding(e) | FrameBound::Following(e) = bound {
2507                walk_expr(e, v);
2508            }
2509        }
2510    }
2511}
2512
2513/// Walk a FROM item with its joins.
2514pub fn walk_table_with_joins<V: Visitor>(t: &TableWithJoins, v: &mut V) {
2515    walk_table_factor(&t.relation, v);
2516    for join in &t.joins {
2517        walk_join(join, v);
2518    }
2519}
2520
2521fn walk_join<V: Visitor>(join: &Join, v: &mut V) {
2522    walk_table_factor(&join.relation, v);
2523    if let JoinConstraint::On(e) = &join.constraint {
2524        walk_expr(e, v);
2525    }
2526}
2527
2528/// Walk a table factor.
2529pub fn walk_table_factor<V: Visitor>(factor: &TableFactor, v: &mut V) {
2530    v.visit_table_factor(factor);
2531    match factor {
2532        TableFactor::Table {
2533            system_time,
2534            sample,
2535            ..
2536        } => {
2537            if let Some(e) = system_time {
2538                walk_expr(e, v);
2539            }
2540            if let Some(s) = sample {
2541                walk_expr(&s.size, v);
2542            }
2543        }
2544        TableFactor::Derived { subquery, .. } => walk_query(subquery, v),
2545        TableFactor::Unnest { array, .. } => walk_expr(array, v),
2546        TableFactor::TableFunction { function, .. } => walk_function(function, v),
2547        TableFactor::NestedJoin { table, .. } => walk_table_with_joins(table, v),
2548        TableFactor::Pivot {
2549            table,
2550            aggregates,
2551            value_column,
2552            values,
2553            ..
2554        } => {
2555            walk_table_factor(table, v);
2556            for a in aggregates.iter().chain(values.iter()) {
2557                walk_expr(&a.expr, v);
2558            }
2559            walk_expr(value_column, v);
2560        }
2561        TableFactor::Unpivot { table, .. } => walk_table_factor(table, v),
2562        TableFactor::MatchRecognize { table, spec, .. } => {
2563            walk_table_factor(table, v);
2564            for e in spec.exprs() {
2565                walk_expr(e, v);
2566            }
2567        }
2568        TableFactor::Align { table, spec, .. } => {
2569            walk_table_factor(table, v);
2570            for e in spec.exprs() {
2571                walk_expr(e, v);
2572            }
2573        }
2574    }
2575}
2576
2577fn walk_function<V: Visitor>(f: &Function, v: &mut V) {
2578    for arg in &f.args {
2579        if let FunctionArg::Expr(e) = arg {
2580            walk_expr(e, v);
2581        }
2582    }
2583    if let Some(h) = &f.having {
2584        walk_expr(&h.expr, v);
2585    }
2586    for o in &f.order_by {
2587        walk_order_by(o, v);
2588    }
2589    if let Some(l) = &f.limit {
2590        walk_expr(l, v);
2591    }
2592    if let Some(WindowType::Spec(spec)) = &f.over {
2593        walk_window_spec(spec, v);
2594    }
2595}
2596
2597/// Walk an expression and everything inside it (subqueries included).
2598pub fn walk_expr<V: Visitor>(expr: &Expr, v: &mut V) {
2599    v.visit_expr(expr);
2600    match expr {
2601        Expr::Identifier(_) | Expr::CompoundIdentifier(_) | Expr::Parameter(_) | Expr::Default => {}
2602        Expr::Literal(Literal::Interval(i)) => walk_expr(&i.value, v),
2603        Expr::Literal(_) => {}
2604        Expr::UnaryOp { expr, .. }
2605        | Expr::IsNull { expr, .. }
2606        | Expr::IsBool { expr, .. }
2607        | Expr::Nested(expr)
2608        | Expr::FieldAccess { expr, .. } => walk_expr(expr, v),
2609        Expr::NamedArg { value, .. } => walk_expr(value, v),
2610        Expr::BinaryOp { left, right, .. } | Expr::IsDistinctFrom { left, right, .. } => {
2611            walk_expr(left, v);
2612            walk_expr(right, v);
2613        }
2614        Expr::InList { expr, list, .. } => {
2615            walk_expr(expr, v);
2616            for e in list {
2617                walk_expr(e, v);
2618            }
2619        }
2620        Expr::InSubquery { expr, subquery, .. } => {
2621            walk_expr(expr, v);
2622            walk_query(subquery, v);
2623        }
2624        Expr::InUnnest { expr, array, .. } => {
2625            walk_expr(expr, v);
2626            walk_expr(array, v);
2627        }
2628        Expr::Between {
2629            expr, low, high, ..
2630        } => {
2631            walk_expr(expr, v);
2632            walk_expr(low, v);
2633            walk_expr(high, v);
2634        }
2635        Expr::Like { expr, pattern, .. } => {
2636            walk_expr(expr, v);
2637            walk_expr(pattern, v);
2638        }
2639        Expr::LikeQuantified { expr, patterns, .. } => {
2640            walk_expr(expr, v);
2641            match patterns {
2642                LikePatterns::List(list) => {
2643                    for e in list {
2644                        walk_expr(e, v);
2645                    }
2646                }
2647                LikePatterns::Unnest(e) => walk_expr(e, v),
2648                LikePatterns::Subquery(q) => walk_query(q, v),
2649            }
2650        }
2651        Expr::Case {
2652            operand,
2653            branches,
2654            else_result,
2655        } => {
2656            if let Some(e) = operand {
2657                walk_expr(e, v);
2658            }
2659            for b in branches {
2660                walk_expr(&b.condition, v);
2661                walk_expr(&b.result, v);
2662            }
2663            if let Some(e) = else_result {
2664                walk_expr(e, v);
2665            }
2666        }
2667        Expr::Cast {
2668            expr,
2669            format,
2670            time_zone,
2671            ..
2672        } => {
2673            walk_expr(expr, v);
2674            for e in format.iter().chain(time_zone.iter()) {
2675                walk_expr(e, v);
2676            }
2677        }
2678        Expr::Extract {
2679            part,
2680            expr,
2681            time_zone,
2682        } => {
2683            walk_expr(part, v);
2684            walk_expr(expr, v);
2685            if let Some(e) = time_zone {
2686                walk_expr(e, v);
2687            }
2688        }
2689        Expr::Struct { fields, .. } => {
2690            for f in fields {
2691                walk_expr(&f.expr, v);
2692            }
2693        }
2694        Expr::Tuple(items)
2695        | Expr::Array {
2696            elements: items, ..
2697        } => {
2698            for e in items {
2699                walk_expr(e, v);
2700            }
2701        }
2702        Expr::ArraySubquery(q) | Expr::Subquery(q) | Expr::Exists(q) => walk_query(q, v),
2703        Expr::Subscript { expr, index, .. } => {
2704            walk_expr(expr, v);
2705            walk_expr(index, v);
2706        }
2707        Expr::Function(f) => walk_function(f, v),
2708        Expr::ScalarWith { bindings, body } => {
2709            for (_, e) in bindings {
2710                walk_expr(e, v);
2711            }
2712            walk_expr(body, v);
2713        }
2714        Expr::Lambda { body, .. } => walk_expr(body, v),
2715    }
2716}
2717
2718// --------------------------------------------------------------------- helpers
2719
2720struct ExprCollector<'a, F: FnMut(&Expr)>(&'a mut F);
2721
2722impl<F: FnMut(&Expr)> Visitor for ExprCollector<'_, F> {
2723    fn visit_expr(&mut self, expr: &Expr) {
2724        (self.0)(expr)
2725    }
2726}
2727
2728struct SelectCollector<'a, F: FnMut(&Select)>(&'a mut F);
2729
2730impl<F: FnMut(&Select)> Visitor for SelectCollector<'_, F> {
2731    fn visit_select(&mut self, select: &Select) {
2732        (self.0)(select)
2733    }
2734}
2735
2736#[derive(Default)]
2737struct DmlDetector {
2738    found: bool,
2739}
2740
2741impl Visitor for DmlDetector {
2742    fn visit_statement(&mut self, statement: &Statement) {
2743        if !matches!(statement, Statement::Query(_)) {
2744            self.found = true;
2745        }
2746    }
2747}
2748
2749impl Statement {
2750    /// Call `f` on every expression of the statement, subqueries included.
2751    pub fn walk_exprs(&self, mut f: impl FnMut(&Expr)) {
2752        walk_statement(self, &mut ExprCollector(&mut f));
2753    }
2754
2755    /// Call `f` on every `SELECT` of the statement.
2756    pub fn walk_selects(&self, mut f: impl FnMut(&Select)) {
2757        walk_statement(self, &mut SelectCollector(&mut f));
2758    }
2759
2760    /// Whether the statement (or a statement nested in it) is anything other than a query:
2761    /// DML, DDL, scripting, a transaction or an unparsed command.
2762    pub fn contains_dml_or_ddl(&self) -> bool {
2763        let mut detector = DmlDetector::default();
2764        walk_statement(self, &mut detector);
2765        detector.found
2766    }
2767
2768    /// The tables the statement reads, without CTE names (see [`Query::referenced_tables`]).
2769    /// Written targets are not included.
2770    pub fn referenced_tables(&self) -> Vec<TableName> {
2771        let mut out = TableCollector::default();
2772        out.statement(self);
2773        out.finish()
2774    }
2775
2776    /// The query a statement reads from: the statement itself, the `AS` query of `CREATE` or the
2777    /// source of `INSERT`.
2778    pub fn query(&self) -> Option<&Query> {
2779        match self {
2780            Statement::Query(q) => Some(q),
2781            Statement::CreateTable(c) => c.query.as_deref(),
2782            Statement::CreateView(c) => Some(&c.query),
2783            Statement::Insert(i) => match &i.source {
2784                InsertSource::Query(q) => Some(q),
2785                InsertSource::Values(_) => None,
2786            },
2787            Statement::ExportData(e) => Some(&e.query),
2788            _ => None,
2789        }
2790    }
2791
2792    /// The table a statement writes, if it writes exactly one.
2793    pub fn target_table(&self) -> Option<TableName> {
2794        match self {
2795            Statement::CreateTable(c) => Some(c.name.table_name()),
2796            Statement::CreateView(c) => Some(c.name.table_name()),
2797            Statement::Insert(i) => Some(i.table.table_name()),
2798            Statement::Update(u) => Some(u.table.table_name()),
2799            Statement::Delete(d) => Some(d.table.table_name()),
2800            Statement::Merge(m) => Some(m.target.table_name()),
2801            Statement::Truncate { name } => Some(name.table_name()),
2802            Statement::Drop(d) if d.object_type.is_relation() => Some(d.name.table_name()),
2803            Statement::AlterTable(a) => Some(a.name.table_name()),
2804            _ => None,
2805        }
2806    }
2807}
2808
2809impl Query {
2810    /// Call `f` on every expression of the query, subqueries included.
2811    pub fn walk_exprs(&self, mut f: impl FnMut(&Expr)) {
2812        walk_query(self, &mut ExprCollector(&mut f));
2813    }
2814
2815    /// Call `f` on every `SELECT` of the query, subqueries and CTEs included.
2816    pub fn walk_selects(&self, mut f: impl FnMut(&Select)) {
2817        walk_query(self, &mut SelectCollector(&mut f));
2818    }
2819
2820    /// The tables the query reads, in first-seen order and without duplicates. A name bound by a
2821    /// `WITH` in scope at the reference is a CTE, not a table (a recursive CTE sees itself).
2822    pub fn referenced_tables(&self) -> Vec<TableName> {
2823        let mut out = TableCollector::default();
2824        out.query(self);
2825        out.finish()
2826    }
2827
2828    /// The names of the query's output columns, when every one is known (no `*`).
2829    pub fn output_names(&self) -> Option<Vec<String>> {
2830        if !self.pipes.is_empty() {
2831            return None;
2832        }
2833        let mut body = &self.body;
2834        loop {
2835            match body {
2836                SetExpr::SetOperation { left, .. } => body = left,
2837                SetExpr::Query(q) => return q.output_names(),
2838                SetExpr::Select(select) => {
2839                    return select
2840                        .projection
2841                        .iter()
2842                        .map(SelectItem::output_name)
2843                        .collect::<Option<Vec<_>>>();
2844                }
2845                SetExpr::From(_) => return None,
2846            }
2847        }
2848    }
2849
2850    /// The first `SELECT` of the body, through set operations and parentheses.
2851    pub fn first_select_mut(&mut self) -> Option<&mut Select> {
2852        fn first(body: &mut SetExpr) -> Option<&mut Select> {
2853            match body {
2854                SetExpr::Select(s) => Some(s),
2855                SetExpr::Query(q) => q.first_select_mut(),
2856                SetExpr::SetOperation { left, .. } => first(left),
2857                SetExpr::From(_) => None,
2858            }
2859        }
2860        first(&mut self.body)
2861    }
2862
2863    /// Mutable access to every table reference with whether a CTE in scope binds its name.
2864    pub fn visit_tables_mut(&mut self, f: &mut dyn FnMut(&mut TableFactor, bool)) {
2865        let mut scopes: Vec<Vec<String>> = Vec::new();
2866        visit_query_tables_mut(self, &mut scopes, f);
2867    }
2868}
2869
2870impl Statement {
2871    /// Mutable access to every table reference with whether a CTE in scope binds its name.
2872    /// Written targets (`INSERT INTO t`, `MERGE t`) are not table factors and are not visited.
2873    pub fn visit_tables_mut(&mut self, f: &mut dyn FnMut(&mut TableFactor, bool)) {
2874        let mut scopes: Vec<Vec<String>> = Vec::new();
2875        match self {
2876            Statement::Query(q) => visit_query_tables_mut(q, &mut scopes, f),
2877            Statement::CreateTable(c) => {
2878                if let Some(q) = &mut c.query {
2879                    visit_query_tables_mut(q, &mut scopes, f);
2880                }
2881            }
2882            Statement::CreateView(c) => visit_query_tables_mut(&mut c.query, &mut scopes, f),
2883            Statement::CreateTableFunction(c) => {
2884                visit_query_tables_mut(&mut c.query, &mut scopes, f)
2885            }
2886            Statement::Insert(i) => match &mut i.source {
2887                InsertSource::Query(q) => visit_query_tables_mut(q, &mut scopes, f),
2888                InsertSource::Values(rows) => {
2889                    for e in rows.iter_mut().flatten() {
2890                        visit_expr_tables_mut(e, &mut scopes, f);
2891                    }
2892                }
2893            },
2894            Statement::Update(u) => {
2895                for a in &mut u.assignments {
2896                    visit_expr_tables_mut(&mut a.value, &mut scopes, f);
2897                }
2898                for t in &mut u.from {
2899                    visit_twj_tables_mut(t, &mut scopes, f);
2900                }
2901                if let Some(e) = &mut u.selection {
2902                    visit_expr_tables_mut(e, &mut scopes, f);
2903                }
2904            }
2905            Statement::Delete(d) => {
2906                if let Some(e) = &mut d.selection {
2907                    visit_expr_tables_mut(e, &mut scopes, f);
2908                }
2909            }
2910            Statement::Merge(m) => {
2911                visit_factor_tables_mut(&mut m.source, &mut scopes, f);
2912                visit_expr_tables_mut(&mut m.on, &mut scopes, f);
2913                for clause in &mut m.clauses {
2914                    if let Some(e) = &mut clause.condition {
2915                        visit_expr_tables_mut(e, &mut scopes, f);
2916                    }
2917                    match &mut clause.action {
2918                        MergeAction::Update(assignments) => {
2919                            for a in assignments {
2920                                visit_expr_tables_mut(&mut a.value, &mut scopes, f);
2921                            }
2922                        }
2923                        MergeAction::Insert { values, .. } => {
2924                            for e in values {
2925                                visit_expr_tables_mut(e, &mut scopes, f);
2926                            }
2927                        }
2928                        MergeAction::Delete => {}
2929                    }
2930                }
2931            }
2932            Statement::ExportData(e) => visit_query_tables_mut(&mut e.query, &mut scopes, f),
2933            Statement::ForIn { query, .. } => visit_query_tables_mut(query, &mut scopes, f),
2934            Statement::Set { value, .. } => visit_expr_tables_mut(value, &mut scopes, f),
2935            Statement::Declare {
2936                default: Some(e), ..
2937            } => visit_expr_tables_mut(e, &mut scopes, f),
2938            _ => {}
2939        }
2940    }
2941}
2942
2943fn bound(scopes: &[Vec<String>], name: &TableName) -> bool {
2944    name.project.is_none()
2945        && name.dataset.is_none()
2946        && scopes
2947            .iter()
2948            .any(|scope| scope.iter().any(|n| n.eq_ignore_ascii_case(&name.name)))
2949}
2950
2951fn visit_query_tables_mut(
2952    query: &mut Query,
2953    scopes: &mut Vec<Vec<String>>,
2954    f: &mut dyn FnMut(&mut TableFactor, bool),
2955) {
2956    let pushed = if let Some(with) = &mut query.with {
2957        let names: Vec<String> = with.ctes.iter().map(|c| c.name.value.clone()).collect();
2958        // each CTE sees the ones before it (and itself when recursive)
2959        for index in 0..with.ctes.len() {
2960            let visible = if with.recursive {
2961                names.clone()
2962            } else {
2963                names[..index].to_vec()
2964            };
2965            scopes.push(visible);
2966            visit_query_tables_mut(&mut with.ctes[index].query, scopes, f);
2967            scopes.pop();
2968        }
2969        scopes.push(names);
2970        true
2971    } else {
2972        false
2973    };
2974    visit_set_expr_tables_mut(&mut query.body, scopes, f);
2975    for o in &mut query.order_by {
2976        visit_expr_tables_mut(&mut o.expr, scopes, f);
2977    }
2978    for pipe in &mut query.pipes {
2979        match pipe {
2980            PipeOperator::Join(join) => {
2981                visit_factor_tables_mut(&mut join.relation, scopes, f);
2982                if let JoinConstraint::On(e) = &mut join.constraint {
2983                    visit_expr_tables_mut(e, scopes, f);
2984                }
2985            }
2986            PipeOperator::SetOperation { queries, .. } => {
2987                for q in queries {
2988                    visit_query_tables_mut(q, scopes, f);
2989                }
2990            }
2991            PipeOperator::Where(e) => visit_expr_tables_mut(e, scopes, f),
2992            PipeOperator::Select { items, .. }
2993            | PipeOperator::Extend(items)
2994            | PipeOperator::Window(items) => {
2995                for item in items {
2996                    if let SelectItem::Expr { expr, .. } = item {
2997                        visit_expr_tables_mut(expr, scopes, f);
2998                    }
2999                }
3000            }
3001            PipeOperator::Aggregate {
3002                items, group_by, ..
3003            } => {
3004                for item in items.iter_mut().chain(group_by.iter_mut()) {
3005                    visit_expr_tables_mut(&mut item.expr, scopes, f);
3006                }
3007            }
3008            PipeOperator::Set(assignments) => {
3009                for a in assignments {
3010                    visit_expr_tables_mut(&mut a.value, scopes, f);
3011                }
3012            }
3013            PipeOperator::Call { function, .. } => visit_function_tables_mut(function, scopes, f),
3014            _ => {}
3015        }
3016    }
3017    if pushed {
3018        scopes.pop();
3019    }
3020}
3021
3022fn visit_set_expr_tables_mut(
3023    body: &mut SetExpr,
3024    scopes: &mut Vec<Vec<String>>,
3025    f: &mut dyn FnMut(&mut TableFactor, bool),
3026) {
3027    match body {
3028        SetExpr::Select(select) => {
3029            for item in &mut select.projection {
3030                match item {
3031                    SelectItem::Expr { expr, .. } => visit_expr_tables_mut(expr, scopes, f),
3032                    SelectItem::Wildcard(o) | SelectItem::QualifiedWildcard { options: o, .. } => {
3033                        for r in &mut o.replace {
3034                            visit_expr_tables_mut(&mut r.expr, scopes, f);
3035                        }
3036                    }
3037                }
3038            }
3039            for t in &mut select.from {
3040                visit_twj_tables_mut(t, scopes, f);
3041            }
3042            for e in select
3043                .where_clause
3044                .iter_mut()
3045                .chain(select.having.iter_mut())
3046                .chain(select.qualify.iter_mut())
3047            {
3048                visit_expr_tables_mut(e, scopes, f);
3049            }
3050            if let Some(GroupBy::Items(items)) = &mut select.group_by {
3051                for item in items {
3052                    if let GroupByItem::Expr(e) = item {
3053                        visit_expr_tables_mut(e, scopes, f);
3054                    }
3055                }
3056            }
3057        }
3058        SetExpr::Query(q) => visit_query_tables_mut(q, scopes, f),
3059        SetExpr::SetOperation { left, right, .. } => {
3060            visit_set_expr_tables_mut(left, scopes, f);
3061            visit_set_expr_tables_mut(right, scopes, f);
3062        }
3063        SetExpr::From(from) => {
3064            for t in from {
3065                visit_twj_tables_mut(t, scopes, f);
3066            }
3067        }
3068    }
3069}
3070
3071fn visit_twj_tables_mut(
3072    t: &mut TableWithJoins,
3073    scopes: &mut Vec<Vec<String>>,
3074    f: &mut dyn FnMut(&mut TableFactor, bool),
3075) {
3076    visit_factor_tables_mut(&mut t.relation, scopes, f);
3077    for join in &mut t.joins {
3078        visit_factor_tables_mut(&mut join.relation, scopes, f);
3079        if let JoinConstraint::On(e) = &mut join.constraint {
3080            visit_expr_tables_mut(e, scopes, f);
3081        }
3082    }
3083}
3084
3085fn visit_factor_tables_mut(
3086    factor: &mut TableFactor,
3087    scopes: &mut Vec<Vec<String>>,
3088    f: &mut dyn FnMut(&mut TableFactor, bool),
3089) {
3090    match factor {
3091        TableFactor::Table { name, .. } => {
3092            let is_cte = bound(scopes, &name.table_name());
3093            f(factor, is_cte);
3094        }
3095        TableFactor::Derived { subquery, .. } => visit_query_tables_mut(subquery, scopes, f),
3096        TableFactor::Unnest { array, .. } => visit_expr_tables_mut(array, scopes, f),
3097        TableFactor::TableFunction { function, .. } => {
3098            visit_function_tables_mut(function, scopes, f);
3099            f(factor, false);
3100        }
3101        TableFactor::NestedJoin { table, .. } => visit_twj_tables_mut(table, scopes, f),
3102        TableFactor::Pivot { table, .. }
3103        | TableFactor::Unpivot { table, .. }
3104        | TableFactor::MatchRecognize { table, .. }
3105        | TableFactor::Align { table, .. } => visit_factor_tables_mut(table, scopes, f),
3106    }
3107}
3108
3109fn visit_function_tables_mut(
3110    function: &mut Function,
3111    scopes: &mut Vec<Vec<String>>,
3112    f: &mut dyn FnMut(&mut TableFactor, bool),
3113) {
3114    for arg in &mut function.args {
3115        match arg {
3116            FunctionArg::Expr(e) => visit_expr_tables_mut(e, scopes, f),
3117            FunctionArg::Table(name) => {
3118                // `TABLE t` is a read of t: visit it as a table factor and write back a rename
3119                let mut factor = TableFactor::table(name.clone(), None);
3120                let is_cte = bound(scopes, &name.table_name());
3121                f(&mut factor, is_cte);
3122                if let TableFactor::Table { name: renamed, .. } = factor {
3123                    *name = renamed;
3124                }
3125            }
3126            _ => {}
3127        }
3128    }
3129}
3130
3131fn visit_expr_tables_mut(
3132    expr: &mut Expr,
3133    scopes: &mut Vec<Vec<String>>,
3134    f: &mut dyn FnMut(&mut TableFactor, bool),
3135) {
3136    match expr {
3137        Expr::Subquery(q) | Expr::Exists(q) | Expr::ArraySubquery(q) => {
3138            visit_query_tables_mut(q, scopes, f)
3139        }
3140        Expr::InSubquery { expr, subquery, .. } => {
3141            visit_expr_tables_mut(expr, scopes, f);
3142            visit_query_tables_mut(subquery, scopes, f);
3143        }
3144        Expr::LikeQuantified { expr, patterns, .. } => {
3145            visit_expr_tables_mut(expr, scopes, f);
3146            match patterns {
3147                LikePatterns::Subquery(q) => visit_query_tables_mut(q, scopes, f),
3148                LikePatterns::Unnest(e) => visit_expr_tables_mut(e, scopes, f),
3149                LikePatterns::List(list) => {
3150                    for e in list {
3151                        visit_expr_tables_mut(e, scopes, f);
3152                    }
3153                }
3154            }
3155        }
3156        Expr::Function(function) => {
3157            if let Some(h) = &mut function.having {
3158                visit_expr_tables_mut(&mut h.expr, scopes, f);
3159            }
3160            visit_function_tables_mut(function, scopes, f)
3161        }
3162        Expr::UnaryOp { expr, .. }
3163        | Expr::IsNull { expr, .. }
3164        | Expr::IsBool { expr, .. }
3165        | Expr::Nested(expr)
3166        | Expr::FieldAccess { expr, .. } => visit_expr_tables_mut(expr, scopes, f),
3167        Expr::NamedArg { value, .. } => visit_expr_tables_mut(value, scopes, f),
3168        Expr::BinaryOp { left, right, .. } | Expr::IsDistinctFrom { left, right, .. } => {
3169            visit_expr_tables_mut(left, scopes, f);
3170            visit_expr_tables_mut(right, scopes, f);
3171        }
3172        Expr::InList { expr, list, .. } => {
3173            visit_expr_tables_mut(expr, scopes, f);
3174            for e in list {
3175                visit_expr_tables_mut(e, scopes, f);
3176            }
3177        }
3178        Expr::InUnnest { expr, array, .. } => {
3179            visit_expr_tables_mut(expr, scopes, f);
3180            visit_expr_tables_mut(array, scopes, f);
3181        }
3182        Expr::Between {
3183            expr, low, high, ..
3184        } => {
3185            visit_expr_tables_mut(expr, scopes, f);
3186            visit_expr_tables_mut(low, scopes, f);
3187            visit_expr_tables_mut(high, scopes, f);
3188        }
3189        Expr::Like { expr, pattern, .. } => {
3190            visit_expr_tables_mut(expr, scopes, f);
3191            visit_expr_tables_mut(pattern, scopes, f);
3192        }
3193        Expr::Case {
3194            operand,
3195            branches,
3196            else_result,
3197        } => {
3198            if let Some(e) = operand {
3199                visit_expr_tables_mut(e, scopes, f);
3200            }
3201            for b in branches {
3202                visit_expr_tables_mut(&mut b.condition, scopes, f);
3203                visit_expr_tables_mut(&mut b.result, scopes, f);
3204            }
3205            if let Some(e) = else_result {
3206                visit_expr_tables_mut(e, scopes, f);
3207            }
3208        }
3209        Expr::Cast { expr, .. } => visit_expr_tables_mut(expr, scopes, f),
3210        Expr::Extract { expr, .. } => visit_expr_tables_mut(expr, scopes, f),
3211        Expr::Struct { fields, .. } => {
3212            for field in fields {
3213                visit_expr_tables_mut(&mut field.expr, scopes, f);
3214            }
3215        }
3216        Expr::Tuple(items)
3217        | Expr::Array {
3218            elements: items, ..
3219        } => {
3220            for e in items {
3221                visit_expr_tables_mut(e, scopes, f);
3222            }
3223        }
3224        Expr::Subscript { expr, index, .. } => {
3225            visit_expr_tables_mut(expr, scopes, f);
3226            visit_expr_tables_mut(index, scopes, f);
3227        }
3228        Expr::ScalarWith { bindings, body } => {
3229            for (_, e) in bindings {
3230                visit_expr_tables_mut(e, scopes, f);
3231            }
3232            visit_expr_tables_mut(body, scopes, f);
3233        }
3234        Expr::Lambda { body, .. } => visit_expr_tables_mut(body, scopes, f),
3235        Expr::Identifier(_)
3236        | Expr::CompoundIdentifier(_)
3237        | Expr::Literal(_)
3238        | Expr::Parameter(_)
3239        | Expr::Default => {}
3240    }
3241}
3242
3243#[derive(Default)]
3244struct TableCollector {
3245    seen: indexmap::IndexMap<String, TableName>,
3246}
3247
3248impl TableCollector {
3249    fn add(&mut self, factor: &TableFactor, is_cte: bool) {
3250        if is_cte {
3251            return;
3252        }
3253        if let TableFactor::Table { name, .. } = factor {
3254            let table = name.table_name();
3255            self.seen.entry(table.key()).or_insert(table);
3256        }
3257    }
3258
3259    fn query(&mut self, query: &Query) {
3260        let mut copy = query.clone();
3261        copy.visit_tables_mut(&mut |factor, is_cte| self.add(factor, is_cte));
3262    }
3263
3264    fn statement(&mut self, statement: &Statement) {
3265        let mut copy = statement.clone();
3266        copy.visit_tables_mut(&mut |factor, is_cte| self.add(factor, is_cte));
3267    }
3268
3269    fn finish(self) -> Vec<TableName> {
3270        self.seen.into_values().collect()
3271    }
3272}
3273
3274// --------------------------------------------------------------------- mutable walks
3275
3276/// Call `f` on every expression inside `expr`, children first (so a replacement is not walked
3277/// again). With `into_queries`, expressions of subqueries are visited too.
3278pub fn walk_expr_mut(expr: &mut Expr, into_queries: bool, f: &mut dyn FnMut(&mut Expr)) {
3279    match expr {
3280        Expr::Identifier(_) | Expr::CompoundIdentifier(_) | Expr::Parameter(_) | Expr::Default => {}
3281        Expr::Literal(Literal::Interval(i)) => walk_expr_mut(&mut i.value, into_queries, f),
3282        Expr::Literal(_) => {}
3283        Expr::UnaryOp { expr: e, .. }
3284        | Expr::IsNull { expr: e, .. }
3285        | Expr::IsBool { expr: e, .. }
3286        | Expr::Nested(e)
3287        | Expr::FieldAccess { expr: e, .. } => walk_expr_mut(e, into_queries, f),
3288        Expr::NamedArg { value, .. } => walk_expr_mut(value, into_queries, f),
3289        Expr::BinaryOp { left, right, .. } | Expr::IsDistinctFrom { left, right, .. } => {
3290            walk_expr_mut(left, into_queries, f);
3291            walk_expr_mut(right, into_queries, f);
3292        }
3293        Expr::InList { expr: e, list, .. } => {
3294            walk_expr_mut(e, into_queries, f);
3295            for x in list {
3296                walk_expr_mut(x, into_queries, f);
3297            }
3298        }
3299        Expr::InSubquery {
3300            expr: e, subquery, ..
3301        } => {
3302            walk_expr_mut(e, into_queries, f);
3303            if into_queries {
3304                walk_query_exprs_mut(subquery, f);
3305            }
3306        }
3307        Expr::InUnnest { expr: e, array, .. } => {
3308            walk_expr_mut(e, into_queries, f);
3309            walk_expr_mut(array, into_queries, f);
3310        }
3311        Expr::Between {
3312            expr: e, low, high, ..
3313        } => {
3314            walk_expr_mut(e, into_queries, f);
3315            walk_expr_mut(low, into_queries, f);
3316            walk_expr_mut(high, into_queries, f);
3317        }
3318        Expr::Like {
3319            expr: e, pattern, ..
3320        } => {
3321            walk_expr_mut(e, into_queries, f);
3322            walk_expr_mut(pattern, into_queries, f);
3323        }
3324        Expr::LikeQuantified {
3325            expr: e, patterns, ..
3326        } => {
3327            walk_expr_mut(e, into_queries, f);
3328            match patterns {
3329                LikePatterns::List(list) => {
3330                    for x in list {
3331                        walk_expr_mut(x, into_queries, f);
3332                    }
3333                }
3334                LikePatterns::Unnest(a) => walk_expr_mut(a, into_queries, f),
3335                LikePatterns::Subquery(q) => {
3336                    if into_queries {
3337                        walk_query_exprs_mut(q, f);
3338                    }
3339                }
3340            }
3341        }
3342        Expr::Case {
3343            operand,
3344            branches,
3345            else_result,
3346        } => {
3347            if let Some(o) = operand {
3348                walk_expr_mut(o, into_queries, f);
3349            }
3350            for b in branches {
3351                walk_expr_mut(&mut b.condition, into_queries, f);
3352                walk_expr_mut(&mut b.result, into_queries, f);
3353            }
3354            if let Some(x) = else_result {
3355                walk_expr_mut(x, into_queries, f);
3356            }
3357        }
3358        Expr::Cast {
3359            expr: e,
3360            format,
3361            time_zone,
3362            ..
3363        } => {
3364            walk_expr_mut(e, into_queries, f);
3365            for x in format.iter_mut().chain(time_zone.iter_mut()) {
3366                walk_expr_mut(x, into_queries, f);
3367            }
3368        }
3369        Expr::Extract {
3370            part,
3371            expr: e,
3372            time_zone,
3373        } => {
3374            walk_expr_mut(part, into_queries, f);
3375            walk_expr_mut(e, into_queries, f);
3376            if let Some(x) = time_zone {
3377                walk_expr_mut(x, into_queries, f);
3378            }
3379        }
3380        Expr::Struct { fields, .. } => {
3381            for field in fields {
3382                walk_expr_mut(&mut field.expr, into_queries, f);
3383            }
3384        }
3385        Expr::Tuple(items)
3386        | Expr::Array {
3387            elements: items, ..
3388        } => {
3389            for x in items {
3390                walk_expr_mut(x, into_queries, f);
3391            }
3392        }
3393        Expr::ArraySubquery(q) | Expr::Subquery(q) | Expr::Exists(q) => {
3394            if into_queries {
3395                walk_query_exprs_mut(q, f);
3396            }
3397        }
3398        Expr::Subscript { expr: e, index, .. } => {
3399            walk_expr_mut(e, into_queries, f);
3400            walk_expr_mut(index, into_queries, f);
3401        }
3402        Expr::Function(function) => walk_function_mut(function, into_queries, f),
3403        Expr::ScalarWith { bindings, body } => {
3404            for (_, x) in bindings {
3405                walk_expr_mut(x, into_queries, f);
3406            }
3407            walk_expr_mut(body, into_queries, f);
3408        }
3409        Expr::Lambda { body, .. } => walk_expr_mut(body, into_queries, f),
3410    }
3411    f(expr);
3412}
3413
3414fn walk_function_mut(function: &mut Function, into_queries: bool, f: &mut dyn FnMut(&mut Expr)) {
3415    for arg in &mut function.args {
3416        if let FunctionArg::Expr(e) = arg {
3417            walk_expr_mut(e, into_queries, f);
3418        }
3419    }
3420    if let Some(h) = &mut function.having {
3421        walk_expr_mut(&mut h.expr, into_queries, f);
3422    }
3423    for o in &mut function.order_by {
3424        walk_expr_mut(&mut o.expr, into_queries, f);
3425    }
3426    if let Some(l) = &mut function.limit {
3427        walk_expr_mut(l, into_queries, f);
3428    }
3429    if let Some(WindowType::Spec(spec)) = &mut function.over {
3430        for e in &mut spec.partition_by {
3431            walk_expr_mut(e, into_queries, f);
3432        }
3433        for o in &mut spec.order_by {
3434            walk_expr_mut(&mut o.expr, into_queries, f);
3435        }
3436    }
3437}
3438
3439fn walk_factor_exprs_mut(factor: &mut TableFactor, f: &mut dyn FnMut(&mut Expr)) {
3440    match factor {
3441        TableFactor::Table { system_time, .. } => {
3442            if let Some(e) = system_time {
3443                walk_expr_mut(e, true, f);
3444            }
3445        }
3446        TableFactor::Derived { subquery, .. } => walk_query_exprs_mut(subquery, f),
3447        TableFactor::Unnest { array, .. } => walk_expr_mut(array, true, f),
3448        TableFactor::TableFunction { function, .. } => walk_function_mut(function, true, f),
3449        TableFactor::NestedJoin { table, .. } => walk_twj_exprs_mut(table, f),
3450        TableFactor::Pivot {
3451            table,
3452            aggregates,
3453            value_column,
3454            values,
3455            ..
3456        } => {
3457            walk_factor_exprs_mut(table, f);
3458            for a in aggregates.iter_mut().chain(values.iter_mut()) {
3459                walk_expr_mut(&mut a.expr, true, f);
3460            }
3461            walk_expr_mut(value_column, true, f);
3462        }
3463        TableFactor::Unpivot { table, .. } => walk_factor_exprs_mut(table, f),
3464        TableFactor::MatchRecognize { table, spec, .. } => {
3465            walk_factor_exprs_mut(table, f);
3466            for e in spec.exprs_mut() {
3467                walk_expr_mut(e, true, f);
3468            }
3469        }
3470        TableFactor::Align { table, spec, .. } => {
3471            walk_factor_exprs_mut(table, f);
3472            for e in spec.exprs_mut() {
3473                walk_expr_mut(e, true, f);
3474            }
3475        }
3476    }
3477}
3478
3479fn walk_twj_exprs_mut(t: &mut TableWithJoins, f: &mut dyn FnMut(&mut Expr)) {
3480    walk_factor_exprs_mut(&mut t.relation, f);
3481    for join in &mut t.joins {
3482        walk_factor_exprs_mut(&mut join.relation, f);
3483        if let JoinConstraint::On(e) = &mut join.constraint {
3484            walk_expr_mut(e, true, f);
3485        }
3486    }
3487}
3488
3489fn walk_items_mut(items: &mut [SelectItem], f: &mut dyn FnMut(&mut Expr)) {
3490    for item in items {
3491        match item {
3492            SelectItem::Expr { expr, .. } => walk_expr_mut(expr, true, f),
3493            SelectItem::Wildcard(o) => {
3494                for r in &mut o.replace {
3495                    walk_expr_mut(&mut r.expr, true, f);
3496                }
3497            }
3498            SelectItem::QualifiedWildcard { qualifier, options } => {
3499                walk_expr_mut(qualifier, true, f);
3500                for r in &mut options.replace {
3501                    walk_expr_mut(&mut r.expr, true, f);
3502                }
3503            }
3504        }
3505    }
3506}
3507
3508fn walk_set_expr_exprs_mut(body: &mut SetExpr, f: &mut dyn FnMut(&mut Expr)) {
3509    match body {
3510        SetExpr::Select(s) => {
3511            walk_items_mut(&mut s.projection, f);
3512            for t in &mut s.from {
3513                walk_twj_exprs_mut(t, f);
3514            }
3515            for e in s
3516                .where_clause
3517                .iter_mut()
3518                .chain(s.having.iter_mut())
3519                .chain(s.qualify.iter_mut())
3520            {
3521                walk_expr_mut(e, true, f);
3522            }
3523            if let Some(GroupBy::Items(items)) = &mut s.group_by {
3524                fn group(item: &mut GroupByItem, f: &mut dyn FnMut(&mut Expr)) {
3525                    match item {
3526                        GroupByItem::Expr(e) => walk_expr_mut(e, true, f),
3527                        GroupByItem::Rollup(es) | GroupByItem::Cube(es) => {
3528                            for e in es {
3529                                walk_expr_mut(e, true, f);
3530                            }
3531                        }
3532                        GroupByItem::GroupingSets(items) => {
3533                            for i in items {
3534                                group(i, f);
3535                            }
3536                        }
3537                        GroupByItem::Empty => {}
3538                    }
3539                }
3540                for item in items {
3541                    group(item, f);
3542                }
3543            }
3544            for w in &mut s.window {
3545                for e in &mut w.spec.partition_by {
3546                    walk_expr_mut(e, true, f);
3547                }
3548                for o in &mut w.spec.order_by {
3549                    walk_expr_mut(&mut o.expr, true, f);
3550                }
3551            }
3552        }
3553        SetExpr::Query(q) => walk_query_exprs_mut(q, f),
3554        SetExpr::SetOperation { left, right, .. } => {
3555            walk_set_expr_exprs_mut(left, f);
3556            walk_set_expr_exprs_mut(right, f);
3557        }
3558        SetExpr::From(from) => {
3559            for t in from {
3560                walk_twj_exprs_mut(t, f);
3561            }
3562        }
3563    }
3564}
3565
3566/// Call `f` on every expression of the query, subqueries and CTEs included, children first.
3567pub fn walk_query_exprs_mut(query: &mut Query, f: &mut dyn FnMut(&mut Expr)) {
3568    if let Some(with) = &mut query.with {
3569        for cte in &mut with.ctes {
3570            walk_query_exprs_mut(&mut cte.query, f);
3571        }
3572    }
3573    walk_set_expr_exprs_mut(&mut query.body, f);
3574    for o in &mut query.order_by {
3575        walk_expr_mut(&mut o.expr, true, f);
3576    }
3577    if let Some(limit) = &mut query.limit {
3578        walk_expr_mut(&mut limit.count, true, f);
3579        if let Some(o) = &mut limit.offset {
3580            walk_expr_mut(o, true, f);
3581        }
3582    }
3583    for pipe in &mut query.pipes {
3584        match pipe {
3585            PipeOperator::Where(e) => walk_expr_mut(e, true, f),
3586            PipeOperator::Select { items, .. }
3587            | PipeOperator::Extend(items)
3588            | PipeOperator::Window(items) => walk_items_mut(items, f),
3589            PipeOperator::Set(assignments) => {
3590                for a in assignments {
3591                    walk_expr_mut(&mut a.value, true, f);
3592                }
3593            }
3594            PipeOperator::Aggregate {
3595                items, group_by, ..
3596            } => {
3597                for item in items.iter_mut().chain(group_by.iter_mut()) {
3598                    walk_expr_mut(&mut item.expr, true, f);
3599                }
3600            }
3601            PipeOperator::Join(join) => {
3602                walk_factor_exprs_mut(&mut join.relation, f);
3603                if let JoinConstraint::On(e) = &mut join.constraint {
3604                    walk_expr_mut(e, true, f);
3605                }
3606            }
3607            PipeOperator::OrderBy(items) => {
3608                for o in items {
3609                    walk_expr_mut(&mut o.expr, true, f);
3610                }
3611            }
3612            PipeOperator::Limit(limit) => walk_expr_mut(&mut limit.count, true, f),
3613            PipeOperator::SetOperation { queries, .. } => {
3614                for q in queries {
3615                    walk_query_exprs_mut(q, f);
3616                }
3617            }
3618            PipeOperator::Call { function, .. } => walk_function_mut(function, true, f),
3619            PipeOperator::Assert { condition, .. } => walk_expr_mut(condition, true, f),
3620            PipeOperator::MatchRecognize { spec, .. } => {
3621                for e in spec.exprs_mut() {
3622                    walk_expr_mut(e, true, f);
3623                }
3624            }
3625            PipeOperator::Align { spec, .. } => {
3626                for e in spec.exprs_mut() {
3627                    walk_expr_mut(e, true, f);
3628                }
3629            }
3630            _ => {}
3631        }
3632    }
3633}
3634
3635/// Call `f` on every expression a statement holds (subqueries included), children first.
3636pub fn walk_statement_exprs_mut(statement: &mut Statement, f: &mut dyn FnMut(&mut Expr)) {
3637    match statement {
3638        Statement::Query(q) => walk_query_exprs_mut(q, f),
3639        Statement::CreateTable(c) => {
3640            if let Some(q) = &mut c.query {
3641                walk_query_exprs_mut(q, f);
3642            }
3643        }
3644        Statement::CreateView(c) => walk_query_exprs_mut(&mut c.query, f),
3645        Statement::CreateTableFunction(c) => walk_query_exprs_mut(&mut c.query, f),
3646        Statement::Insert(i) => match &mut i.source {
3647            InsertSource::Query(q) => walk_query_exprs_mut(q, f),
3648            InsertSource::Values(rows) => {
3649                for e in rows.iter_mut().flatten() {
3650                    walk_expr_mut(e, true, f);
3651                }
3652            }
3653        },
3654        Statement::Update(u) => {
3655            for a in &mut u.assignments {
3656                walk_expr_mut(&mut a.value, true, f);
3657            }
3658            for t in &mut u.from {
3659                walk_twj_exprs_mut(t, f);
3660            }
3661            if let Some(e) = &mut u.selection {
3662                walk_expr_mut(e, true, f);
3663            }
3664        }
3665        Statement::Delete(d) => {
3666            if let Some(e) = &mut d.selection {
3667                walk_expr_mut(e, true, f);
3668            }
3669        }
3670        Statement::Merge(m) => {
3671            walk_factor_exprs_mut(&mut m.source, f);
3672            walk_expr_mut(&mut m.on, true, f);
3673            for clause in &mut m.clauses {
3674                if let Some(e) = &mut clause.condition {
3675                    walk_expr_mut(e, true, f);
3676                }
3677                match &mut clause.action {
3678                    MergeAction::Update(assignments) => {
3679                        for a in assignments {
3680                            walk_expr_mut(&mut a.value, true, f);
3681                        }
3682                    }
3683                    MergeAction::Insert { values, .. } => {
3684                        for e in values {
3685                            walk_expr_mut(e, true, f);
3686                        }
3687                    }
3688                    MergeAction::Delete => {}
3689                }
3690            }
3691        }
3692        Statement::ExportData(e) => walk_query_exprs_mut(&mut e.query, f),
3693        Statement::Set { value, .. } => walk_expr_mut(value, true, f),
3694        Statement::Declare {
3695            default: Some(e), ..
3696        } => walk_expr_mut(e, true, f),
3697        _ => {}
3698    }
3699}
3700
3701#[cfg(test)]
3702mod tests {
3703    use super::*;
3704
3705    #[test]
3706    fn object_name_parts_split_backticked_paths() {
3707        let name = ObjectName(vec![Ident::quoted("p.d.t")]);
3708        assert_eq!(name.parts(), vec!["p", "d", "t"]);
3709        let t = name.table_name();
3710        assert_eq!(t.project.as_deref(), Some("p"));
3711        assert_eq!(t.dataset.as_deref(), Some("d"));
3712        assert_eq!(t.name, "t");
3713        assert_eq!(TableName::parse("`p.d`.t"), t);
3714        assert!(TableName::new("x").is_temp_name());
3715        assert!(TableName::parse("_SESSION.x").is_temp_name());
3716        assert!(!TableName::parse("d.x").is_temp_name());
3717    }
3718
3719    #[test]
3720    fn ident_equality_ignores_quotes() {
3721        assert_eq!(Ident::new("a"), Ident::quoted("a"));
3722        let a = Literal::String(StringLiteral {
3723            value: "x".into(),
3724            raw: true,
3725            quote: QuoteStyle::Double,
3726        });
3727        assert_eq!(a, Literal::string("x"));
3728    }
3729
3730    #[test]
3731    fn data_type_aliases() {
3732        assert_eq!(DataType::from_name("integer"), Some(DataType::Int64));
3733        assert_eq!(
3734            DataType::from_name("DECIMAL"),
3735            Some(DataType::Numeric(None))
3736        );
3737        assert!(DataType::is_type_name("struct"));
3738        assert!(!DataType::is_type_name("foo"));
3739    }
3740}