use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};
use crate::token::QuoteStyle;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Ident {
pub value: String,
pub quoted: bool,
}
impl Ident {
pub fn new(value: impl Into<String>) -> Self {
Ident {
value: value.into(),
quoted: false,
}
}
pub fn quoted(value: impl Into<String>) -> Self {
Ident {
value: value.into(),
quoted: true,
}
}
pub fn matches(&self, other: &str) -> bool {
self.value.eq_ignore_ascii_case(other)
}
}
impl PartialEq for Ident {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}
impl Eq for Ident {}
impl Hash for Ident {
fn hash<H: Hasher>(&self, state: &mut H) {
self.value.hash(state);
}
}
impl From<&str> for Ident {
fn from(value: &str) -> Self {
Ident::new(value)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ObjectName(pub Vec<Ident>);
impl ObjectName {
pub fn new<I: Into<Ident>>(parts: impl IntoIterator<Item = I>) -> Self {
ObjectName(parts.into_iter().map(Into::into).collect())
}
pub fn parts(&self) -> Vec<String> {
let mut parts = Vec::new();
for ident in &self.0 {
if ident.quoted && ident.value.contains('.') {
parts.extend(
ident
.value
.split('.')
.filter(|p| !p.is_empty())
.map(str::to_string),
);
} else {
parts.push(ident.value.clone());
}
}
parts
}
pub fn base_name(&self) -> String {
self.parts().pop().unwrap_or_default()
}
pub fn dotted(&self) -> String {
self.parts().join(".")
}
pub fn table_name(&self) -> TableName {
TableName::from_parts(self.parts())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
pub struct TableName {
pub project: Option<String>,
pub dataset: Option<String>,
pub name: String,
}
impl TableName {
pub fn new(name: impl Into<String>) -> Self {
TableName {
project: None,
dataset: None,
name: name.into(),
}
}
pub fn from_parts(mut parts: Vec<String>) -> Self {
let name = parts.pop().unwrap_or_default();
let dataset = parts.pop();
let project = if parts.is_empty() {
None
} else {
Some(parts.join("."))
};
TableName {
project,
dataset,
name,
}
}
pub fn parse(text: &str) -> Self {
let mut parts = Vec::new();
let mut current = String::new();
let mut quoted = false;
for ch in text.trim().chars() {
match ch {
'`' => quoted = !quoted,
'.' => {
if !current.is_empty() {
parts.push(std::mem::take(&mut current));
}
}
c if c.is_whitespace() && !quoted => {}
c => current.push(c),
}
}
if !current.is_empty() {
parts.push(current);
}
TableName::from_parts(parts)
}
pub fn dotted(&self) -> String {
let mut out = Vec::new();
if let Some(p) = &self.project {
out.push(p.as_str());
}
if let Some(d) = &self.dataset {
out.push(d.as_str());
}
out.push(self.name.as_str());
out.join(".")
}
pub fn key(&self) -> String {
self.dotted().to_lowercase()
}
pub fn is_temp_name(&self) -> bool {
self.project.is_none()
&& self
.dataset
.as_deref()
.map_or(true, |d| d.eq_ignore_ascii_case("_session"))
}
}
impl std::fmt::Display for TableName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.dotted())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Statement {
Query(Box<Query>),
CreateTable(Box<CreateTable>),
CreateView(Box<CreateView>),
CreateFunction(Box<CreateFunction>),
CreateTableFunction(Box<CreateTableFunction>),
CreateProcedure(Box<CreateProcedure>),
CreateSchema(Box<CreateSchema>),
Insert(Box<Insert>),
Update(Box<Update>),
Delete(Box<Delete>),
Merge(Box<Merge>),
Drop(Box<Drop>),
AlterTable(Box<AlterTable>),
Truncate {
name: ObjectName,
},
Declare {
names: Vec<Ident>,
data_type: Option<DataType>,
default: Option<Expr>,
},
Set {
targets: Vec<Expr>,
value: Expr,
},
BeginEnd {
label: Option<Ident>,
body: Vec<Statement>,
exception: Option<Vec<Statement>>,
},
If {
branches: Vec<ConditionalBlock>,
else_branch: Option<Vec<Statement>>,
},
Case {
operand: Option<Expr>,
branches: Vec<ConditionalBlock>,
else_branch: Option<Vec<Statement>>,
},
Loop {
label: Option<Ident>,
body: Vec<Statement>,
},
While {
label: Option<Ident>,
condition: Expr,
body: Vec<Statement>,
},
ForIn {
label: Option<Ident>,
variable: Ident,
query: Box<Query>,
body: Vec<Statement>,
},
Repeat {
label: Option<Ident>,
body: Vec<Statement>,
until: Expr,
},
Control {
kind: ControlKind,
label: Option<Ident>,
},
Return,
Raise {
message: Option<Expr>,
},
Call {
procedure: ObjectName,
args: Vec<Expr>,
},
ExecuteImmediate {
sql: Expr,
into: Vec<Ident>,
using: Vec<ExprWithAlias>,
},
Assert {
condition: Expr,
description: Option<Expr>,
},
Transaction(TransactionKind),
ExportData(Box<ExportData>),
LoadData(Box<LoadData>),
Raw(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ConditionalBlock {
pub condition: Expr,
pub body: Vec<Statement>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ControlKind {
Break,
Leave,
Continue,
Iterate,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TransactionKind {
Begin,
Commit,
Rollback,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ExprWithAlias {
pub expr: Expr,
pub alias: Option<Ident>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SqlOption {
pub name: Ident,
pub value: Expr,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TableKind {
Table,
External,
Snapshot,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CopyKind {
Like,
Copy,
Clone,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TableCopy {
pub kind: CopyKind,
pub source: ObjectName,
pub system_time: Option<Expr>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CreateTable {
pub or_replace: bool,
pub temporary: bool,
pub kind: TableKind,
pub if_not_exists: bool,
pub name: ObjectName,
pub columns: Vec<ColumnDef>,
pub constraints: Vec<TableConstraint>,
pub copy: Option<TableCopy>,
pub with_connection: Option<ObjectName>,
pub default_collate: Option<Expr>,
pub partition_by: Option<Expr>,
pub cluster_by: Vec<Expr>,
pub options: Vec<SqlOption>,
pub query: Option<Box<Query>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ColumnDef {
pub name: Ident,
pub data_type: DataType,
pub collate: Option<Expr>,
pub not_null: bool,
pub default: Option<Expr>,
pub primary_key: bool,
pub options: Vec<SqlOption>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TableConstraint {
PrimaryKey {
columns: Vec<Ident>,
not_enforced: bool,
},
ForeignKey {
name: Option<Ident>,
columns: Vec<Ident>,
foreign_table: ObjectName,
referred_columns: Vec<Ident>,
not_enforced: bool,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ViewColumn {
pub name: Ident,
pub options: Vec<SqlOption>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CreateView {
pub or_replace: bool,
pub materialized: bool,
pub if_not_exists: bool,
pub name: ObjectName,
pub columns: Vec<ViewColumn>,
pub partition_by: Option<Expr>,
pub cluster_by: Vec<Expr>,
pub options: Vec<SqlOption>,
pub query: Box<Query>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ParamType {
Type(DataType),
AnyType,
Table(Vec<StructField>),
AnyTable,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct FunctionParam {
pub name: Ident,
pub param_type: ParamType,
pub not_aggregate: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FunctionBody {
Expr(Expr),
Code(Literal),
Remote(ObjectName),
None,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CreateFunction {
pub or_replace: bool,
pub temporary: bool,
pub aggregate: bool,
pub if_not_exists: bool,
pub name: ObjectName,
pub params: Vec<FunctionParam>,
pub returns: Option<DataType>,
pub determinism: Option<bool>,
pub language: Option<Ident>,
pub options: Vec<SqlOption>,
pub body: FunctionBody,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CreateTableFunction {
pub or_replace: bool,
pub temporary: bool,
pub if_not_exists: bool,
pub name: ObjectName,
pub params: Vec<FunctionParam>,
pub returns: Option<Vec<StructField>>,
pub options: Vec<SqlOption>,
pub query: Box<Query>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ParamMode {
In,
Out,
InOut,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ProcedureParam {
pub mode: Option<ParamMode>,
pub name: Ident,
pub param_type: ParamType,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CreateProcedure {
pub or_replace: bool,
pub if_not_exists: bool,
pub name: ObjectName,
pub params: Vec<ProcedureParam>,
pub options: Vec<SqlOption>,
pub body: Vec<Statement>,
pub exception: Option<Vec<Statement>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CreateSchema {
pub if_not_exists: bool,
pub name: ObjectName,
pub default_collate: Option<Expr>,
pub options: Vec<SqlOption>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum InsertSource {
Values(Vec<Vec<Expr>>),
Query(Box<Query>),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Insert {
pub table: ObjectName,
pub columns: Vec<Ident>,
pub source: InsertSource,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Assignment {
pub target: Vec<Ident>,
pub value: Expr,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Update {
pub table: ObjectName,
pub alias: Option<Ident>,
pub assignments: Vec<Assignment>,
pub from: Vec<TableWithJoins>,
pub selection: Option<Expr>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Delete {
pub table: ObjectName,
pub alias: Option<Ident>,
pub selection: Option<Expr>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MergeMatch {
Matched,
NotMatchedByTarget,
NotMatchedBySource,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MergeAction {
Update(Vec<Assignment>),
Delete,
Insert {
columns: Vec<Ident>,
values: Vec<Expr>,
row: bool,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MergeClause {
pub kind: MergeMatch,
pub explicit_by_target: bool,
pub condition: Option<Expr>,
pub action: MergeAction,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Merge {
pub target: ObjectName,
pub target_alias: Option<Ident>,
pub source: TableFactor,
pub on: Expr,
pub clauses: Vec<MergeClause>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ObjectType {
Table,
ExternalTable,
SnapshotTable,
View,
MaterializedView,
Schema,
Function,
TableFunction,
Procedure,
Model,
}
impl ObjectType {
pub fn keyword(self) -> &'static str {
match self {
ObjectType::Table => "TABLE",
ObjectType::ExternalTable => "EXTERNAL TABLE",
ObjectType::SnapshotTable => "SNAPSHOT TABLE",
ObjectType::View => "VIEW",
ObjectType::MaterializedView => "MATERIALIZED VIEW",
ObjectType::Schema => "SCHEMA",
ObjectType::Function => "FUNCTION",
ObjectType::TableFunction => "TABLE FUNCTION",
ObjectType::Procedure => "PROCEDURE",
ObjectType::Model => "MODEL",
}
}
pub fn is_relation(self) -> bool {
matches!(
self,
ObjectType::Table
| ObjectType::ExternalTable
| ObjectType::SnapshotTable
| ObjectType::View
| ObjectType::MaterializedView
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Drop {
pub object_type: ObjectType,
pub if_exists: bool,
pub name: ObjectName,
pub cascade: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AlterColumnAction {
SetOptions(Vec<SqlOption>),
DropNotNull,
SetDataType(DataType),
SetDefault(Expr),
DropDefault,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AlterAction {
AddColumn {
if_not_exists: bool,
column: ColumnDef,
},
DropColumn {
if_exists: bool,
name: Ident,
},
RenameTo(ObjectName),
RenameColumn {
if_exists: bool,
from: Ident,
to: Ident,
},
SetOptions(Vec<SqlOption>),
SetDefaultCollate(Expr),
AlterColumn {
if_exists: bool,
name: Ident,
action: AlterColumnAction,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AlterTable {
pub object_type: ObjectType,
pub if_exists: bool,
pub name: ObjectName,
pub actions: Vec<AlterAction>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ExportData {
pub connection: Option<ObjectName>,
pub options: Vec<SqlOption>,
pub query: Box<Query>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct LoadData {
pub overwrite: bool,
pub temporary: bool,
pub table: ObjectName,
pub rest: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Query {
pub with: Option<With>,
pub body: SetExpr,
pub order_by: Vec<OrderByExpr>,
pub limit: Option<Limit>,
pub pipes: Vec<PipeOperator>,
}
impl Query {
pub fn from_body(body: SetExpr) -> Self {
Query {
with: None,
body,
order_by: Vec::new(),
limit: None,
pipes: Vec::new(),
}
}
pub fn from_select(select: Select) -> Self {
Query::from_body(SetExpr::Select(Box::new(select)))
}
pub fn is_pipe(&self) -> bool {
!self.pipes.is_empty() || matches!(self.body, SetExpr::From(_))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct With {
pub recursive: bool,
pub ctes: Vec<Cte>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Cte {
pub name: Ident,
pub query: Box<Query>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Limit {
pub count: Expr,
pub offset: Option<Expr>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SetOperator {
Union,
Intersect,
Except,
}
impl SetOperator {
pub fn keyword(self) -> &'static str {
match self {
SetOperator::Union => "UNION",
SetOperator::Intersect => "INTERSECT",
SetOperator::Except => "EXCEPT",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SetQuantifier {
All,
Distinct,
None,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SetOpMode {
Full,
Left,
Inner,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Corresponding {
ByName(Vec<Ident>),
Corresponding { strict: bool, by: Vec<Ident> },
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SetExpr {
Select(Box<Select>),
Query(Box<Query>),
SetOperation {
op: SetOperator,
quantifier: SetQuantifier,
mode: Option<SetOpMode>,
corresponding: Option<Corresponding>,
left: Box<SetExpr>,
right: Box<SetExpr>,
},
From(Vec<TableWithJoins>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SelectAs {
Struct,
Value,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Select {
pub distinct: bool,
pub select_as: Option<SelectAs>,
pub projection: Vec<SelectItem>,
pub from: Vec<TableWithJoins>,
pub where_clause: Option<Expr>,
pub group_by: Option<GroupBy>,
pub having: Option<Expr>,
pub qualify: Option<Expr>,
pub window: Vec<NamedWindow>,
}
impl Select {
pub fn new(projection: Vec<SelectItem>) -> Self {
Select {
distinct: false,
select_as: None,
projection,
from: Vec::new(),
where_clause: None,
group_by: None,
having: None,
qualify: None,
window: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub struct WildcardOptions {
pub except: Vec<Ident>,
pub replace: Vec<ExprWithAlias>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SelectItem {
Expr {
expr: Expr,
alias: Option<Ident>,
},
Wildcard(WildcardOptions),
QualifiedWildcard {
qualifier: Expr,
options: WildcardOptions,
},
}
impl SelectItem {
pub fn expr(expr: Expr, alias: Option<&str>) -> Self {
SelectItem::Expr {
expr,
alias: alias.map(Ident::new),
}
}
pub fn output_name(&self) -> Option<String> {
match self {
SelectItem::Expr {
alias: Some(alias), ..
} => Some(alias.value.clone()),
SelectItem::Expr { expr, .. } => expr.implicit_name(),
_ => None,
}
}
pub fn is_star(&self) -> bool {
matches!(
self,
SelectItem::Wildcard(_) | SelectItem::QualifiedWildcard { .. }
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum GroupBy {
All,
Items(Vec<GroupByItem>),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum GroupByItem {
Expr(Expr),
Rollup(Vec<Expr>),
Cube(Vec<Expr>),
GroupingSets(Vec<GroupByItem>),
Empty,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct NamedWindow {
pub name: Ident,
pub spec: WindowSpec,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct OrderByExpr {
pub expr: Expr,
pub collate: Option<Expr>,
pub asc: Option<bool>,
pub nulls_first: Option<bool>,
}
impl OrderByExpr {
pub fn new(expr: Expr) -> Self {
OrderByExpr {
expr,
collate: None,
asc: None,
nulls_first: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TableWithJoins {
pub relation: TableFactor,
pub joins: Vec<Join>,
}
impl TableWithJoins {
pub fn table(name: ObjectName) -> Self {
TableWithJoins {
relation: TableFactor::table(name, None),
joins: Vec::new(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum JoinKind {
Inner,
Left,
Right,
Full,
Cross,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum JoinConstraint {
On(Expr),
Using(Vec<Ident>),
None,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Join {
pub kind: JoinKind,
pub natural: bool,
pub relation: TableFactor,
pub constraint: JoinConstraint,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SampleUnit {
Percent,
Rows,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TableSample {
pub method: Ident,
pub size: Expr,
pub unit: SampleUnit,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct UnpivotColumns {
pub columns: Vec<Ident>,
pub alias: Option<Expr>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TableFactor {
Table {
name: ObjectName,
alias: Option<Ident>,
system_time: Option<Expr>,
sample: Option<TableSample>,
},
Derived {
subquery: Box<Query>,
alias: Option<Ident>,
sample: Option<TableSample>,
},
Unnest {
array: Box<Expr>,
alias: Option<Ident>,
with_offset: Option<Option<Ident>>,
},
TableFunction {
function: Function,
alias: Option<Ident>,
},
NestedJoin {
table: Box<TableWithJoins>,
alias: Option<Ident>,
},
Pivot {
table: Box<TableFactor>,
aggregates: Vec<ExprWithAlias>,
value_column: Box<Expr>,
values: Vec<ExprWithAlias>,
alias: Option<Ident>,
},
Unpivot {
table: Box<TableFactor>,
include_nulls: Option<bool>,
value_columns: Vec<Ident>,
name_column: Ident,
columns: Vec<UnpivotColumns>,
alias: Option<Ident>,
},
MatchRecognize {
table: Box<TableFactor>,
spec: Box<MatchRecognize>,
alias: Option<Ident>,
},
Align {
table: Box<TableFactor>,
spec: Box<Align>,
alias: Option<Ident>,
},
}
impl TableFactor {
pub fn table(name: ObjectName, alias: Option<Ident>) -> Self {
TableFactor::Table {
name,
alias,
system_time: None,
sample: None,
}
}
pub fn alias(&self) -> Option<&Ident> {
match self {
TableFactor::Table { alias, .. }
| TableFactor::Derived { alias, .. }
| TableFactor::Unnest { alias, .. }
| TableFactor::TableFunction { alias, .. }
| TableFactor::NestedJoin { alias, .. }
| TableFactor::Pivot { alias, .. }
| TableFactor::Unpivot { alias, .. }
| TableFactor::MatchRecognize { alias, .. }
| TableFactor::Align { alias, .. } => alias.as_ref(),
}
}
pub fn set_alias(&mut self, new: Option<Ident>) {
match self {
TableFactor::Table { alias, .. }
| TableFactor::Derived { alias, .. }
| TableFactor::Unnest { alias, .. }
| TableFactor::TableFunction { alias, .. }
| TableFactor::NestedJoin { alias, .. }
| TableFactor::Pivot { alias, .. }
| TableFactor::Unpivot { alias, .. }
| TableFactor::MatchRecognize { alias, .. }
| TableFactor::Align { alias, .. } => *alias = new,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PipeExprItem {
pub expr: Expr,
pub alias: Option<Ident>,
pub asc: Option<bool>,
pub nulls_first: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PipeOperator {
Where(Expr),
Select {
distinct: bool,
select_as: Option<SelectAs>,
items: Vec<SelectItem>,
},
Extend(Vec<SelectItem>),
Set(Vec<Assignment>),
Drop(Vec<Ident>),
Rename(Vec<(Ident, Ident)>),
As(Ident),
Aggregate {
items: Vec<PipeExprItem>,
group_by: Vec<PipeExprItem>,
group_and_order: bool,
},
Join(Join),
OrderBy(Vec<OrderByExpr>),
Limit(Limit),
SetOperation {
op: SetOperator,
quantifier: SetQuantifier,
mode: Option<SetOpMode>,
corresponding: Option<Corresponding>,
queries: Vec<Query>,
},
Call {
function: Function,
alias: Option<Ident>,
},
Distinct,
TableSample(TableSample),
Pivot {
aggregates: Vec<ExprWithAlias>,
value_column: Box<Expr>,
values: Vec<ExprWithAlias>,
alias: Option<Ident>,
},
Unpivot {
include_nulls: Option<bool>,
value_columns: Vec<Ident>,
name_column: Ident,
columns: Vec<UnpivotColumns>,
alias: Option<Ident>,
},
Window(Vec<SelectItem>),
Assert {
condition: Expr,
payload: Vec<Expr>,
},
MatchRecognize {
spec: Box<MatchRecognize>,
alias: Option<Ident>,
},
Align {
spec: Box<Align>,
alias: Option<Ident>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MatchRecognize {
pub partition_by: Vec<Expr>,
pub order_by: Vec<OrderByExpr>,
pub measures: Vec<(Expr, Ident)>,
pub after_match: Option<AfterMatchSkip>,
pub pattern: RowPattern,
pub define: Vec<(Ident, Expr)>,
pub options: Vec<SqlOption>,
}
impl MatchRecognize {
pub fn variables(&self) -> Vec<Ident> {
let mut out: Vec<Ident> = Vec::new();
let mut push = |i: &Ident| {
if !out.iter().any(|o| o.value.eq_ignore_ascii_case(&i.value)) {
out.push(i.clone());
}
};
self.pattern.symbols().into_iter().for_each(&mut push);
self.define.iter().for_each(|(i, _)| push(i));
out
}
pub fn exprs(&self) -> Vec<&Expr> {
let mut out: Vec<&Expr> = self.partition_by.iter().collect();
out.extend(self.order_by.iter().map(|o| &o.expr));
out.extend(self.measures.iter().map(|(e, _)| e));
out.extend(self.define.iter().map(|(_, e)| e));
out.extend(self.options.iter().map(|o| &o.value));
out
}
pub fn exprs_mut(&mut self) -> Vec<&mut Expr> {
let mut out: Vec<&mut Expr> = self.partition_by.iter_mut().collect();
out.extend(self.order_by.iter_mut().map(|o| &mut o.expr));
out.extend(self.measures.iter_mut().map(|(e, _)| e));
out.extend(self.define.iter_mut().map(|(_, e)| e));
out.extend(self.options.iter_mut().map(|o| &mut o.value));
out
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AfterMatchSkip {
PastLastRow,
ToNextRow,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RowPattern {
Empty,
Symbol(Ident),
Start,
Concat(Vec<RowPattern>),
Alternation(Vec<RowPattern>),
Group(Box<RowPattern>),
Quantified {
pattern: Box<RowPattern>,
quantifier: PatternQuantifier,
reluctant: bool,
},
}
impl RowPattern {
pub fn symbols(&self) -> Vec<&Ident> {
fn walk<'a>(p: &'a RowPattern, out: &mut Vec<&'a Ident>) {
match p {
RowPattern::Empty | RowPattern::Start => {}
RowPattern::Symbol(i) => {
if !out.iter().any(|o| o.value.eq_ignore_ascii_case(&i.value)) {
out.push(i);
}
}
RowPattern::Concat(items) | RowPattern::Alternation(items) => {
items.iter().for_each(|i| walk(i, out))
}
RowPattern::Group(inner) => walk(inner, out),
RowPattern::Quantified { pattern, .. } => walk(pattern, out),
}
}
let mut out = Vec::new();
walk(self, &mut out);
out
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PatternQuantifier {
ZeroOrMore,
OneOrMore,
ZeroOrOne,
Exactly(u64),
Range { min: Option<u64>, max: Option<u64> },
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Align {
pub timestamp: Option<Ident>,
pub timestamp_alias: Option<Ident>,
pub period: Expr,
pub origin: Option<Expr>,
pub output: Option<String>,
pub partition_by: Vec<ExprWithAlias>,
pub metrics: Vec<AlignMetric>,
}
impl Align {
pub fn output_timestamp_name(&self) -> String {
self.timestamp_alias
.as_ref()
.or(self.timestamp.as_ref())
.map(|i| i.value.clone())
.unwrap_or_else(|| "timestamp".to_string())
}
pub fn exprs(&self) -> Vec<&Expr> {
let mut out = vec![&self.period];
out.extend(self.origin.iter());
out.extend(self.partition_by.iter().map(|p| &p.expr));
out.extend(self.metrics.iter().map(|m| &m.expr));
out
}
pub fn exprs_mut(&mut self) -> Vec<&mut Expr> {
let mut out = vec![&mut self.period];
out.extend(self.origin.iter_mut());
out.extend(self.partition_by.iter_mut().map(|p| &mut p.expr));
out.extend(self.metrics.iter_mut().map(|m| &mut m.expr));
out
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AlignMetric {
pub expr: Expr,
pub within: Option<String>,
pub alias: Option<Ident>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum UnaryOperator {
Not,
Minus,
Plus,
BitNot,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum BinaryOperator {
Or,
And,
Eq,
NotEq,
Lt,
LtEq,
Gt,
GtEq,
BitOr,
BitXor,
BitAnd,
ShiftLeft,
ShiftRight,
Plus,
Minus,
Multiply,
Divide,
Concat,
}
impl BinaryOperator {
pub fn as_str(self) -> &'static str {
match self {
BinaryOperator::Or => "OR",
BinaryOperator::And => "AND",
BinaryOperator::Eq => "=",
BinaryOperator::NotEq => "!=",
BinaryOperator::Lt => "<",
BinaryOperator::LtEq => "<=",
BinaryOperator::Gt => ">",
BinaryOperator::GtEq => ">=",
BinaryOperator::BitOr => "|",
BinaryOperator::BitXor => "^",
BinaryOperator::BitAnd => "&",
BinaryOperator::ShiftLeft => "<<",
BinaryOperator::ShiftRight => ">>",
BinaryOperator::Plus => "+",
BinaryOperator::Minus => "-",
BinaryOperator::Multiply => "*",
BinaryOperator::Divide => "/",
BinaryOperator::Concat => "||",
}
}
pub fn precedence(self) -> u8 {
match self {
BinaryOperator::Or => 1,
BinaryOperator::And => 2,
BinaryOperator::Eq
| BinaryOperator::NotEq
| BinaryOperator::Lt
| BinaryOperator::LtEq
| BinaryOperator::Gt
| BinaryOperator::GtEq => 4,
BinaryOperator::BitOr => 5,
BinaryOperator::BitXor => 6,
BinaryOperator::BitAnd => 7,
BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => 8,
BinaryOperator::Plus | BinaryOperator::Minus => 9,
BinaryOperator::Multiply | BinaryOperator::Divide | BinaryOperator::Concat => 10,
}
}
}
pub const COMPARISON_PRECEDENCE: u8 = 4;
pub const NOT_PRECEDENCE: u8 = 3;
pub const UNARY_PRECEDENCE: u8 = 11;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Parameter {
Named(String),
Positional,
System(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StringLiteral {
pub value: String,
pub raw: bool,
pub quote: QuoteStyle,
}
impl StringLiteral {
pub fn new(value: impl Into<String>) -> Self {
StringLiteral {
value: value.into(),
raw: false,
quote: QuoteStyle::Single,
}
}
}
impl PartialEq for StringLiteral {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}
impl Eq for StringLiteral {}
impl Hash for StringLiteral {
fn hash<H: Hasher>(&self, state: &mut H) {
self.value.hash(state);
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BytesLiteral {
pub value: Vec<u8>,
pub raw: bool,
pub quote: QuoteStyle,
}
impl PartialEq for BytesLiteral {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}
impl Eq for BytesLiteral {}
impl Hash for BytesLiteral {
fn hash<H: Hasher>(&self, state: &mut H) {
self.value.hash(state);
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct IntervalLiteral {
pub value: Box<Expr>,
pub leading: String,
pub trailing: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Literal {
Null,
Bool(bool),
Int(String),
Float(String),
Numeric(String),
BigNumeric(String),
String(StringLiteral),
Bytes(BytesLiteral),
Date(String),
Datetime(String),
Time(String),
Timestamp(String),
Interval(IntervalLiteral),
Json(String),
Range {
element: Box<DataType>,
value: String,
},
}
impl Literal {
pub fn string(value: impl Into<String>) -> Self {
Literal::String(StringLiteral::new(value))
}
pub fn int(value: i64) -> Self {
Literal::Int(value.to_string())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SubscriptKind {
Plain,
Offset,
Ordinal,
SafeOffset,
SafeOrdinal,
}
impl SubscriptKind {
pub fn keyword(self) -> Option<&'static str> {
match self {
SubscriptKind::Plain => None,
SubscriptKind::Offset => Some("OFFSET"),
SubscriptKind::Ordinal => Some("ORDINAL"),
SubscriptKind::SafeOffset => Some("SAFE_OFFSET"),
SubscriptKind::SafeOrdinal => Some("SAFE_ORDINAL"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum LikeQuantifier {
Any,
Some,
All,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum LikePatterns {
List(Vec<Expr>),
Unnest(Box<Expr>),
Subquery(Box<Query>),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CaseWhen {
pub condition: Expr,
pub result: Expr,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct StructExprField {
pub expr: Expr,
pub alias: Option<Ident>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum NullTreatment {
IgnoreNulls,
RespectNulls,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct HavingBound {
pub max: bool,
pub expr: Box<Expr>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FunctionArg {
Expr(Expr),
Wildcard,
Table(ObjectName),
Model(ObjectName),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Function {
pub name: ObjectName,
pub args: Vec<FunctionArg>,
pub distinct: bool,
pub null_treatment: Option<NullTreatment>,
pub having: Option<HavingBound>,
pub order_by: Vec<OrderByExpr>,
pub limit: Option<Box<Expr>>,
pub over: Option<WindowType>,
pub no_parens: bool,
}
impl Function {
pub fn new(name: &str, args: Vec<Expr>) -> Self {
Function {
name: ObjectName::new([name]),
args: args.into_iter().map(FunctionArg::Expr).collect(),
distinct: false,
null_treatment: None,
having: None,
order_by: Vec::new(),
limit: None,
over: None,
no_parens: false,
}
}
pub fn upper_name(&self) -> String {
self.name.dotted().to_ascii_uppercase()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum WindowType {
Named(Ident),
Spec(WindowSpec),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub struct WindowSpec {
pub base: Option<Ident>,
pub partition_by: Vec<Expr>,
pub order_by: Vec<OrderByExpr>,
pub frame: Option<WindowFrame>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FrameUnits {
Rows,
Range,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FrameBound {
UnboundedPreceding,
Preceding(Box<Expr>),
CurrentRow,
Following(Box<Expr>),
UnboundedFollowing,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct WindowFrame {
pub units: FrameUnits,
pub start: FrameBound,
pub end: Option<FrameBound>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Expr {
Identifier(Ident),
CompoundIdentifier(Vec<Ident>),
Literal(Literal),
Parameter(Parameter),
UnaryOp {
op: UnaryOperator,
expr: Box<Expr>,
},
BinaryOp {
left: Box<Expr>,
op: BinaryOperator,
right: Box<Expr>,
},
IsNull {
expr: Box<Expr>,
negated: bool,
},
IsBool {
expr: Box<Expr>,
value: Option<bool>,
negated: bool,
},
IsDistinctFrom {
left: Box<Expr>,
right: Box<Expr>,
negated: bool,
},
InList {
expr: Box<Expr>,
list: Vec<Expr>,
negated: bool,
},
InSubquery {
expr: Box<Expr>,
subquery: Box<Query>,
negated: bool,
},
InUnnest {
expr: Box<Expr>,
array: Box<Expr>,
negated: bool,
},
Between {
expr: Box<Expr>,
negated: bool,
low: Box<Expr>,
high: Box<Expr>,
},
Like {
expr: Box<Expr>,
negated: bool,
pattern: Box<Expr>,
},
LikeQuantified {
expr: Box<Expr>,
negated: bool,
quantifier: LikeQuantifier,
patterns: LikePatterns,
},
Case {
operand: Option<Box<Expr>>,
branches: Vec<CaseWhen>,
else_result: Option<Box<Expr>>,
},
Cast {
expr: Box<Expr>,
data_type: DataType,
safe: bool,
format: Option<Box<Expr>>,
time_zone: Option<Box<Expr>>,
},
Extract {
part: Box<Expr>,
expr: Box<Expr>,
time_zone: Option<Box<Expr>>,
},
Struct {
fields: Vec<StructExprField>,
typed: Option<Vec<StructField>>,
},
Tuple(Vec<Expr>),
Array {
elements: Vec<Expr>,
element_type: Option<Box<DataType>>,
keyword: bool,
},
ArraySubquery(Box<Query>),
Subscript {
expr: Box<Expr>,
kind: SubscriptKind,
index: Box<Expr>,
},
FieldAccess {
expr: Box<Expr>,
field: Ident,
},
Function(Box<Function>),
Subquery(Box<Query>),
Exists(Box<Query>),
ScalarWith {
bindings: Vec<(Ident, Expr)>,
body: Box<Expr>,
},
Lambda {
params: Vec<Ident>,
body: Box<Expr>,
},
NamedArg {
name: Ident,
value: Box<Expr>,
},
Nested(Box<Expr>),
Default,
}
impl Expr {
pub fn ident(name: &str) -> Expr {
Expr::Identifier(Ident::new(name))
}
pub fn compound(parts: &[&str]) -> Expr {
Expr::CompoundIdentifier(parts.iter().map(|p| Ident::new(*p)).collect())
}
pub fn null() -> Expr {
Expr::Literal(Literal::Null)
}
pub fn binary(left: Expr, op: BinaryOperator, right: Expr) -> Expr {
Expr::BinaryOp {
left: Box::new(left),
op,
right: Box::new(right),
}
}
pub fn function(name: &str, args: Vec<Expr>) -> Expr {
Expr::Function(Box::new(Function::new(name, args)))
}
pub fn implicit_name(&self) -> Option<String> {
match self {
Expr::Identifier(ident) => Some(ident.value.clone()),
Expr::CompoundIdentifier(parts) => parts.last().map(|p| p.value.clone()),
Expr::FieldAccess { field, .. } => Some(field.value.clone()),
Expr::Nested(inner) => inner.implicit_name(),
_ => None,
}
}
pub fn unnested(&self) -> &Expr {
let mut expr = self;
while let Expr::Nested(inner) = expr {
expr = inner;
}
expr
}
pub fn children(&self) -> Vec<&Expr> {
let mut out: Vec<&Expr> = Vec::new();
match self {
Expr::Identifier(_)
| Expr::CompoundIdentifier(_)
| Expr::Parameter(_)
| Expr::Default
| Expr::Subquery(_)
| Expr::Exists(_)
| Expr::ArraySubquery(_) => {}
Expr::Literal(Literal::Interval(i)) => out.push(&i.value),
Expr::Literal(_) => {}
Expr::UnaryOp { expr, .. }
| Expr::IsNull { expr, .. }
| Expr::IsBool { expr, .. }
| Expr::Nested(expr)
| Expr::FieldAccess { expr, .. }
| Expr::InSubquery { expr, .. } => out.push(expr),
Expr::NamedArg { value, .. } => out.push(value),
Expr::BinaryOp { left, right, .. } | Expr::IsDistinctFrom { left, right, .. } => {
out.push(left);
out.push(right);
}
Expr::InList { expr, list, .. } => {
out.push(expr);
out.extend(list.iter());
}
Expr::InUnnest { expr, array, .. } => {
out.push(expr);
out.push(array);
}
Expr::Between {
expr, low, high, ..
} => {
out.push(expr);
out.push(low);
out.push(high);
}
Expr::Like { expr, pattern, .. } => {
out.push(expr);
out.push(pattern);
}
Expr::LikeQuantified { expr, patterns, .. } => {
out.push(expr);
match patterns {
LikePatterns::List(list) => out.extend(list.iter()),
LikePatterns::Unnest(e) => out.push(e),
LikePatterns::Subquery(_) => {}
}
}
Expr::Case {
operand,
branches,
else_result,
} => {
if let Some(e) = operand {
out.push(e);
}
for b in branches {
out.push(&b.condition);
out.push(&b.result);
}
if let Some(e) = else_result {
out.push(e);
}
}
Expr::Cast {
expr,
format,
time_zone,
..
} => {
out.push(expr);
out.extend(format.iter().map(|b| &**b));
out.extend(time_zone.iter().map(|b| &**b));
}
Expr::Extract {
part,
expr,
time_zone,
} => {
out.push(part);
out.push(expr);
out.extend(time_zone.iter().map(|b| &**b));
}
Expr::Struct { fields, .. } => out.extend(fields.iter().map(|f| &f.expr)),
Expr::Tuple(items)
| Expr::Array {
elements: items, ..
} => out.extend(items.iter()),
Expr::Subscript { expr, index, .. } => {
out.push(expr);
out.push(index);
}
Expr::Function(f) => {
for arg in &f.args {
if let FunctionArg::Expr(e) = arg {
out.push(e);
}
}
if let Some(h) = &f.having {
out.push(&h.expr);
}
out.extend(f.order_by.iter().map(|o| &o.expr));
if let Some(l) = &f.limit {
out.push(l);
}
if let Some(WindowType::Spec(spec)) = &f.over {
out.extend(spec.partition_by.iter());
out.extend(spec.order_by.iter().map(|o| &o.expr));
}
}
Expr::ScalarWith { bindings, body } => {
out.extend(bindings.iter().map(|(_, e)| e));
out.push(body);
}
Expr::Lambda { body, .. } => out.push(body),
}
out
}
pub fn walk_shallow<'e>(&'e self, f: &mut dyn FnMut(&'e Expr) -> bool) {
if f(self) {
for child in self.children() {
child.walk_shallow(f);
}
}
}
pub fn column_parts(&self) -> Option<Vec<&str>> {
match self {
Expr::Identifier(ident) => Some(vec![ident.value.as_str()]),
Expr::CompoundIdentifier(parts) => {
Some(parts.iter().map(|p| p.value.as_str()).collect())
}
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct StructField {
pub name: Option<Ident>,
pub data_type: DataType,
pub not_null: bool,
pub options: Vec<SqlOption>,
}
impl StructField {
pub fn new(name: Option<&str>, data_type: DataType) -> Self {
StructField {
name: name.map(Ident::new),
data_type,
not_null: false,
options: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DataType {
Int64,
Float64,
Numeric(Option<(u32, Option<u32>)>),
BigNumeric(Option<(u32, Option<u32>)>),
Bool,
String(Option<u64>),
Bytes(Option<u64>),
Date,
Datetime,
Time,
Timestamp,
Interval,
Json,
Geography,
Array(Box<DataType>),
Struct(Vec<StructField>),
Range(Box<DataType>),
Other(String),
}
impl DataType {
pub fn from_name(name: &str) -> Option<DataType> {
Some(match name.to_ascii_uppercase().as_str() {
"INT64" | "INT" | "INTEGER" | "BIGINT" | "SMALLINT" | "TINYINT" | "BYTEINT" => {
DataType::Int64
}
"FLOAT64" | "FLOAT" | "DOUBLE" => DataType::Float64,
"NUMERIC" | "DECIMAL" => DataType::Numeric(None),
"BIGNUMERIC" | "BIGDECIMAL" => DataType::BigNumeric(None),
"BOOL" | "BOOLEAN" => DataType::Bool,
"STRING" => DataType::String(None),
"BYTES" => DataType::Bytes(None),
"DATE" => DataType::Date,
"DATETIME" => DataType::Datetime,
"TIME" => DataType::Time,
"TIMESTAMP" => DataType::Timestamp,
"INTERVAL" => DataType::Interval,
"JSON" => DataType::Json,
"GEOGRAPHY" => DataType::Geography,
_ => return None,
})
}
pub fn is_type_name(name: &str) -> bool {
DataType::from_name(name).is_some()
|| matches!(
name.to_ascii_uppercase().as_str(),
"ARRAY" | "STRUCT" | "RANGE"
)
}
}
pub trait Visitor {
fn visit_query(&mut self, _query: &Query) {}
fn visit_select(&mut self, _select: &Select) {}
fn visit_expr(&mut self, _expr: &Expr) {}
fn visit_table_factor(&mut self, _factor: &TableFactor) {}
fn visit_statement(&mut self, _statement: &Statement) {}
}
pub fn walk_statement<V: Visitor>(statement: &Statement, v: &mut V) {
v.visit_statement(statement);
match statement {
Statement::Query(q) => walk_query(q, v),
Statement::CreateTable(c) => {
for col in &c.columns {
walk_column_def(col, v);
}
if let Some(copy) = &c.copy {
if let Some(e) = ©.system_time {
walk_expr(e, v);
}
}
for e in c
.default_collate
.iter()
.chain(c.partition_by.iter())
.chain(c.cluster_by.iter())
{
walk_expr(e, v);
}
walk_options(&c.options, v);
if let Some(q) = &c.query {
walk_query(q, v);
}
}
Statement::CreateView(c) => {
for e in c.partition_by.iter().chain(c.cluster_by.iter()) {
walk_expr(e, v);
}
for col in &c.columns {
walk_options(&col.options, v);
}
walk_options(&c.options, v);
walk_query(&c.query, v);
}
Statement::CreateFunction(f) => {
walk_options(&f.options, v);
if let FunctionBody::Expr(e) = &f.body {
walk_expr(e, v);
}
}
Statement::CreateTableFunction(f) => {
walk_options(&f.options, v);
walk_query(&f.query, v);
}
Statement::CreateProcedure(p) => {
walk_options(&p.options, v);
for s in p.body.iter().chain(p.exception.iter().flatten()) {
walk_statement(s, v);
}
}
Statement::CreateSchema(s) => {
if let Some(e) = &s.default_collate {
walk_expr(e, v);
}
walk_options(&s.options, v);
}
Statement::Insert(i) => match &i.source {
InsertSource::Values(rows) => {
for e in rows.iter().flatten() {
walk_expr(e, v);
}
}
InsertSource::Query(q) => walk_query(q, v),
},
Statement::Update(u) => {
for a in &u.assignments {
walk_expr(&a.value, v);
}
for t in &u.from {
walk_table_with_joins(t, v);
}
if let Some(e) = &u.selection {
walk_expr(e, v);
}
}
Statement::Delete(d) => {
if let Some(e) = &d.selection {
walk_expr(e, v);
}
}
Statement::Merge(m) => {
walk_table_factor(&m.source, v);
walk_expr(&m.on, v);
for clause in &m.clauses {
if let Some(e) = &clause.condition {
walk_expr(e, v);
}
match &clause.action {
MergeAction::Update(assignments) => {
for a in assignments {
walk_expr(&a.value, v);
}
}
MergeAction::Insert { values, .. } => {
for e in values {
walk_expr(e, v);
}
}
MergeAction::Delete => {}
}
}
}
Statement::AlterTable(a) => {
for action in &a.actions {
match action {
AlterAction::AddColumn { column, .. } => walk_column_def(column, v),
AlterAction::SetOptions(o) => walk_options(o, v),
AlterAction::SetDefaultCollate(e) => walk_expr(e, v),
AlterAction::AlterColumn { action, .. } => match action {
AlterColumnAction::SetOptions(o) => walk_options(o, v),
AlterColumnAction::SetDefault(e) => walk_expr(e, v),
_ => {}
},
_ => {}
}
}
}
Statement::Declare { default, .. } => {
if let Some(e) = default {
walk_expr(e, v);
}
}
Statement::Set { targets, value } => {
for e in targets {
walk_expr(e, v);
}
walk_expr(value, v);
}
Statement::BeginEnd {
body, exception, ..
} => {
for s in body.iter().chain(exception.iter().flatten()) {
walk_statement(s, v);
}
}
Statement::If {
branches,
else_branch,
}
| Statement::Case {
branches,
else_branch,
..
} => {
if let Statement::Case {
operand: Some(e), ..
} = statement
{
walk_expr(e, v);
}
for b in branches {
walk_expr(&b.condition, v);
for s in &b.body {
walk_statement(s, v);
}
}
for s in else_branch.iter().flatten() {
walk_statement(s, v);
}
}
Statement::Loop { body, .. } => {
for s in body {
walk_statement(s, v);
}
}
Statement::While {
condition, body, ..
} => {
walk_expr(condition, v);
for s in body {
walk_statement(s, v);
}
}
Statement::ForIn { query, body, .. } => {
walk_query(query, v);
for s in body {
walk_statement(s, v);
}
}
Statement::Repeat { body, until, .. } => {
for s in body {
walk_statement(s, v);
}
walk_expr(until, v);
}
Statement::Raise { message: Some(e) } => walk_expr(e, v),
Statement::Call { args, .. } => {
for e in args {
walk_expr(e, v);
}
}
Statement::ExecuteImmediate { sql, using, .. } => {
walk_expr(sql, v);
for u in using {
walk_expr(&u.expr, v);
}
}
Statement::Assert {
condition,
description,
} => {
walk_expr(condition, v);
if let Some(e) = description {
walk_expr(e, v);
}
}
Statement::ExportData(e) => {
walk_options(&e.options, v);
walk_query(&e.query, v);
}
Statement::Truncate { .. }
| Statement::Drop(_)
| Statement::Control { .. }
| Statement::Return
| Statement::Raise { message: None }
| Statement::Transaction(_)
| Statement::LoadData(_)
| Statement::Raw(_) => {}
}
}
fn walk_options<V: Visitor>(options: &[SqlOption], v: &mut V) {
for o in options {
walk_expr(&o.value, v);
}
}
fn walk_column_def<V: Visitor>(col: &ColumnDef, v: &mut V) {
if let Some(e) = &col.default {
walk_expr(e, v);
}
if let Some(e) = &col.collate {
walk_expr(e, v);
}
walk_options(&col.options, v);
}
pub fn walk_query<V: Visitor>(query: &Query, v: &mut V) {
v.visit_query(query);
if let Some(with) = &query.with {
for cte in &with.ctes {
walk_query(&cte.query, v);
}
}
walk_set_expr(&query.body, v);
for o in &query.order_by {
walk_order_by(o, v);
}
if let Some(limit) = &query.limit {
walk_expr(&limit.count, v);
if let Some(o) = &limit.offset {
walk_expr(o, v);
}
}
for pipe in &query.pipes {
walk_pipe(pipe, v);
}
}
fn walk_order_by<V: Visitor>(o: &OrderByExpr, v: &mut V) {
walk_expr(&o.expr, v);
if let Some(c) = &o.collate {
walk_expr(c, v);
}
}
fn walk_pipe<V: Visitor>(pipe: &PipeOperator, v: &mut V) {
match pipe {
PipeOperator::Where(e) => walk_expr(e, v),
PipeOperator::Select { items, .. }
| PipeOperator::Extend(items)
| PipeOperator::Window(items) => {
for item in items {
walk_select_item(item, v);
}
}
PipeOperator::Set(assignments) => {
for a in assignments {
walk_expr(&a.value, v);
}
}
PipeOperator::Aggregate {
items, group_by, ..
} => {
for item in items.iter().chain(group_by.iter()) {
walk_expr(&item.expr, v);
}
}
PipeOperator::Join(join) => walk_join(join, v),
PipeOperator::OrderBy(items) => {
for o in items {
walk_order_by(o, v);
}
}
PipeOperator::Limit(limit) => {
walk_expr(&limit.count, v);
if let Some(o) = &limit.offset {
walk_expr(o, v);
}
}
PipeOperator::SetOperation { queries, .. } => {
for q in queries {
walk_query(q, v);
}
}
PipeOperator::Call { function, .. } => walk_function(function, v),
PipeOperator::TableSample(s) => walk_expr(&s.size, v),
PipeOperator::Pivot {
aggregates,
value_column,
values,
..
} => {
for a in aggregates.iter().chain(values.iter()) {
walk_expr(&a.expr, v);
}
walk_expr(value_column, v);
}
PipeOperator::Assert { condition, payload } => {
walk_expr(condition, v);
for e in payload {
walk_expr(e, v);
}
}
PipeOperator::MatchRecognize { spec, .. } => {
for e in spec.exprs() {
walk_expr(e, v);
}
}
PipeOperator::Align { spec, .. } => {
for e in spec.exprs() {
walk_expr(e, v);
}
}
PipeOperator::Drop(_)
| PipeOperator::Rename(_)
| PipeOperator::As(_)
| PipeOperator::Distinct
| PipeOperator::Unpivot { .. } => {}
}
}
fn walk_set_expr<V: Visitor>(body: &SetExpr, v: &mut V) {
match body {
SetExpr::Select(select) => walk_select(select, v),
SetExpr::Query(q) => walk_query(q, v),
SetExpr::SetOperation { left, right, .. } => {
walk_set_expr(left, v);
walk_set_expr(right, v);
}
SetExpr::From(from) => {
for t in from {
walk_table_with_joins(t, v);
}
}
}
}
fn walk_select_item<V: Visitor>(item: &SelectItem, v: &mut V) {
match item {
SelectItem::Expr { expr, .. } => walk_expr(expr, v),
SelectItem::Wildcard(options) => {
for r in &options.replace {
walk_expr(&r.expr, v);
}
}
SelectItem::QualifiedWildcard { qualifier, options } => {
walk_expr(qualifier, v);
for r in &options.replace {
walk_expr(&r.expr, v);
}
}
}
}
pub fn walk_select<V: Visitor>(select: &Select, v: &mut V) {
v.visit_select(select);
for item in &select.projection {
walk_select_item(item, v);
}
for t in &select.from {
walk_table_with_joins(t, v);
}
if let Some(e) = &select.where_clause {
walk_expr(e, v);
}
if let Some(GroupBy::Items(items)) = &select.group_by {
for item in items {
walk_group_by_item(item, v);
}
}
for e in select.having.iter().chain(select.qualify.iter()) {
walk_expr(e, v);
}
for w in &select.window {
walk_window_spec(&w.spec, v);
}
}
fn walk_group_by_item<V: Visitor>(item: &GroupByItem, v: &mut V) {
match item {
GroupByItem::Expr(e) => walk_expr(e, v),
GroupByItem::Rollup(es) | GroupByItem::Cube(es) => {
for e in es {
walk_expr(e, v);
}
}
GroupByItem::GroupingSets(items) => {
for i in items {
walk_group_by_item(i, v);
}
}
GroupByItem::Empty => {}
}
}
fn walk_window_spec<V: Visitor>(spec: &WindowSpec, v: &mut V) {
for e in &spec.partition_by {
walk_expr(e, v);
}
for o in &spec.order_by {
walk_order_by(o, v);
}
if let Some(frame) = &spec.frame {
for bound in std::iter::once(&frame.start).chain(frame.end.iter()) {
if let FrameBound::Preceding(e) | FrameBound::Following(e) = bound {
walk_expr(e, v);
}
}
}
}
pub fn walk_table_with_joins<V: Visitor>(t: &TableWithJoins, v: &mut V) {
walk_table_factor(&t.relation, v);
for join in &t.joins {
walk_join(join, v);
}
}
fn walk_join<V: Visitor>(join: &Join, v: &mut V) {
walk_table_factor(&join.relation, v);
if let JoinConstraint::On(e) = &join.constraint {
walk_expr(e, v);
}
}
pub fn walk_table_factor<V: Visitor>(factor: &TableFactor, v: &mut V) {
v.visit_table_factor(factor);
match factor {
TableFactor::Table {
system_time,
sample,
..
} => {
if let Some(e) = system_time {
walk_expr(e, v);
}
if let Some(s) = sample {
walk_expr(&s.size, v);
}
}
TableFactor::Derived { subquery, .. } => walk_query(subquery, v),
TableFactor::Unnest { array, .. } => walk_expr(array, v),
TableFactor::TableFunction { function, .. } => walk_function(function, v),
TableFactor::NestedJoin { table, .. } => walk_table_with_joins(table, v),
TableFactor::Pivot {
table,
aggregates,
value_column,
values,
..
} => {
walk_table_factor(table, v);
for a in aggregates.iter().chain(values.iter()) {
walk_expr(&a.expr, v);
}
walk_expr(value_column, v);
}
TableFactor::Unpivot { table, .. } => walk_table_factor(table, v),
TableFactor::MatchRecognize { table, spec, .. } => {
walk_table_factor(table, v);
for e in spec.exprs() {
walk_expr(e, v);
}
}
TableFactor::Align { table, spec, .. } => {
walk_table_factor(table, v);
for e in spec.exprs() {
walk_expr(e, v);
}
}
}
}
fn walk_function<V: Visitor>(f: &Function, v: &mut V) {
for arg in &f.args {
if let FunctionArg::Expr(e) = arg {
walk_expr(e, v);
}
}
if let Some(h) = &f.having {
walk_expr(&h.expr, v);
}
for o in &f.order_by {
walk_order_by(o, v);
}
if let Some(l) = &f.limit {
walk_expr(l, v);
}
if let Some(WindowType::Spec(spec)) = &f.over {
walk_window_spec(spec, v);
}
}
pub fn walk_expr<V: Visitor>(expr: &Expr, v: &mut V) {
v.visit_expr(expr);
match expr {
Expr::Identifier(_) | Expr::CompoundIdentifier(_) | Expr::Parameter(_) | Expr::Default => {}
Expr::Literal(Literal::Interval(i)) => walk_expr(&i.value, v),
Expr::Literal(_) => {}
Expr::UnaryOp { expr, .. }
| Expr::IsNull { expr, .. }
| Expr::IsBool { expr, .. }
| Expr::Nested(expr)
| Expr::FieldAccess { expr, .. } => walk_expr(expr, v),
Expr::NamedArg { value, .. } => walk_expr(value, v),
Expr::BinaryOp { left, right, .. } | Expr::IsDistinctFrom { left, right, .. } => {
walk_expr(left, v);
walk_expr(right, v);
}
Expr::InList { expr, list, .. } => {
walk_expr(expr, v);
for e in list {
walk_expr(e, v);
}
}
Expr::InSubquery { expr, subquery, .. } => {
walk_expr(expr, v);
walk_query(subquery, v);
}
Expr::InUnnest { expr, array, .. } => {
walk_expr(expr, v);
walk_expr(array, v);
}
Expr::Between {
expr, low, high, ..
} => {
walk_expr(expr, v);
walk_expr(low, v);
walk_expr(high, v);
}
Expr::Like { expr, pattern, .. } => {
walk_expr(expr, v);
walk_expr(pattern, v);
}
Expr::LikeQuantified { expr, patterns, .. } => {
walk_expr(expr, v);
match patterns {
LikePatterns::List(list) => {
for e in list {
walk_expr(e, v);
}
}
LikePatterns::Unnest(e) => walk_expr(e, v),
LikePatterns::Subquery(q) => walk_query(q, v),
}
}
Expr::Case {
operand,
branches,
else_result,
} => {
if let Some(e) = operand {
walk_expr(e, v);
}
for b in branches {
walk_expr(&b.condition, v);
walk_expr(&b.result, v);
}
if let Some(e) = else_result {
walk_expr(e, v);
}
}
Expr::Cast {
expr,
format,
time_zone,
..
} => {
walk_expr(expr, v);
for e in format.iter().chain(time_zone.iter()) {
walk_expr(e, v);
}
}
Expr::Extract {
part,
expr,
time_zone,
} => {
walk_expr(part, v);
walk_expr(expr, v);
if let Some(e) = time_zone {
walk_expr(e, v);
}
}
Expr::Struct { fields, .. } => {
for f in fields {
walk_expr(&f.expr, v);
}
}
Expr::Tuple(items)
| Expr::Array {
elements: items, ..
} => {
for e in items {
walk_expr(e, v);
}
}
Expr::ArraySubquery(q) | Expr::Subquery(q) | Expr::Exists(q) => walk_query(q, v),
Expr::Subscript { expr, index, .. } => {
walk_expr(expr, v);
walk_expr(index, v);
}
Expr::Function(f) => walk_function(f, v),
Expr::ScalarWith { bindings, body } => {
for (_, e) in bindings {
walk_expr(e, v);
}
walk_expr(body, v);
}
Expr::Lambda { body, .. } => walk_expr(body, v),
}
}
struct ExprCollector<'a, F: FnMut(&Expr)>(&'a mut F);
impl<F: FnMut(&Expr)> Visitor for ExprCollector<'_, F> {
fn visit_expr(&mut self, expr: &Expr) {
(self.0)(expr)
}
}
struct SelectCollector<'a, F: FnMut(&Select)>(&'a mut F);
impl<F: FnMut(&Select)> Visitor for SelectCollector<'_, F> {
fn visit_select(&mut self, select: &Select) {
(self.0)(select)
}
}
#[derive(Default)]
struct DmlDetector {
found: bool,
}
impl Visitor for DmlDetector {
fn visit_statement(&mut self, statement: &Statement) {
if !matches!(statement, Statement::Query(_)) {
self.found = true;
}
}
}
impl Statement {
pub fn walk_exprs(&self, mut f: impl FnMut(&Expr)) {
walk_statement(self, &mut ExprCollector(&mut f));
}
pub fn walk_selects(&self, mut f: impl FnMut(&Select)) {
walk_statement(self, &mut SelectCollector(&mut f));
}
pub fn contains_dml_or_ddl(&self) -> bool {
let mut detector = DmlDetector::default();
walk_statement(self, &mut detector);
detector.found
}
pub fn referenced_tables(&self) -> Vec<TableName> {
let mut out = TableCollector::default();
out.statement(self);
out.finish()
}
pub fn query(&self) -> Option<&Query> {
match self {
Statement::Query(q) => Some(q),
Statement::CreateTable(c) => c.query.as_deref(),
Statement::CreateView(c) => Some(&c.query),
Statement::Insert(i) => match &i.source {
InsertSource::Query(q) => Some(q),
InsertSource::Values(_) => None,
},
Statement::ExportData(e) => Some(&e.query),
_ => None,
}
}
pub fn target_table(&self) -> Option<TableName> {
match self {
Statement::CreateTable(c) => Some(c.name.table_name()),
Statement::CreateView(c) => Some(c.name.table_name()),
Statement::Insert(i) => Some(i.table.table_name()),
Statement::Update(u) => Some(u.table.table_name()),
Statement::Delete(d) => Some(d.table.table_name()),
Statement::Merge(m) => Some(m.target.table_name()),
Statement::Truncate { name } => Some(name.table_name()),
Statement::Drop(d) if d.object_type.is_relation() => Some(d.name.table_name()),
Statement::AlterTable(a) => Some(a.name.table_name()),
_ => None,
}
}
}
impl Query {
pub fn walk_exprs(&self, mut f: impl FnMut(&Expr)) {
walk_query(self, &mut ExprCollector(&mut f));
}
pub fn walk_selects(&self, mut f: impl FnMut(&Select)) {
walk_query(self, &mut SelectCollector(&mut f));
}
pub fn referenced_tables(&self) -> Vec<TableName> {
let mut out = TableCollector::default();
out.query(self);
out.finish()
}
pub fn output_names(&self) -> Option<Vec<String>> {
if !self.pipes.is_empty() {
return None;
}
let mut body = &self.body;
loop {
match body {
SetExpr::SetOperation { left, .. } => body = left,
SetExpr::Query(q) => return q.output_names(),
SetExpr::Select(select) => {
return select
.projection
.iter()
.map(SelectItem::output_name)
.collect::<Option<Vec<_>>>();
}
SetExpr::From(_) => return None,
}
}
}
pub fn first_select_mut(&mut self) -> Option<&mut Select> {
fn first(body: &mut SetExpr) -> Option<&mut Select> {
match body {
SetExpr::Select(s) => Some(s),
SetExpr::Query(q) => q.first_select_mut(),
SetExpr::SetOperation { left, .. } => first(left),
SetExpr::From(_) => None,
}
}
first(&mut self.body)
}
pub fn visit_tables_mut(&mut self, f: &mut dyn FnMut(&mut TableFactor, bool)) {
let mut scopes: Vec<Vec<String>> = Vec::new();
visit_query_tables_mut(self, &mut scopes, f);
}
}
impl Statement {
pub fn visit_tables_mut(&mut self, f: &mut dyn FnMut(&mut TableFactor, bool)) {
let mut scopes: Vec<Vec<String>> = Vec::new();
match self {
Statement::Query(q) => visit_query_tables_mut(q, &mut scopes, f),
Statement::CreateTable(c) => {
if let Some(q) = &mut c.query {
visit_query_tables_mut(q, &mut scopes, f);
}
}
Statement::CreateView(c) => visit_query_tables_mut(&mut c.query, &mut scopes, f),
Statement::CreateTableFunction(c) => {
visit_query_tables_mut(&mut c.query, &mut scopes, f)
}
Statement::Insert(i) => match &mut i.source {
InsertSource::Query(q) => visit_query_tables_mut(q, &mut scopes, f),
InsertSource::Values(rows) => {
for e in rows.iter_mut().flatten() {
visit_expr_tables_mut(e, &mut scopes, f);
}
}
},
Statement::Update(u) => {
for a in &mut u.assignments {
visit_expr_tables_mut(&mut a.value, &mut scopes, f);
}
for t in &mut u.from {
visit_twj_tables_mut(t, &mut scopes, f);
}
if let Some(e) = &mut u.selection {
visit_expr_tables_mut(e, &mut scopes, f);
}
}
Statement::Delete(d) => {
if let Some(e) = &mut d.selection {
visit_expr_tables_mut(e, &mut scopes, f);
}
}
Statement::Merge(m) => {
visit_factor_tables_mut(&mut m.source, &mut scopes, f);
visit_expr_tables_mut(&mut m.on, &mut scopes, f);
for clause in &mut m.clauses {
if let Some(e) = &mut clause.condition {
visit_expr_tables_mut(e, &mut scopes, f);
}
match &mut clause.action {
MergeAction::Update(assignments) => {
for a in assignments {
visit_expr_tables_mut(&mut a.value, &mut scopes, f);
}
}
MergeAction::Insert { values, .. } => {
for e in values {
visit_expr_tables_mut(e, &mut scopes, f);
}
}
MergeAction::Delete => {}
}
}
}
Statement::ExportData(e) => visit_query_tables_mut(&mut e.query, &mut scopes, f),
Statement::ForIn { query, .. } => visit_query_tables_mut(query, &mut scopes, f),
Statement::Set { value, .. } => visit_expr_tables_mut(value, &mut scopes, f),
Statement::Declare {
default: Some(e), ..
} => visit_expr_tables_mut(e, &mut scopes, f),
_ => {}
}
}
}
fn bound(scopes: &[Vec<String>], name: &TableName) -> bool {
name.project.is_none()
&& name.dataset.is_none()
&& scopes
.iter()
.any(|scope| scope.iter().any(|n| n.eq_ignore_ascii_case(&name.name)))
}
fn visit_query_tables_mut(
query: &mut Query,
scopes: &mut Vec<Vec<String>>,
f: &mut dyn FnMut(&mut TableFactor, bool),
) {
let pushed = if let Some(with) = &mut query.with {
let names: Vec<String> = with.ctes.iter().map(|c| c.name.value.clone()).collect();
for index in 0..with.ctes.len() {
let visible = if with.recursive {
names.clone()
} else {
names[..index].to_vec()
};
scopes.push(visible);
visit_query_tables_mut(&mut with.ctes[index].query, scopes, f);
scopes.pop();
}
scopes.push(names);
true
} else {
false
};
visit_set_expr_tables_mut(&mut query.body, scopes, f);
for o in &mut query.order_by {
visit_expr_tables_mut(&mut o.expr, scopes, f);
}
for pipe in &mut query.pipes {
match pipe {
PipeOperator::Join(join) => {
visit_factor_tables_mut(&mut join.relation, scopes, f);
if let JoinConstraint::On(e) = &mut join.constraint {
visit_expr_tables_mut(e, scopes, f);
}
}
PipeOperator::SetOperation { queries, .. } => {
for q in queries {
visit_query_tables_mut(q, scopes, f);
}
}
PipeOperator::Where(e) => visit_expr_tables_mut(e, scopes, f),
PipeOperator::Select { items, .. }
| PipeOperator::Extend(items)
| PipeOperator::Window(items) => {
for item in items {
if let SelectItem::Expr { expr, .. } = item {
visit_expr_tables_mut(expr, scopes, f);
}
}
}
PipeOperator::Aggregate {
items, group_by, ..
} => {
for item in items.iter_mut().chain(group_by.iter_mut()) {
visit_expr_tables_mut(&mut item.expr, scopes, f);
}
}
PipeOperator::Set(assignments) => {
for a in assignments {
visit_expr_tables_mut(&mut a.value, scopes, f);
}
}
PipeOperator::Call { function, .. } => visit_function_tables_mut(function, scopes, f),
_ => {}
}
}
if pushed {
scopes.pop();
}
}
fn visit_set_expr_tables_mut(
body: &mut SetExpr,
scopes: &mut Vec<Vec<String>>,
f: &mut dyn FnMut(&mut TableFactor, bool),
) {
match body {
SetExpr::Select(select) => {
for item in &mut select.projection {
match item {
SelectItem::Expr { expr, .. } => visit_expr_tables_mut(expr, scopes, f),
SelectItem::Wildcard(o) | SelectItem::QualifiedWildcard { options: o, .. } => {
for r in &mut o.replace {
visit_expr_tables_mut(&mut r.expr, scopes, f);
}
}
}
}
for t in &mut select.from {
visit_twj_tables_mut(t, scopes, f);
}
for e in select
.where_clause
.iter_mut()
.chain(select.having.iter_mut())
.chain(select.qualify.iter_mut())
{
visit_expr_tables_mut(e, scopes, f);
}
if let Some(GroupBy::Items(items)) = &mut select.group_by {
for item in items {
if let GroupByItem::Expr(e) = item {
visit_expr_tables_mut(e, scopes, f);
}
}
}
}
SetExpr::Query(q) => visit_query_tables_mut(q, scopes, f),
SetExpr::SetOperation { left, right, .. } => {
visit_set_expr_tables_mut(left, scopes, f);
visit_set_expr_tables_mut(right, scopes, f);
}
SetExpr::From(from) => {
for t in from {
visit_twj_tables_mut(t, scopes, f);
}
}
}
}
fn visit_twj_tables_mut(
t: &mut TableWithJoins,
scopes: &mut Vec<Vec<String>>,
f: &mut dyn FnMut(&mut TableFactor, bool),
) {
visit_factor_tables_mut(&mut t.relation, scopes, f);
for join in &mut t.joins {
visit_factor_tables_mut(&mut join.relation, scopes, f);
if let JoinConstraint::On(e) = &mut join.constraint {
visit_expr_tables_mut(e, scopes, f);
}
}
}
fn visit_factor_tables_mut(
factor: &mut TableFactor,
scopes: &mut Vec<Vec<String>>,
f: &mut dyn FnMut(&mut TableFactor, bool),
) {
match factor {
TableFactor::Table { name, .. } => {
let is_cte = bound(scopes, &name.table_name());
f(factor, is_cte);
}
TableFactor::Derived { subquery, .. } => visit_query_tables_mut(subquery, scopes, f),
TableFactor::Unnest { array, .. } => visit_expr_tables_mut(array, scopes, f),
TableFactor::TableFunction { function, .. } => {
visit_function_tables_mut(function, scopes, f);
f(factor, false);
}
TableFactor::NestedJoin { table, .. } => visit_twj_tables_mut(table, scopes, f),
TableFactor::Pivot { table, .. }
| TableFactor::Unpivot { table, .. }
| TableFactor::MatchRecognize { table, .. }
| TableFactor::Align { table, .. } => visit_factor_tables_mut(table, scopes, f),
}
}
fn visit_function_tables_mut(
function: &mut Function,
scopes: &mut Vec<Vec<String>>,
f: &mut dyn FnMut(&mut TableFactor, bool),
) {
for arg in &mut function.args {
match arg {
FunctionArg::Expr(e) => visit_expr_tables_mut(e, scopes, f),
FunctionArg::Table(name) => {
let mut factor = TableFactor::table(name.clone(), None);
let is_cte = bound(scopes, &name.table_name());
f(&mut factor, is_cte);
if let TableFactor::Table { name: renamed, .. } = factor {
*name = renamed;
}
}
_ => {}
}
}
}
fn visit_expr_tables_mut(
expr: &mut Expr,
scopes: &mut Vec<Vec<String>>,
f: &mut dyn FnMut(&mut TableFactor, bool),
) {
match expr {
Expr::Subquery(q) | Expr::Exists(q) | Expr::ArraySubquery(q) => {
visit_query_tables_mut(q, scopes, f)
}
Expr::InSubquery { expr, subquery, .. } => {
visit_expr_tables_mut(expr, scopes, f);
visit_query_tables_mut(subquery, scopes, f);
}
Expr::LikeQuantified { expr, patterns, .. } => {
visit_expr_tables_mut(expr, scopes, f);
match patterns {
LikePatterns::Subquery(q) => visit_query_tables_mut(q, scopes, f),
LikePatterns::Unnest(e) => visit_expr_tables_mut(e, scopes, f),
LikePatterns::List(list) => {
for e in list {
visit_expr_tables_mut(e, scopes, f);
}
}
}
}
Expr::Function(function) => {
if let Some(h) = &mut function.having {
visit_expr_tables_mut(&mut h.expr, scopes, f);
}
visit_function_tables_mut(function, scopes, f)
}
Expr::UnaryOp { expr, .. }
| Expr::IsNull { expr, .. }
| Expr::IsBool { expr, .. }
| Expr::Nested(expr)
| Expr::FieldAccess { expr, .. } => visit_expr_tables_mut(expr, scopes, f),
Expr::NamedArg { value, .. } => visit_expr_tables_mut(value, scopes, f),
Expr::BinaryOp { left, right, .. } | Expr::IsDistinctFrom { left, right, .. } => {
visit_expr_tables_mut(left, scopes, f);
visit_expr_tables_mut(right, scopes, f);
}
Expr::InList { expr, list, .. } => {
visit_expr_tables_mut(expr, scopes, f);
for e in list {
visit_expr_tables_mut(e, scopes, f);
}
}
Expr::InUnnest { expr, array, .. } => {
visit_expr_tables_mut(expr, scopes, f);
visit_expr_tables_mut(array, scopes, f);
}
Expr::Between {
expr, low, high, ..
} => {
visit_expr_tables_mut(expr, scopes, f);
visit_expr_tables_mut(low, scopes, f);
visit_expr_tables_mut(high, scopes, f);
}
Expr::Like { expr, pattern, .. } => {
visit_expr_tables_mut(expr, scopes, f);
visit_expr_tables_mut(pattern, scopes, f);
}
Expr::Case {
operand,
branches,
else_result,
} => {
if let Some(e) = operand {
visit_expr_tables_mut(e, scopes, f);
}
for b in branches {
visit_expr_tables_mut(&mut b.condition, scopes, f);
visit_expr_tables_mut(&mut b.result, scopes, f);
}
if let Some(e) = else_result {
visit_expr_tables_mut(e, scopes, f);
}
}
Expr::Cast { expr, .. } => visit_expr_tables_mut(expr, scopes, f),
Expr::Extract { expr, .. } => visit_expr_tables_mut(expr, scopes, f),
Expr::Struct { fields, .. } => {
for field in fields {
visit_expr_tables_mut(&mut field.expr, scopes, f);
}
}
Expr::Tuple(items)
| Expr::Array {
elements: items, ..
} => {
for e in items {
visit_expr_tables_mut(e, scopes, f);
}
}
Expr::Subscript { expr, index, .. } => {
visit_expr_tables_mut(expr, scopes, f);
visit_expr_tables_mut(index, scopes, f);
}
Expr::ScalarWith { bindings, body } => {
for (_, e) in bindings {
visit_expr_tables_mut(e, scopes, f);
}
visit_expr_tables_mut(body, scopes, f);
}
Expr::Lambda { body, .. } => visit_expr_tables_mut(body, scopes, f),
Expr::Identifier(_)
| Expr::CompoundIdentifier(_)
| Expr::Literal(_)
| Expr::Parameter(_)
| Expr::Default => {}
}
}
#[derive(Default)]
struct TableCollector {
seen: indexmap::IndexMap<String, TableName>,
}
impl TableCollector {
fn add(&mut self, factor: &TableFactor, is_cte: bool) {
if is_cte {
return;
}
if let TableFactor::Table { name, .. } = factor {
let table = name.table_name();
self.seen.entry(table.key()).or_insert(table);
}
}
fn query(&mut self, query: &Query) {
let mut copy = query.clone();
copy.visit_tables_mut(&mut |factor, is_cte| self.add(factor, is_cte));
}
fn statement(&mut self, statement: &Statement) {
let mut copy = statement.clone();
copy.visit_tables_mut(&mut |factor, is_cte| self.add(factor, is_cte));
}
fn finish(self) -> Vec<TableName> {
self.seen.into_values().collect()
}
}
pub fn walk_expr_mut(expr: &mut Expr, into_queries: bool, f: &mut dyn FnMut(&mut Expr)) {
match expr {
Expr::Identifier(_) | Expr::CompoundIdentifier(_) | Expr::Parameter(_) | Expr::Default => {}
Expr::Literal(Literal::Interval(i)) => walk_expr_mut(&mut i.value, into_queries, f),
Expr::Literal(_) => {}
Expr::UnaryOp { expr: e, .. }
| Expr::IsNull { expr: e, .. }
| Expr::IsBool { expr: e, .. }
| Expr::Nested(e)
| Expr::FieldAccess { expr: e, .. } => walk_expr_mut(e, into_queries, f),
Expr::NamedArg { value, .. } => walk_expr_mut(value, into_queries, f),
Expr::BinaryOp { left, right, .. } | Expr::IsDistinctFrom { left, right, .. } => {
walk_expr_mut(left, into_queries, f);
walk_expr_mut(right, into_queries, f);
}
Expr::InList { expr: e, list, .. } => {
walk_expr_mut(e, into_queries, f);
for x in list {
walk_expr_mut(x, into_queries, f);
}
}
Expr::InSubquery {
expr: e, subquery, ..
} => {
walk_expr_mut(e, into_queries, f);
if into_queries {
walk_query_exprs_mut(subquery, f);
}
}
Expr::InUnnest { expr: e, array, .. } => {
walk_expr_mut(e, into_queries, f);
walk_expr_mut(array, into_queries, f);
}
Expr::Between {
expr: e, low, high, ..
} => {
walk_expr_mut(e, into_queries, f);
walk_expr_mut(low, into_queries, f);
walk_expr_mut(high, into_queries, f);
}
Expr::Like {
expr: e, pattern, ..
} => {
walk_expr_mut(e, into_queries, f);
walk_expr_mut(pattern, into_queries, f);
}
Expr::LikeQuantified {
expr: e, patterns, ..
} => {
walk_expr_mut(e, into_queries, f);
match patterns {
LikePatterns::List(list) => {
for x in list {
walk_expr_mut(x, into_queries, f);
}
}
LikePatterns::Unnest(a) => walk_expr_mut(a, into_queries, f),
LikePatterns::Subquery(q) => {
if into_queries {
walk_query_exprs_mut(q, f);
}
}
}
}
Expr::Case {
operand,
branches,
else_result,
} => {
if let Some(o) = operand {
walk_expr_mut(o, into_queries, f);
}
for b in branches {
walk_expr_mut(&mut b.condition, into_queries, f);
walk_expr_mut(&mut b.result, into_queries, f);
}
if let Some(x) = else_result {
walk_expr_mut(x, into_queries, f);
}
}
Expr::Cast {
expr: e,
format,
time_zone,
..
} => {
walk_expr_mut(e, into_queries, f);
for x in format.iter_mut().chain(time_zone.iter_mut()) {
walk_expr_mut(x, into_queries, f);
}
}
Expr::Extract {
part,
expr: e,
time_zone,
} => {
walk_expr_mut(part, into_queries, f);
walk_expr_mut(e, into_queries, f);
if let Some(x) = time_zone {
walk_expr_mut(x, into_queries, f);
}
}
Expr::Struct { fields, .. } => {
for field in fields {
walk_expr_mut(&mut field.expr, into_queries, f);
}
}
Expr::Tuple(items)
| Expr::Array {
elements: items, ..
} => {
for x in items {
walk_expr_mut(x, into_queries, f);
}
}
Expr::ArraySubquery(q) | Expr::Subquery(q) | Expr::Exists(q) => {
if into_queries {
walk_query_exprs_mut(q, f);
}
}
Expr::Subscript { expr: e, index, .. } => {
walk_expr_mut(e, into_queries, f);
walk_expr_mut(index, into_queries, f);
}
Expr::Function(function) => walk_function_mut(function, into_queries, f),
Expr::ScalarWith { bindings, body } => {
for (_, x) in bindings {
walk_expr_mut(x, into_queries, f);
}
walk_expr_mut(body, into_queries, f);
}
Expr::Lambda { body, .. } => walk_expr_mut(body, into_queries, f),
}
f(expr);
}
fn walk_function_mut(function: &mut Function, into_queries: bool, f: &mut dyn FnMut(&mut Expr)) {
for arg in &mut function.args {
if let FunctionArg::Expr(e) = arg {
walk_expr_mut(e, into_queries, f);
}
}
if let Some(h) = &mut function.having {
walk_expr_mut(&mut h.expr, into_queries, f);
}
for o in &mut function.order_by {
walk_expr_mut(&mut o.expr, into_queries, f);
}
if let Some(l) = &mut function.limit {
walk_expr_mut(l, into_queries, f);
}
if let Some(WindowType::Spec(spec)) = &mut function.over {
for e in &mut spec.partition_by {
walk_expr_mut(e, into_queries, f);
}
for o in &mut spec.order_by {
walk_expr_mut(&mut o.expr, into_queries, f);
}
}
}
fn walk_factor_exprs_mut(factor: &mut TableFactor, f: &mut dyn FnMut(&mut Expr)) {
match factor {
TableFactor::Table { system_time, .. } => {
if let Some(e) = system_time {
walk_expr_mut(e, true, f);
}
}
TableFactor::Derived { subquery, .. } => walk_query_exprs_mut(subquery, f),
TableFactor::Unnest { array, .. } => walk_expr_mut(array, true, f),
TableFactor::TableFunction { function, .. } => walk_function_mut(function, true, f),
TableFactor::NestedJoin { table, .. } => walk_twj_exprs_mut(table, f),
TableFactor::Pivot {
table,
aggregates,
value_column,
values,
..
} => {
walk_factor_exprs_mut(table, f);
for a in aggregates.iter_mut().chain(values.iter_mut()) {
walk_expr_mut(&mut a.expr, true, f);
}
walk_expr_mut(value_column, true, f);
}
TableFactor::Unpivot { table, .. } => walk_factor_exprs_mut(table, f),
TableFactor::MatchRecognize { table, spec, .. } => {
walk_factor_exprs_mut(table, f);
for e in spec.exprs_mut() {
walk_expr_mut(e, true, f);
}
}
TableFactor::Align { table, spec, .. } => {
walk_factor_exprs_mut(table, f);
for e in spec.exprs_mut() {
walk_expr_mut(e, true, f);
}
}
}
}
fn walk_twj_exprs_mut(t: &mut TableWithJoins, f: &mut dyn FnMut(&mut Expr)) {
walk_factor_exprs_mut(&mut t.relation, f);
for join in &mut t.joins {
walk_factor_exprs_mut(&mut join.relation, f);
if let JoinConstraint::On(e) = &mut join.constraint {
walk_expr_mut(e, true, f);
}
}
}
fn walk_items_mut(items: &mut [SelectItem], f: &mut dyn FnMut(&mut Expr)) {
for item in items {
match item {
SelectItem::Expr { expr, .. } => walk_expr_mut(expr, true, f),
SelectItem::Wildcard(o) => {
for r in &mut o.replace {
walk_expr_mut(&mut r.expr, true, f);
}
}
SelectItem::QualifiedWildcard { qualifier, options } => {
walk_expr_mut(qualifier, true, f);
for r in &mut options.replace {
walk_expr_mut(&mut r.expr, true, f);
}
}
}
}
}
fn walk_set_expr_exprs_mut(body: &mut SetExpr, f: &mut dyn FnMut(&mut Expr)) {
match body {
SetExpr::Select(s) => {
walk_items_mut(&mut s.projection, f);
for t in &mut s.from {
walk_twj_exprs_mut(t, f);
}
for e in s
.where_clause
.iter_mut()
.chain(s.having.iter_mut())
.chain(s.qualify.iter_mut())
{
walk_expr_mut(e, true, f);
}
if let Some(GroupBy::Items(items)) = &mut s.group_by {
fn group(item: &mut GroupByItem, f: &mut dyn FnMut(&mut Expr)) {
match item {
GroupByItem::Expr(e) => walk_expr_mut(e, true, f),
GroupByItem::Rollup(es) | GroupByItem::Cube(es) => {
for e in es {
walk_expr_mut(e, true, f);
}
}
GroupByItem::GroupingSets(items) => {
for i in items {
group(i, f);
}
}
GroupByItem::Empty => {}
}
}
for item in items {
group(item, f);
}
}
for w in &mut s.window {
for e in &mut w.spec.partition_by {
walk_expr_mut(e, true, f);
}
for o in &mut w.spec.order_by {
walk_expr_mut(&mut o.expr, true, f);
}
}
}
SetExpr::Query(q) => walk_query_exprs_mut(q, f),
SetExpr::SetOperation { left, right, .. } => {
walk_set_expr_exprs_mut(left, f);
walk_set_expr_exprs_mut(right, f);
}
SetExpr::From(from) => {
for t in from {
walk_twj_exprs_mut(t, f);
}
}
}
}
pub fn walk_query_exprs_mut(query: &mut Query, f: &mut dyn FnMut(&mut Expr)) {
if let Some(with) = &mut query.with {
for cte in &mut with.ctes {
walk_query_exprs_mut(&mut cte.query, f);
}
}
walk_set_expr_exprs_mut(&mut query.body, f);
for o in &mut query.order_by {
walk_expr_mut(&mut o.expr, true, f);
}
if let Some(limit) = &mut query.limit {
walk_expr_mut(&mut limit.count, true, f);
if let Some(o) = &mut limit.offset {
walk_expr_mut(o, true, f);
}
}
for pipe in &mut query.pipes {
match pipe {
PipeOperator::Where(e) => walk_expr_mut(e, true, f),
PipeOperator::Select { items, .. }
| PipeOperator::Extend(items)
| PipeOperator::Window(items) => walk_items_mut(items, f),
PipeOperator::Set(assignments) => {
for a in assignments {
walk_expr_mut(&mut a.value, true, f);
}
}
PipeOperator::Aggregate {
items, group_by, ..
} => {
for item in items.iter_mut().chain(group_by.iter_mut()) {
walk_expr_mut(&mut item.expr, true, f);
}
}
PipeOperator::Join(join) => {
walk_factor_exprs_mut(&mut join.relation, f);
if let JoinConstraint::On(e) = &mut join.constraint {
walk_expr_mut(e, true, f);
}
}
PipeOperator::OrderBy(items) => {
for o in items {
walk_expr_mut(&mut o.expr, true, f);
}
}
PipeOperator::Limit(limit) => walk_expr_mut(&mut limit.count, true, f),
PipeOperator::SetOperation { queries, .. } => {
for q in queries {
walk_query_exprs_mut(q, f);
}
}
PipeOperator::Call { function, .. } => walk_function_mut(function, true, f),
PipeOperator::Assert { condition, .. } => walk_expr_mut(condition, true, f),
PipeOperator::MatchRecognize { spec, .. } => {
for e in spec.exprs_mut() {
walk_expr_mut(e, true, f);
}
}
PipeOperator::Align { spec, .. } => {
for e in spec.exprs_mut() {
walk_expr_mut(e, true, f);
}
}
_ => {}
}
}
}
pub fn walk_statement_exprs_mut(statement: &mut Statement, f: &mut dyn FnMut(&mut Expr)) {
match statement {
Statement::Query(q) => walk_query_exprs_mut(q, f),
Statement::CreateTable(c) => {
if let Some(q) = &mut c.query {
walk_query_exprs_mut(q, f);
}
}
Statement::CreateView(c) => walk_query_exprs_mut(&mut c.query, f),
Statement::CreateTableFunction(c) => walk_query_exprs_mut(&mut c.query, f),
Statement::Insert(i) => match &mut i.source {
InsertSource::Query(q) => walk_query_exprs_mut(q, f),
InsertSource::Values(rows) => {
for e in rows.iter_mut().flatten() {
walk_expr_mut(e, true, f);
}
}
},
Statement::Update(u) => {
for a in &mut u.assignments {
walk_expr_mut(&mut a.value, true, f);
}
for t in &mut u.from {
walk_twj_exprs_mut(t, f);
}
if let Some(e) = &mut u.selection {
walk_expr_mut(e, true, f);
}
}
Statement::Delete(d) => {
if let Some(e) = &mut d.selection {
walk_expr_mut(e, true, f);
}
}
Statement::Merge(m) => {
walk_factor_exprs_mut(&mut m.source, f);
walk_expr_mut(&mut m.on, true, f);
for clause in &mut m.clauses {
if let Some(e) = &mut clause.condition {
walk_expr_mut(e, true, f);
}
match &mut clause.action {
MergeAction::Update(assignments) => {
for a in assignments {
walk_expr_mut(&mut a.value, true, f);
}
}
MergeAction::Insert { values, .. } => {
for e in values {
walk_expr_mut(e, true, f);
}
}
MergeAction::Delete => {}
}
}
}
Statement::ExportData(e) => walk_query_exprs_mut(&mut e.query, f),
Statement::Set { value, .. } => walk_expr_mut(value, true, f),
Statement::Declare {
default: Some(e), ..
} => walk_expr_mut(e, true, f),
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn object_name_parts_split_backticked_paths() {
let name = ObjectName(vec![Ident::quoted("p.d.t")]);
assert_eq!(name.parts(), vec!["p", "d", "t"]);
let t = name.table_name();
assert_eq!(t.project.as_deref(), Some("p"));
assert_eq!(t.dataset.as_deref(), Some("d"));
assert_eq!(t.name, "t");
assert_eq!(TableName::parse("`p.d`.t"), t);
assert!(TableName::new("x").is_temp_name());
assert!(TableName::parse("_SESSION.x").is_temp_name());
assert!(!TableName::parse("d.x").is_temp_name());
}
#[test]
fn ident_equality_ignores_quotes() {
assert_eq!(Ident::new("a"), Ident::quoted("a"));
let a = Literal::String(StringLiteral {
value: "x".into(),
raw: true,
quote: QuoteStyle::Double,
});
assert_eq!(a, Literal::string("x"));
}
#[test]
fn data_type_aliases() {
assert_eq!(DataType::from_name("integer"), Some(DataType::Int64));
assert_eq!(
DataType::from_name("DECIMAL"),
Some(DataType::Numeric(None))
);
assert!(DataType::is_type_name("struct"));
assert!(!DataType::is_type_name("foo"));
}
}