use crate::ast::*;
use crate::token::{escape_identifier, escape_string, is_reserved_keyword, QuoteStyle};
pub fn to_sql(statement: &Statement) -> String {
Printer { pretty: true }.statement(statement, 0)
}
pub fn to_sql_compact(statement: &Statement) -> String {
Printer { pretty: false }.statement(statement, 0)
}
pub fn statements_to_sql(statements: &[Statement]) -> String {
let printer = Printer { pretty: true };
statements
.iter()
.map(|s| format!("{};", printer.statement(s, 0)))
.collect::<Vec<_>>()
.join("\n\n")
}
pub fn query_to_sql(query: &Query) -> String {
Printer { pretty: true }.query(query, 0)
}
pub fn query_to_sql_compact(query: &Query) -> String {
Printer { pretty: false }.query(query, 0)
}
pub fn expr_to_sql(expr: &Expr) -> String {
Printer { pretty: false }.expr(expr, 0)
}
pub fn data_type_to_sql(data_type: &DataType) -> String {
Printer { pretty: false }.data_type(data_type)
}
pub fn table_factor_to_sql(factor: &TableFactor) -> String {
Printer { pretty: false }.table_factor(factor, 0)
}
fn is_plain_word(value: &str) -> bool {
let mut chars = value.chars();
matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
pub fn ident_to_sql(ident: &Ident) -> String {
if ident.quoted || !is_plain_word(&ident.value) || is_reserved_keyword(&ident.value) {
format!("`{}`", escape_identifier(&ident.value))
} else {
ident.value.clone()
}
}
fn path_part(ident: &Ident) -> String {
if ident.quoted
|| ident.value.is_empty()
|| !ident
.value
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_')
{
format!("`{}`", escape_identifier(&ident.value))
} else {
ident.value.clone()
}
}
fn table_first_part(ident: &Ident) -> String {
let dashed = !ident.quoted
&& ident.value.contains('-')
&& ident
.value
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
&& ident.value.starts_with(|c: char| c.is_ascii_alphabetic());
if dashed {
ident.value.clone()
} else {
ident_to_sql(ident)
}
}
pub fn object_name_to_sql(name: &ObjectName) -> String {
name.0
.iter()
.enumerate()
.map(|(i, part)| {
if i == 0 {
table_first_part(part)
} else {
path_part(part)
}
})
.collect::<Vec<_>>()
.join(".")
}
fn function_name(name: &ObjectName) -> String {
name.0
.iter()
.map(|part| {
if part.quoted
|| !part
.value
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_')
{
format!("`{}`", escape_identifier(&part.value))
} else {
part.value.clone()
}
})
.collect::<Vec<_>>()
.join(".")
}
fn quote_string(value: &str) -> String {
format!("'{}'", escape_string(value, QuoteStyle::Single))
}
fn raw_ok(value: &str, quote: QuoteStyle) -> bool {
if !quote.is_triple() && (value.contains('\n') || value.contains('\r')) {
return false;
}
if quote.is_triple() && value.ends_with(quote.quote_char()) {
return false;
}
let trailing = value.chars().rev().take_while(|c| *c == '\\').count();
if trailing % 2 == 1 {
return false;
}
let delimiter = quote.delimiter().as_bytes();
let bytes = value.as_bytes();
let mut index = 0;
while index < bytes.len() {
if bytes[index] == b'\\' {
index += 2;
continue;
}
if bytes[index..].starts_with(delimiter) {
return false;
}
index += 1;
}
true
}
fn escape_bytes(value: &[u8]) -> String {
let mut out = String::new();
for &b in value {
match b {
b'\\' => out.push_str("\\\\"),
b'\'' => out.push_str("\\'"),
b'\n' => out.push_str("\\n"),
b'\t' => out.push_str("\\t"),
b'\r' => out.push_str("\\r"),
0x20..=0x7e => out.push(b as char),
_ => out.push_str(&format!("\\x{b:02x}")),
}
}
out
}
fn precedence(expr: &Expr) -> u8 {
match expr {
Expr::BinaryOp { op, .. } => op.precedence(),
Expr::IsNull { .. }
| Expr::IsBool { .. }
| Expr::IsDistinctFrom { .. }
| Expr::InList { .. }
| Expr::InSubquery { .. }
| Expr::InUnnest { .. }
| Expr::Between { .. }
| Expr::Like { .. }
| Expr::LikeQuantified { .. } => COMPARISON_PRECEDENCE,
Expr::UnaryOp {
op: UnaryOperator::Not,
..
} => NOT_PRECEDENCE,
Expr::UnaryOp { .. } => UNARY_PRECEDENCE,
Expr::Lambda { .. } | Expr::NamedArg { .. } => 0,
_ => 255,
}
}
struct Printer {
pretty: bool,
}
impl Printer {
fn nl(&self, indent: usize) -> String {
if self.pretty {
format!("\n{}", " ".repeat(indent))
} else {
" ".to_string()
}
}
fn subquery(&self, query: &Query, indent: usize) -> String {
if self.pretty {
format!(
"({}{}{})",
self.nl(indent + 1),
self.query(query, indent + 1),
self.nl(indent)
)
} else {
format!("({})", self.query(query, indent))
}
}
fn list<T>(&self, items: &[T], f: impl Fn(&T) -> String) -> String {
items.iter().map(f).collect::<Vec<_>>().join(", ")
}
fn block(&self, statements: &[Statement], indent: usize) -> String {
let mut out = String::new();
for s in statements {
out.push_str(&self.nl(indent + 1));
out.push_str(&self.statement(s, indent + 1));
out.push(';');
}
out
}
fn label(&self, label: &Option<Ident>) -> String {
label
.as_ref()
.map(|l| format!("{}: ", ident_to_sql(l)))
.unwrap_or_default()
}
fn end_label(&self, label: &Option<Ident>) -> String {
label
.as_ref()
.map(|l| format!(" {}", ident_to_sql(l)))
.unwrap_or_default()
}
fn options(&self, options: &[SqlOption], indent: usize) -> String {
format!(
"OPTIONS({})",
self.list(options, |o| format!(
"{} = {}",
path_part(&o.name),
self.expr(&o.value, indent)
))
)
}
fn statement(&self, statement: &Statement, i: usize) -> String {
match statement {
Statement::Query(q) => self.query(q, i),
Statement::CreateTable(c) => self.create_table(c, i),
Statement::CreateView(c) => {
let mut out = String::from("CREATE ");
if c.or_replace {
out.push_str("OR REPLACE ");
}
out.push_str(if c.materialized {
"MATERIALIZED VIEW "
} else {
"VIEW "
});
if c.if_not_exists {
out.push_str("IF NOT EXISTS ");
}
out.push_str(&object_name_to_sql(&c.name));
if !c.columns.is_empty() {
out.push_str(&format!(
" ({})",
self.list(&c.columns, |col| {
let mut s = ident_to_sql(&col.name);
if !col.options.is_empty() {
s.push(' ');
s.push_str(&self.options(&col.options, i));
}
s
})
));
}
if let Some(p) = &c.partition_by {
out.push_str(&format!("{}PARTITION BY {}", self.nl(i), self.expr(p, i)));
}
if !c.cluster_by.is_empty() {
out.push_str(&format!(
"{}CLUSTER BY {}",
self.nl(i),
self.list(&c.cluster_by, |e| self.expr(e, i))
));
}
if !c.options.is_empty() {
out.push_str(&self.nl(i));
out.push_str(&self.options(&c.options, i));
}
out.push_str(&format!(" AS{}{}", self.nl(i), self.query(&c.query, i)));
out
}
Statement::CreateFunction(f) => self.create_function(f, i),
Statement::CreateTableFunction(f) => {
let mut out = String::from("CREATE ");
if f.or_replace {
out.push_str("OR REPLACE ");
}
if f.temporary {
out.push_str("TEMP ");
}
out.push_str("TABLE FUNCTION ");
if f.if_not_exists {
out.push_str("IF NOT EXISTS ");
}
out.push_str(&object_name_to_sql(&f.name));
out.push_str(&self.function_params(&f.params));
if let Some(returns) = &f.returns {
out.push_str(&format!(" RETURNS TABLE<{}>", self.struct_fields(returns)));
}
if !f.options.is_empty() {
out.push(' ');
out.push_str(&self.options(&f.options, i));
}
out.push_str(&format!(" AS{}{}", self.nl(i), self.query(&f.query, i)));
out
}
Statement::CreateProcedure(p) => {
let mut out = String::from("CREATE ");
if p.or_replace {
out.push_str("OR REPLACE ");
}
out.push_str("PROCEDURE ");
if p.if_not_exists {
out.push_str("IF NOT EXISTS ");
}
out.push_str(&object_name_to_sql(&p.name));
out.push_str(&format!(
"({})",
self.list(&p.params, |param| {
let mode = match param.mode {
Some(ParamMode::In) => "IN ",
Some(ParamMode::Out) => "OUT ",
Some(ParamMode::InOut) => "INOUT ",
None => "",
};
format!(
"{mode}{} {}",
ident_to_sql(¶m.name),
self.param_type(¶m.param_type)
)
})
));
if !p.options.is_empty() {
out.push(' ');
out.push_str(&self.options(&p.options, i));
}
out.push_str(&format!("{}BEGIN", self.nl(i)));
out.push_str(&self.block(&p.body, i));
if let Some(handler) = &p.exception {
out.push_str(&format!("{}EXCEPTION WHEN ERROR THEN", self.nl(i)));
out.push_str(&self.block(handler, i));
}
out.push_str(&format!("{}END", self.nl(i)));
out
}
Statement::CreateSchema(s) => {
let mut out = String::from("CREATE SCHEMA ");
if s.if_not_exists {
out.push_str("IF NOT EXISTS ");
}
out.push_str(&object_name_to_sql(&s.name));
if let Some(c) = &s.default_collate {
out.push_str(&format!(" DEFAULT COLLATE {}", self.expr(c, i)));
}
if !s.options.is_empty() {
out.push(' ');
out.push_str(&self.options(&s.options, i));
}
out
}
Statement::Insert(ins) => {
let mut out = format!("INSERT INTO {}", object_name_to_sql(&ins.table));
if !ins.columns.is_empty() {
out.push_str(&format!(" ({})", self.list(&ins.columns, ident_to_sql)));
}
match &ins.source {
InsertSource::Values(rows) => {
out.push_str(&format!("{}VALUES ", self.nl(i)));
out.push_str(&self.list(rows, |row| {
format!("({})", self.list(row, |e| self.expr(e, i)))
}));
}
InsertSource::Query(q) => {
out.push_str(&self.nl(i));
out.push_str(&self.query(q, i));
}
}
out
}
Statement::Update(u) => {
let mut out = format!("UPDATE {}", object_name_to_sql(&u.table));
if let Some(a) = &u.alias {
out.push_str(&format!(" AS {}", ident_to_sql(a)));
}
out.push_str(&format!(
"{}SET {}",
self.nl(i),
self.assignments(&u.assignments, i)
));
if !u.from.is_empty() {
out.push_str(&format!(
"{}FROM {}",
self.nl(i),
self.table_list(&u.from, i)
));
}
if let Some(w) = &u.selection {
out.push_str(&format!("{}WHERE {}", self.nl(i), self.expr(w, i)));
}
out
}
Statement::Delete(d) => {
let mut out = format!("DELETE FROM {}", object_name_to_sql(&d.table));
if let Some(a) = &d.alias {
out.push_str(&format!(" AS {}", ident_to_sql(a)));
}
if let Some(w) = &d.selection {
out.push_str(&format!("{}WHERE {}", self.nl(i), self.expr(w, i)));
}
out
}
Statement::Merge(m) => {
let mut out = format!("MERGE INTO {}", object_name_to_sql(&m.target));
if let Some(a) = &m.target_alias {
out.push_str(&format!(" AS {}", ident_to_sql(a)));
}
out.push_str(&format!(
"{}USING {}",
self.nl(i),
self.table_factor(&m.source, i)
));
out.push_str(&format!("{}ON {}", self.nl(i), self.expr(&m.on, i)));
for clause in &m.clauses {
out.push_str(&self.nl(i));
out.push_str(match clause.kind {
MergeMatch::Matched => "WHEN MATCHED",
MergeMatch::NotMatchedByTarget if clause.explicit_by_target => {
"WHEN NOT MATCHED BY TARGET"
}
MergeMatch::NotMatchedByTarget => "WHEN NOT MATCHED",
MergeMatch::NotMatchedBySource => "WHEN NOT MATCHED BY SOURCE",
});
if let Some(c) = &clause.condition {
out.push_str(&format!(" AND {}", self.expr(c, i)));
}
out.push_str(" THEN ");
match &clause.action {
MergeAction::Update(a) => {
out.push_str(&format!("UPDATE SET {}", self.assignments(a, i)))
}
MergeAction::Delete => out.push_str("DELETE"),
MergeAction::Insert {
columns,
values,
row,
} => {
out.push_str("INSERT");
if !columns.is_empty() {
out.push_str(&format!(" ({})", self.list(columns, ident_to_sql)));
}
if *row {
out.push_str(" ROW");
} else {
out.push_str(&format!(
" VALUES ({})",
self.list(values, |e| self.expr(e, i))
));
}
}
}
}
out
}
Statement::Drop(d) => {
let mut out = format!("DROP {} ", d.object_type.keyword());
if d.if_exists {
out.push_str("IF EXISTS ");
}
out.push_str(&object_name_to_sql(&d.name));
match d.cascade {
Some(true) => out.push_str(" CASCADE"),
Some(false) => out.push_str(" RESTRICT"),
None => {}
}
out
}
Statement::AlterTable(a) => {
let mut out = format!("ALTER {} ", a.object_type.keyword());
if a.if_exists {
out.push_str("IF EXISTS ");
}
out.push_str(&object_name_to_sql(&a.name));
out.push(' ');
out.push_str(&self.list(&a.actions, |action| self.alter_action(action, i)));
out
}
Statement::Truncate { name } => format!("TRUNCATE TABLE {}", object_name_to_sql(name)),
Statement::Declare {
names,
data_type,
default,
} => {
let mut out = format!("DECLARE {}", self.list(names, ident_to_sql));
if let Some(t) = data_type {
out.push(' ');
out.push_str(&self.data_type(t));
}
if let Some(d) = default {
out.push_str(&format!(" DEFAULT {}", self.expr(d, i)));
}
out
}
Statement::Set { targets, value } => {
let target = if targets.len() == 1 {
self.expr(&targets[0], i)
} else {
format!("({})", self.list(targets, |e| self.expr(e, i)))
};
format!("SET {target} = {}", self.expr(value, i))
}
Statement::BeginEnd {
label,
body,
exception,
} => {
let mut out = format!("{}BEGIN", self.label(label));
out.push_str(&self.block(body, i));
if let Some(handler) = exception {
out.push_str(&format!("{}EXCEPTION WHEN ERROR THEN", self.nl(i)));
out.push_str(&self.block(handler, i));
}
out.push_str(&format!("{}END{}", self.nl(i), self.end_label(label)));
out
}
Statement::If {
branches,
else_branch,
} => {
let mut out = String::new();
for (index, branch) in branches.iter().enumerate() {
if index == 0 {
out.push_str("IF ");
} else {
out.push_str(&format!("{}ELSEIF ", self.nl(i)));
}
out.push_str(&format!("{} THEN", self.expr(&branch.condition, i)));
out.push_str(&self.block(&branch.body, i));
}
if let Some(e) = else_branch {
out.push_str(&format!("{}ELSE", self.nl(i)));
out.push_str(&self.block(e, i));
}
out.push_str(&format!("{}END IF", self.nl(i)));
out
}
Statement::Case {
operand,
branches,
else_branch,
} => {
let mut out = String::from("CASE");
if let Some(o) = operand {
out.push_str(&format!(" {}", self.expr(o, i)));
}
for branch in branches {
out.push_str(&format!(
"{}WHEN {} THEN",
self.nl(i),
self.expr(&branch.condition, i)
));
out.push_str(&self.block(&branch.body, i));
}
if let Some(e) = else_branch {
out.push_str(&format!("{}ELSE", self.nl(i)));
out.push_str(&self.block(e, i));
}
out.push_str(&format!("{}END CASE", self.nl(i)));
out
}
Statement::Loop { label, body } => format!(
"{}LOOP{}{}END LOOP{}",
self.label(label),
self.block(body, i),
self.nl(i),
self.end_label(label)
),
Statement::While {
label,
condition,
body,
} => format!(
"{}WHILE {} DO{}{}END WHILE{}",
self.label(label),
self.expr(condition, i),
self.block(body, i),
self.nl(i),
self.end_label(label)
),
Statement::ForIn {
label,
variable,
query,
body,
} => format!(
"{}FOR {} IN {} DO{}{}END FOR{}",
self.label(label),
ident_to_sql(variable),
self.subquery(query, i),
self.block(body, i),
self.nl(i),
self.end_label(label)
),
Statement::Repeat { label, body, until } => format!(
"{}REPEAT{}{}UNTIL {}{}END REPEAT{}",
self.label(label),
self.block(body, i),
self.nl(i),
self.expr(until, i),
self.nl(i),
self.end_label(label)
),
Statement::Control { kind, label } => {
let word = match kind {
ControlKind::Break => "BREAK",
ControlKind::Leave => "LEAVE",
ControlKind::Continue => "CONTINUE",
ControlKind::Iterate => "ITERATE",
};
format!("{word}{}", self.end_label(label))
}
Statement::Return => "RETURN".to_string(),
Statement::Raise { message } => match message {
Some(m) => format!("RAISE USING MESSAGE = {}", self.expr(m, i)),
None => "RAISE".to_string(),
},
Statement::Call { procedure, args } => {
format!(
"CALL {}({})",
object_name_to_sql(procedure),
self.list(args, |e| self.expr(e, i))
)
}
Statement::ExecuteImmediate { sql, into, using } => {
let mut out = format!("EXECUTE IMMEDIATE {}", self.expr(sql, i));
if !into.is_empty() {
out.push_str(&format!(" INTO {}", self.list(into, ident_to_sql)));
}
if !using.is_empty() {
out.push_str(&format!(
" USING {}",
self.list(using, |u| match &u.alias {
Some(a) => format!("{} AS {}", self.expr(&u.expr, i), ident_to_sql(a)),
None => self.expr(&u.expr, i),
})
));
}
out
}
Statement::Assert {
condition,
description,
} => {
let mut out = format!("ASSERT {}", self.expr(condition, i));
if let Some(d) = description {
out.push_str(&format!(" AS {}", self.expr(d, i)));
}
out
}
Statement::Transaction(kind) => match kind {
TransactionKind::Begin => "BEGIN TRANSACTION".to_string(),
TransactionKind::Commit => "COMMIT TRANSACTION".to_string(),
TransactionKind::Rollback => "ROLLBACK TRANSACTION".to_string(),
},
Statement::ExportData(e) => {
let mut out = String::from("EXPORT DATA");
if let Some(c) = &e.connection {
out.push_str(&format!(" WITH CONNECTION {}", object_name_to_sql(c)));
}
if !e.options.is_empty() {
out.push(' ');
out.push_str(&self.options(&e.options, i));
}
out.push_str(&format!(" AS{}{}", self.nl(i), self.query(&e.query, i)));
out
}
Statement::LoadData(l) => {
let mut out = format!(
"LOAD DATA {} ",
if l.overwrite { "OVERWRITE" } else { "INTO" }
);
if l.temporary {
out.push_str("TEMP TABLE ");
}
out.push_str(&object_name_to_sql(&l.table));
if !l.rest.is_empty() {
out.push(' ');
out.push_str(&l.rest);
}
out
}
Statement::Raw(text) => text.clone(),
}
}
fn assignments(&self, assignments: &[Assignment], i: usize) -> String {
self.list(assignments, |a| {
let target = a
.target
.iter()
.enumerate()
.map(|(n, p)| {
if n == 0 {
ident_to_sql(p)
} else {
path_part(p)
}
})
.collect::<Vec<_>>()
.join(".");
format!("{target} = {}", self.expr(&a.value, i))
})
}
fn create_table(&self, c: &CreateTable, i: usize) -> String {
let mut out = String::from("CREATE ");
if c.or_replace {
out.push_str("OR REPLACE ");
}
if c.temporary {
out.push_str("TEMP ");
}
out.push_str(match c.kind {
TableKind::Table => "TABLE ",
TableKind::External => "EXTERNAL TABLE ",
TableKind::Snapshot => "SNAPSHOT TABLE ",
});
if c.if_not_exists {
out.push_str("IF NOT EXISTS ");
}
out.push_str(&object_name_to_sql(&c.name));
if !c.columns.is_empty() || !c.constraints.is_empty() {
let mut parts: Vec<String> = c
.columns
.iter()
.map(|col| self.column_def(col, i))
.collect();
parts.extend(c.constraints.iter().map(|k| self.constraint(k)));
if self.pretty {
out.push_str(" (");
for (n, part) in parts.iter().enumerate() {
out.push_str(&self.nl(i + 1));
out.push_str(part);
if n + 1 < parts.len() {
out.push(',');
}
}
out.push_str(&format!("{})", self.nl(i)));
} else {
out.push_str(&format!(" ({})", parts.join(", ")));
}
}
if let Some(copy) = &c.copy {
let word = match copy.kind {
CopyKind::Like => "LIKE",
CopyKind::Copy => "COPY",
CopyKind::Clone => "CLONE",
};
out.push_str(&format!(" {word} {}", object_name_to_sql(©.source)));
if let Some(t) = ©.system_time {
out.push_str(&format!(" FOR SYSTEM_TIME AS OF {}", self.expr(t, i)));
}
}
if let Some(c) = &c.default_collate {
out.push_str(&format!(
"{}DEFAULT COLLATE {}",
self.nl(i),
self.expr(c, i)
));
}
if let Some(p) = &c.partition_by {
out.push_str(&format!("{}PARTITION BY {}", self.nl(i), self.expr(p, i)));
}
if !c.cluster_by.is_empty() {
out.push_str(&format!(
"{}CLUSTER BY {}",
self.nl(i),
self.list(&c.cluster_by, |e| self.expr(e, i))
));
}
if let Some(conn) = &c.with_connection {
out.push_str(&format!(
"{}WITH CONNECTION {}",
self.nl(i),
object_name_to_sql(conn)
));
}
if !c.options.is_empty() {
out.push_str(&self.nl(i));
out.push_str(&self.options(&c.options, i));
}
if let Some(q) = &c.query {
out.push_str(&format!(" AS{}{}", self.nl(i), self.query(q, i)));
}
out
}
fn column_def(&self, col: &ColumnDef, i: usize) -> String {
let mut out = format!(
"{} {}",
ident_to_sql(&col.name),
self.data_type(&col.data_type)
);
if let Some(c) = &col.collate {
out.push_str(&format!(" COLLATE {}", self.expr(c, i)));
}
if let Some(d) = &col.default {
out.push_str(&format!(" DEFAULT {}", self.expr(d, i)));
}
if col.not_null {
out.push_str(" NOT NULL");
}
if col.primary_key {
out.push_str(" PRIMARY KEY NOT ENFORCED");
}
if !col.options.is_empty() {
out.push(' ');
out.push_str(&self.options(&col.options, i));
}
out
}
fn constraint(&self, constraint: &TableConstraint) -> String {
match constraint {
TableConstraint::PrimaryKey {
columns,
not_enforced,
} => format!(
"PRIMARY KEY ({}){}",
self.list(columns, ident_to_sql),
if *not_enforced { " NOT ENFORCED" } else { "" }
),
TableConstraint::ForeignKey {
name,
columns,
foreign_table,
referred_columns,
not_enforced,
} => {
let mut out = String::new();
if let Some(n) = name {
out.push_str(&format!("CONSTRAINT {} ", ident_to_sql(n)));
}
out.push_str(&format!(
"FOREIGN KEY ({}) REFERENCES {}({}){}",
self.list(columns, ident_to_sql),
object_name_to_sql(foreign_table),
self.list(referred_columns, ident_to_sql),
if *not_enforced { " NOT ENFORCED" } else { "" }
));
out
}
}
}
fn alter_action(&self, action: &AlterAction, i: usize) -> String {
match action {
AlterAction::AddColumn {
if_not_exists,
column,
} => format!(
"ADD COLUMN {}{}",
if *if_not_exists { "IF NOT EXISTS " } else { "" },
self.column_def(column, i)
),
AlterAction::DropColumn { if_exists, name } => {
format!(
"DROP COLUMN {}{}",
if *if_exists { "IF EXISTS " } else { "" },
ident_to_sql(name)
)
}
AlterAction::RenameTo(name) => format!("RENAME TO {}", object_name_to_sql(name)),
AlterAction::RenameColumn {
if_exists,
from,
to,
} => format!(
"RENAME COLUMN {}{} TO {}",
if *if_exists { "IF EXISTS " } else { "" },
ident_to_sql(from),
ident_to_sql(to)
),
AlterAction::SetOptions(o) => format!("SET {}", self.options(o, i)),
AlterAction::SetDefaultCollate(e) => format!("SET DEFAULT COLLATE {}", self.expr(e, i)),
AlterAction::AlterColumn {
if_exists,
name,
action,
} => {
let what = match action {
AlterColumnAction::SetOptions(o) => format!("SET {}", self.options(o, i)),
AlterColumnAction::DropNotNull => "DROP NOT NULL".to_string(),
AlterColumnAction::SetDataType(t) => {
format!("SET DATA TYPE {}", self.data_type(t))
}
AlterColumnAction::SetDefault(e) => format!("SET DEFAULT {}", self.expr(e, i)),
AlterColumnAction::DropDefault => "DROP DEFAULT".to_string(),
};
format!(
"ALTER COLUMN {}{} {what}",
if *if_exists { "IF EXISTS " } else { "" },
ident_to_sql(name)
)
}
}
}
fn param_type(&self, param_type: &ParamType) -> String {
match param_type {
ParamType::Type(t) => self.data_type(t),
ParamType::AnyType => "ANY TYPE".to_string(),
ParamType::Table(fields) => format!("TABLE<{}>", self.struct_fields(fields)),
ParamType::AnyTable => "ANY TABLE".to_string(),
}
}
fn function_params(&self, params: &[FunctionParam]) -> String {
format!(
"({})",
self.list(params, |p| {
let mut s = format!(
"{} {}",
ident_to_sql(&p.name),
self.param_type(&p.param_type)
);
if p.not_aggregate {
s.push_str(" NOT AGGREGATE");
}
s
})
)
}
fn create_function(&self, f: &CreateFunction, i: usize) -> String {
let mut out = String::from("CREATE ");
if f.or_replace {
out.push_str("OR REPLACE ");
}
if f.temporary {
out.push_str("TEMP ");
}
if f.aggregate {
out.push_str("AGGREGATE ");
}
out.push_str("FUNCTION ");
if f.if_not_exists {
out.push_str("IF NOT EXISTS ");
}
out.push_str(&object_name_to_sql(&f.name));
out.push_str(&self.function_params(&f.params));
if let Some(r) = &f.returns {
out.push_str(&format!(" RETURNS {}", self.data_type(r)));
}
match f.determinism {
Some(true) => out.push_str(" DETERMINISTIC"),
Some(false) => out.push_str(" NOT DETERMINISTIC"),
None => {}
}
if let Some(l) = &f.language {
out.push_str(&format!(" LANGUAGE {}", ident_to_sql(l)));
}
if let FunctionBody::Remote(c) = &f.body {
out.push_str(&format!(
" REMOTE WITH CONNECTION {}",
object_name_to_sql(c)
));
}
if !f.options.is_empty() {
out.push(' ');
out.push_str(&self.options(&f.options, i));
}
match &f.body {
FunctionBody::Expr(e) => out.push_str(&format!(" AS ({})", self.expr(e, i))),
FunctionBody::Code(code) => out.push_str(&format!(" AS {}", self.literal(code, i))),
FunctionBody::Remote(_) | FunctionBody::None => {}
}
out
}
fn query(&self, q: &Query, i: usize) -> String {
let mut out = String::new();
if let Some(with) = &q.with {
out.push_str("WITH ");
if with.recursive {
out.push_str("RECURSIVE ");
}
let ctes: Vec<String> = with
.ctes
.iter()
.map(|cte| {
format!(
"{} AS {}",
ident_to_sql(&cte.name),
self.subquery(&cte.query, i)
)
})
.collect();
out.push_str(&ctes.join(&format!(",{}", self.nl(i))));
out.push_str(&self.nl(i));
}
out.push_str(&self.set_expr(&q.body, i));
if !q.order_by.is_empty() {
out.push_str(&format!(
"{}ORDER BY {}",
self.nl(i),
self.order_by(&q.order_by, i)
));
}
if let Some(limit) = &q.limit {
out.push_str(&self.nl(i));
out.push_str(&self.limit(limit, i));
}
for pipe in &q.pipes {
out.push_str(&format!("{}|> {}", self.nl(i), self.pipe(pipe, i)));
}
out
}
fn limit(&self, limit: &Limit, i: usize) -> String {
let mut out = format!("LIMIT {}", self.expr(&limit.count, i));
if let Some(o) = &limit.offset {
out.push_str(&format!(" OFFSET {}", self.expr(o, i)));
}
out
}
fn set_op_keyword(
&self,
op: SetOperator,
quantifier: SetQuantifier,
mode: Option<SetOpMode>,
corresponding: &Option<Corresponding>,
) -> String {
let mut out = String::new();
match mode {
Some(SetOpMode::Full) => out.push_str("FULL "),
Some(SetOpMode::Left) => out.push_str("LEFT "),
Some(SetOpMode::Inner) => out.push_str("INNER "),
None => {}
}
out.push_str(op.keyword());
match quantifier {
SetQuantifier::All => out.push_str(" ALL"),
SetQuantifier::Distinct => out.push_str(" DISTINCT"),
SetQuantifier::None => {}
}
match corresponding {
Some(Corresponding::ByName(on)) => {
out.push_str(" BY NAME");
if !on.is_empty() {
out.push_str(&format!(" ON ({})", self.list(on, ident_to_sql)));
}
}
Some(Corresponding::Corresponding { strict, by }) => {
if *strict {
out.push_str(" STRICT");
}
out.push_str(" CORRESPONDING");
if !by.is_empty() {
out.push_str(&format!(" BY ({})", self.list(by, ident_to_sql)));
}
}
None => {}
}
out
}
fn set_expr(&self, body: &SetExpr, i: usize) -> String {
match body {
SetExpr::Select(s) => self.select(s, i),
SetExpr::Query(q) => self.subquery(q, i),
SetExpr::SetOperation {
op,
quantifier,
mode,
corresponding,
left,
right,
} => {
let right_text = match right.as_ref() {
SetExpr::SetOperation { .. } => format!("({})", self.set_expr(right, i)),
other => self.set_expr(other, i),
};
format!(
"{}{}{}{}{}",
self.set_expr(left, i),
self.nl(i),
self.set_op_keyword(*op, *quantifier, *mode, corresponding),
self.nl(i),
right_text
)
}
SetExpr::From(from) => format!("FROM {}", self.table_list(from, i)),
}
}
fn select(&self, s: &Select, i: usize) -> String {
let mut out = String::from("SELECT");
if s.distinct {
out.push_str(" DISTINCT");
}
match s.select_as {
Some(SelectAs::Struct) => out.push_str(" AS STRUCT"),
Some(SelectAs::Value) => out.push_str(" AS VALUE"),
None => {}
}
out.push(' ');
out.push_str(&self.select_items(&s.projection, i));
if !s.from.is_empty() {
out.push_str(&format!(
"{}FROM {}",
self.nl(i),
self.table_list(&s.from, i)
));
}
if let Some(w) = &s.where_clause {
out.push_str(&format!("{}WHERE {}", self.nl(i), self.expr(w, i)));
}
if let Some(g) = &s.group_by {
out.push_str(&format!("{}GROUP BY ", self.nl(i)));
match g {
GroupBy::All => out.push_str("ALL"),
GroupBy::Items(items) => {
out.push_str(&self.list(items, |item| self.group_by_item(item, i)))
}
}
}
if let Some(h) = &s.having {
out.push_str(&format!("{}HAVING {}", self.nl(i), self.expr(h, i)));
}
if let Some(q) = &s.qualify {
out.push_str(&format!("{}QUALIFY {}", self.nl(i), self.expr(q, i)));
}
if !s.window.is_empty() {
out.push_str(&format!(
"{}WINDOW {}",
self.nl(i),
self.list(&s.window, |w| format!(
"{} AS {}",
ident_to_sql(&w.name),
self.window_spec(&w.spec, i)
))
));
}
out
}
fn select_items(&self, items: &[SelectItem], i: usize) -> String {
self.list(items, |item| self.select_item(item, i))
}
fn select_item(&self, item: &SelectItem, i: usize) -> String {
match item {
SelectItem::Expr { expr, alias } => match alias {
Some(a) => format!("{} AS {}", self.expr(expr, i), ident_to_sql(a)),
None => self.expr(expr, i),
},
SelectItem::Wildcard(o) => format!("*{}", self.wildcard_options(o, i)),
SelectItem::QualifiedWildcard { qualifier, options } => {
let q = self.expr(qualifier, i);
let q = if precedence(qualifier) < 255 {
format!("({q})")
} else {
q
};
format!("{q}.*{}", self.wildcard_options(options, i))
}
}
}
fn wildcard_options(&self, o: &WildcardOptions, i: usize) -> String {
let mut out = String::new();
if !o.except.is_empty() {
out.push_str(&format!(" EXCEPT ({})", self.list(&o.except, ident_to_sql)));
}
if !o.replace.is_empty() {
out.push_str(&format!(
" REPLACE ({})",
self.list(&o.replace, |r| {
let alias = r.alias.as_ref().map(ident_to_sql).unwrap_or_default();
format!("{} AS {alias}", self.expr(&r.expr, i))
})
));
}
out
}
fn group_by_item(&self, item: &GroupByItem, i: usize) -> String {
match item {
GroupByItem::Expr(e) => self.expr(e, i),
GroupByItem::Rollup(es) => format!("ROLLUP({})", self.list(es, |e| self.expr(e, i))),
GroupByItem::Cube(es) => format!("CUBE({})", self.list(es, |e| self.expr(e, i))),
GroupByItem::GroupingSets(items) => {
format!(
"GROUPING SETS({})",
self.list(items, |item| self.group_by_item(item, i))
)
}
GroupByItem::Empty => "()".to_string(),
}
}
fn order_by(&self, items: &[OrderByExpr], i: usize) -> String {
self.list(items, |o| {
let mut s = self.expr(&o.expr, i);
if let Some(c) = &o.collate {
s.push_str(&format!(" COLLATE {}", self.expr(c, i)));
}
s.push_str(&order_suffix(o.asc, o.nulls_first));
s
})
}
fn table_list(&self, items: &[TableWithJoins], i: usize) -> String {
self.list(items, |t| self.table_with_joins(t, i))
}
fn table_with_joins(&self, t: &TableWithJoins, i: usize) -> String {
let mut out = self.table_factor(&t.relation, i);
for join in &t.joins {
out.push_str(&self.nl(i));
out.push_str(&self.join(join, i));
}
out
}
fn join(&self, join: &Join, i: usize) -> String {
let mut out = String::new();
if join.natural {
out.push_str("NATURAL ");
}
out.push_str(match join.kind {
JoinKind::Inner => "JOIN ",
JoinKind::Left => "LEFT JOIN ",
JoinKind::Right => "RIGHT JOIN ",
JoinKind::Full => "FULL JOIN ",
JoinKind::Cross => "CROSS JOIN ",
});
out.push_str(&self.table_factor(&join.relation, i));
match &join.constraint {
JoinConstraint::On(e) => out.push_str(&format!(" ON {}", self.expr(e, i))),
JoinConstraint::Using(cols) => {
out.push_str(&format!(" USING ({})", self.list(cols, ident_to_sql)))
}
JoinConstraint::None => {}
}
out
}
fn alias(&self, alias: &Option<Ident>) -> String {
alias
.as_ref()
.map(|a| format!(" AS {}", ident_to_sql(a)))
.unwrap_or_default()
}
fn sample(&self, sample: &Option<TableSample>, i: usize) -> String {
match sample {
Some(s) => format!(
" TABLESAMPLE {} ({} {})",
ident_to_sql(&s.method),
self.expr(&s.size, i),
match s.unit {
SampleUnit::Percent => "PERCENT",
SampleUnit::Rows => "ROWS",
}
),
None => String::new(),
}
}
fn table_factor(&self, factor: &TableFactor, i: usize) -> String {
match factor {
TableFactor::Table {
name,
alias,
system_time,
sample,
} => {
let mut out = object_name_to_sql(name);
out.push_str(&self.alias(alias));
if let Some(t) = system_time {
out.push_str(&format!(" FOR SYSTEM_TIME AS OF {}", self.expr(t, i)));
}
out.push_str(&self.sample(sample, i));
out
}
TableFactor::Derived {
subquery,
alias,
sample,
} => {
format!(
"{}{}{}",
self.subquery(subquery, i),
self.alias(alias),
self.sample(sample, i)
)
}
TableFactor::Unnest {
array,
alias,
with_offset,
} => {
let mut out = format!("UNNEST({}){}", self.expr(array, i), self.alias(alias));
if let Some(offset) = with_offset {
out.push_str(" WITH OFFSET");
out.push_str(&self.alias(offset));
}
out
}
TableFactor::TableFunction { function, alias } => {
format!("{}{}", self.function(function, i), self.alias(alias))
}
TableFactor::NestedJoin { table, alias } => {
format!("({}){}", self.table_with_joins(table, i), self.alias(alias))
}
TableFactor::Pivot {
table,
aggregates,
value_column,
values,
alias,
} => format!(
"{} PIVOT({}){}",
self.table_factor(table, i),
self.pivot_body(aggregates, value_column, values, i),
self.alias(alias)
),
TableFactor::Unpivot {
table,
include_nulls,
value_columns,
name_column,
columns,
alias,
} => format!(
"{} {}{}",
self.table_factor(table, i),
self.unpivot_body(*include_nulls, value_columns, name_column, columns, i),
self.alias(alias)
),
TableFactor::MatchRecognize { table, spec, alias } => format!(
"{} {}{}",
self.table_factor(table, i),
self.match_recognize(spec, i),
self.alias(alias)
),
TableFactor::Align { table, spec, alias } => format!(
"{} {}{}",
self.table_factor(table, i),
self.align(spec, i),
self.alias(alias)
),
}
}
fn match_recognize(&self, m: &MatchRecognize, i: usize) -> String {
let mut parts = Vec::new();
if !m.partition_by.is_empty() {
parts.push(format!(
"PARTITION BY {}",
self.list(&m.partition_by, |e| self.expr(e, i))
));
}
parts.push(format!("ORDER BY {}", self.order_by(&m.order_by, i)));
parts.push(format!(
"MEASURES {}",
self.list(&m.measures, |(e, a)| format!(
"{} AS {}",
self.expr(e, i),
ident_to_sql(a)
))
));
match m.after_match {
Some(AfterMatchSkip::PastLastRow) => {
parts.push("AFTER MATCH SKIP PAST LAST ROW".into())
}
Some(AfterMatchSkip::ToNextRow) => parts.push("AFTER MATCH SKIP TO NEXT ROW".into()),
None => {}
}
parts.push(format!("PATTERN ({})", row_pattern(&m.pattern)));
if !m.define.is_empty() {
parts.push(format!(
"DEFINE {}",
self.list(&m.define, |(s, e)| format!(
"{} AS {}",
ident_to_sql(s),
self.expr(e, i)
))
));
}
if !m.options.is_empty() {
parts.push(self.options(&m.options, i));
}
format!("MATCH_RECOGNIZE ({})", parts.join(" "))
}
fn align(&self, a: &Align, i: usize) -> String {
let mut parts = Vec::new();
if let Some(t) = &a.timestamp {
let mut s = format!("TIMESTAMP {}", ident_to_sql(t));
if let Some(alias) = &a.timestamp_alias {
s.push_str(&format!(" AS {}", ident_to_sql(alias)));
}
parts.push(s);
}
parts.push(format!("PERIOD {}", self.expr(&a.period, i)));
if let Some(o) = &a.origin {
parts.push(format!("ORIGIN {}", self.expr(o, i)));
}
if let Some(o) = &a.output {
parts.push(format!("OUTPUT {o}"));
}
if !a.partition_by.is_empty() {
parts.push(format!(
"PARTITION BY {}",
self.expr_alias_list(&a.partition_by, i)
));
}
if !a.metrics.is_empty() {
parts.push(format!(
"METRICS {}",
self.list(&a.metrics, |m| {
let mut s = self.expr(&m.expr, i);
if let Some(w) = &m.within {
s.push_str(&format!(" WITHIN ({w})"));
}
if let Some(alias) = &m.alias {
s.push_str(&format!(" AS {}", ident_to_sql(alias)));
}
s
})
));
}
format!("ALIGN ({})", parts.join(" "))
}
fn expr_alias_list(&self, items: &[ExprWithAlias], i: usize) -> String {
self.list(items, |item| match &item.alias {
Some(a) => format!("{} AS {}", self.expr(&item.expr, i), ident_to_sql(a)),
None => self.expr(&item.expr, i),
})
}
fn pivot_body(
&self,
aggregates: &[ExprWithAlias],
value_column: &Expr,
values: &[ExprWithAlias],
i: usize,
) -> String {
format!(
"{} FOR {} IN ({})",
self.expr_alias_list(aggregates, i),
self.operand(value_column, COMPARISON_PRECEDENCE, true, i),
self.expr_alias_list(values, i)
)
}
fn unpivot_body(
&self,
include_nulls: Option<bool>,
value_columns: &[Ident],
name_column: &Ident,
columns: &[UnpivotColumns],
i: usize,
) -> String {
let nulls = match include_nulls {
Some(true) => "INCLUDE NULLS ",
Some(false) => "EXCLUDE NULLS ",
None => "",
};
let values = if value_columns.len() == 1 {
ident_to_sql(&value_columns[0])
} else {
format!("({})", self.list(value_columns, ident_to_sql))
};
let cols = self.list(columns, |c| {
let names = if c.columns.len() == 1 {
ident_to_sql(&c.columns[0])
} else {
format!("({})", self.list(&c.columns, ident_to_sql))
};
match &c.alias {
Some(a) => format!("{names} AS {}", self.expr(a, i)),
None => names,
}
});
format!(
"UNPIVOT {nulls}({values} FOR {} IN ({cols}))",
ident_to_sql(name_column)
)
}
fn pipe_items(&self, items: &[PipeExprItem], i: usize) -> String {
self.list(items, |item| {
let mut s = self.expr(&item.expr, i);
if let Some(a) = &item.alias {
s.push_str(&format!(" AS {}", ident_to_sql(a)));
}
s.push_str(&order_suffix(item.asc, item.nulls_first));
s
})
}
fn pipe(&self, pipe: &PipeOperator, i: usize) -> String {
match pipe {
PipeOperator::Where(e) => format!("WHERE {}", self.expr(e, i)),
PipeOperator::Select {
distinct,
select_as,
items,
} => {
let mut out = String::from("SELECT ");
if *distinct {
out.push_str("DISTINCT ");
}
match select_as {
Some(SelectAs::Struct) => out.push_str("AS STRUCT "),
Some(SelectAs::Value) => out.push_str("AS VALUE "),
None => {}
}
out.push_str(&self.select_items(items, i));
out
}
PipeOperator::Extend(items) => format!("EXTEND {}", self.select_items(items, i)),
PipeOperator::Window(items) => format!("WINDOW {}", self.select_items(items, i)),
PipeOperator::Set(a) => format!("SET {}", self.assignments(a, i)),
PipeOperator::Drop(cols) => format!("DROP {}", self.list(cols, ident_to_sql)),
PipeOperator::Rename(pairs) => format!(
"RENAME {}",
self.list(pairs, |(a, b)| format!(
"{} AS {}",
ident_to_sql(a),
ident_to_sql(b)
))
),
PipeOperator::As(a) => format!("AS {}", ident_to_sql(a)),
PipeOperator::Aggregate {
items,
group_by,
group_and_order,
} => {
let mut out = String::from("AGGREGATE");
if !items.is_empty() {
out.push(' ');
out.push_str(&self.pipe_items(items, i));
}
if !group_by.is_empty() {
out.push_str(if *group_and_order {
" GROUP AND ORDER BY "
} else {
" GROUP BY "
});
out.push_str(&self.pipe_items(group_by, i));
}
out
}
PipeOperator::Join(j) => self.join(j, i),
PipeOperator::OrderBy(items) => format!("ORDER BY {}", self.order_by(items, i)),
PipeOperator::Limit(l) => self.limit(l, i),
PipeOperator::SetOperation {
op,
quantifier,
mode,
corresponding,
queries,
} => format!(
"{} {}",
self.set_op_keyword(*op, *quantifier, *mode, corresponding),
self.list(queries, |q| self.subquery(q, i))
),
PipeOperator::Call { function, alias } => {
format!("CALL {}{}", self.function(function, i), self.alias(alias))
}
PipeOperator::Distinct => "DISTINCT".to_string(),
PipeOperator::TableSample(s) => {
self.sample(&Some(s.clone()), i).trim_start().to_string()
}
PipeOperator::Pivot {
aggregates,
value_column,
values,
alias,
} => format!(
"PIVOT({}){}",
self.pivot_body(aggregates, value_column, values, i),
self.alias(alias)
),
PipeOperator::Unpivot {
include_nulls,
value_columns,
name_column,
columns,
alias,
} => format!(
"{}{}",
self.unpivot_body(*include_nulls, value_columns, name_column, columns, i),
self.alias(alias)
),
PipeOperator::Assert { condition, payload } => {
let mut out = format!("ASSERT {}", self.expr(condition, i));
for p in payload {
out.push_str(&format!(", {}", self.expr(p, i)));
}
out
}
PipeOperator::MatchRecognize { spec, alias } => {
format!("{}{}", self.match_recognize(spec, i), self.alias(alias))
}
PipeOperator::Align { spec, alias } => {
format!("{}{}", self.align(spec, i), self.alias(alias))
}
}
}
fn operand(&self, expr: &Expr, min: u8, strict: bool, i: usize) -> String {
let p = precedence(expr);
let text = self.expr(expr, i);
if p < min || (strict && p == min) {
format!("({text})")
} else {
text
}
}
fn expr(&self, expr: &Expr, i: usize) -> String {
match expr {
Expr::Identifier(ident) => ident_to_sql(ident),
Expr::CompoundIdentifier(parts) => parts
.iter()
.enumerate()
.map(|(n, p)| {
if n == 0 {
ident_to_sql(p)
} else {
path_part(p)
}
})
.collect::<Vec<_>>()
.join("."),
Expr::Literal(lit) => self.literal(lit, i),
Expr::Parameter(p) => match p {
Parameter::Named(name) if is_plain_word(name) => format!("@{name}"),
Parameter::Named(name) => format!("@`{}`", escape_identifier(name)),
Parameter::Positional => "?".to_string(),
Parameter::System(name) => format!("@@{name}"),
},
Expr::UnaryOp { op, expr: inner } => match op {
UnaryOperator::Not => {
format!("NOT {}", self.operand(inner, NOT_PRECEDENCE, false, i))
}
_ => {
let symbol = match op {
UnaryOperator::Minus => "-",
UnaryOperator::Plus => "+",
_ => "~",
};
let operand = self.operand(inner, UNARY_PRECEDENCE, false, i);
let space = if operand.starts_with('-') || operand.starts_with('+') {
" "
} else {
""
};
format!("{symbol}{space}{operand}")
}
},
Expr::BinaryOp { left, op, right } => {
let p = op.precedence();
format!(
"{} {} {}",
self.operand(left, p, false, i),
op.as_str(),
self.operand(right, p, true, i)
)
}
Expr::IsNull { expr: e, negated } => format!(
"{} IS {}NULL",
self.operand(e, COMPARISON_PRECEDENCE, false, i),
if *negated { "NOT " } else { "" }
),
Expr::IsBool {
expr: e,
value,
negated,
} => format!(
"{} IS {}{}",
self.operand(e, COMPARISON_PRECEDENCE, false, i),
if *negated { "NOT " } else { "" },
match value {
Some(true) => "TRUE",
Some(false) => "FALSE",
None => "UNKNOWN",
}
),
Expr::IsDistinctFrom {
left,
right,
negated,
} => format!(
"{} IS {}DISTINCT FROM {}",
self.operand(left, COMPARISON_PRECEDENCE, false, i),
if *negated { "NOT " } else { "" },
self.operand(right, COMPARISON_PRECEDENCE, true, i)
),
Expr::InList {
expr: e,
list,
negated,
} => format!(
"{} {}IN ({})",
self.operand(e, COMPARISON_PRECEDENCE, false, i),
not(*negated),
self.list(list, |x| self.expr(x, i))
),
Expr::InSubquery {
expr: e,
subquery,
negated,
} => format!(
"{} {}IN {}",
self.operand(e, COMPARISON_PRECEDENCE, false, i),
not(*negated),
self.subquery(subquery, i)
),
Expr::InUnnest {
expr: e,
array,
negated,
} => format!(
"{} {}IN UNNEST({})",
self.operand(e, COMPARISON_PRECEDENCE, false, i),
not(*negated),
self.expr(array, i)
),
Expr::Between {
expr: e,
negated,
low,
high,
} => format!(
"{} {}BETWEEN {} AND {}",
self.operand(e, COMPARISON_PRECEDENCE, false, i),
not(*negated),
self.operand(low, COMPARISON_PRECEDENCE, true, i),
self.operand(high, COMPARISON_PRECEDENCE, true, i)
),
Expr::Like {
expr: e,
negated,
pattern,
} => format!(
"{} {}LIKE {}",
self.operand(e, COMPARISON_PRECEDENCE, false, i),
not(*negated),
self.operand(pattern, COMPARISON_PRECEDENCE, true, i)
),
Expr::LikeQuantified {
expr: e,
negated,
quantifier,
patterns,
} => {
let q = match quantifier {
LikeQuantifier::Any => "ANY",
LikeQuantifier::Some => "SOME",
LikeQuantifier::All => "ALL",
};
let p = match patterns {
LikePatterns::List(list) => {
format!("({})", self.list(list, |x| self.expr(x, i)))
}
LikePatterns::Unnest(a) => format!("UNNEST({})", self.expr(a, i)),
LikePatterns::Subquery(q) => self.subquery(q, i),
};
format!(
"{} {}LIKE {q} {p}",
self.operand(e, COMPARISON_PRECEDENCE, false, i),
not(*negated)
)
}
Expr::Case {
operand,
branches,
else_result,
} => {
let mut out = String::from("CASE");
if let Some(o) = operand {
out.push_str(&format!(" {}", self.expr(o, i)));
}
for b in branches {
out.push_str(&format!(
" WHEN {} THEN {}",
self.expr(&b.condition, i),
self.expr(&b.result, i)
));
}
if let Some(e) = else_result {
out.push_str(&format!(" ELSE {}", self.expr(e, i)));
}
out.push_str(" END");
out
}
Expr::Cast {
expr: e,
data_type,
safe,
format,
time_zone,
} => {
let mut out = format!(
"{}({} AS {}",
if *safe { "SAFE_CAST" } else { "CAST" },
self.expr(e, i),
self.data_type(data_type)
);
if let Some(f) = format {
out.push_str(&format!(" FORMAT {}", self.expr(f, i)));
}
if let Some(t) = time_zone {
out.push_str(&format!(" AT TIME ZONE {}", self.expr(t, i)));
}
out.push(')');
out
}
Expr::Extract {
part,
expr: e,
time_zone,
} => {
let mut out = format!("EXTRACT({} FROM {}", self.expr(part, i), self.expr(e, i));
if let Some(t) = time_zone {
out.push_str(&format!(" AT TIME ZONE {}", self.expr(t, i)));
}
out.push(')');
out
}
Expr::Struct { fields, typed } => {
let mut out = String::from("STRUCT");
if let Some(t) = typed {
out.push_str(&format!("<{}>", self.struct_fields(t)));
}
out.push_str(&format!(
"({})",
self.list(fields, |f| match &f.alias {
Some(a) => format!("{} AS {}", self.expr(&f.expr, i), ident_to_sql(a)),
None => self.expr(&f.expr, i),
})
));
out
}
Expr::Tuple(items) => format!("({})", self.list(items, |x| self.expr(x, i))),
Expr::Array {
elements,
element_type,
keyword,
} => {
let mut out = String::new();
if *keyword || element_type.is_some() {
out.push_str("ARRAY");
}
if let Some(t) = element_type {
out.push_str(&format!("<{}>", self.data_type(t)));
}
out.push_str(&format!("[{}]", self.list(elements, |x| self.expr(x, i))));
out
}
Expr::ArraySubquery(q) => format!("ARRAY{}", self.subquery(q, i)),
Expr::Subscript {
expr: e,
kind,
index,
} => {
let base = self.operand(e, 255, false, i);
match kind.keyword() {
Some(word) => format!("{base}[{word}({})]", self.expr(index, i)),
None => format!("{base}[{}]", self.expr(index, i)),
}
}
Expr::FieldAccess { expr: e, field } => {
format!("{}.{}", self.operand(e, 255, false, i), path_part(field))
}
Expr::Function(f) => self.function(f, i),
Expr::Subquery(q) => self.subquery(q, i),
Expr::Exists(q) => format!("EXISTS {}", self.subquery(q, i)),
Expr::ScalarWith { bindings, body } => {
let mut parts: Vec<String> = bindings
.iter()
.map(|(name, value)| {
format!("{} AS {}", ident_to_sql(name), self.expr(value, i))
})
.collect();
parts.push(self.expr(body, i));
format!("WITH({})", parts.join(", "))
}
Expr::Lambda { params, body } => {
let head = if params.len() == 1 {
ident_to_sql(¶ms[0])
} else {
format!("({})", self.list(params, ident_to_sql))
};
format!("{head} -> {}", self.expr(body, i))
}
Expr::NamedArg { name, value } => {
format!("{} => {}", ident_to_sql(name), self.expr(value, i))
}
Expr::Nested(inner) => format!("({})", self.expr(inner, i)),
Expr::Default => "DEFAULT".to_string(),
}
}
fn literal(&self, lit: &Literal, i: usize) -> String {
match lit {
Literal::Null => "NULL".to_string(),
Literal::Bool(true) => "TRUE".to_string(),
Literal::Bool(false) => "FALSE".to_string(),
Literal::Int(text) | Literal::Float(text) => text.clone(),
Literal::Numeric(v) => format!("NUMERIC {}", quote_string(v)),
Literal::BigNumeric(v) => format!("BIGNUMERIC {}", quote_string(v)),
Literal::String(s) => {
if s.raw && raw_ok(&s.value, s.quote) {
format!("r{q}{}{q}", s.value, q = s.quote.delimiter())
} else {
let quote = if s.raw { QuoteStyle::Single } else { s.quote };
format!(
"{q}{}{q}",
escape_string(&s.value, quote),
q = quote.delimiter()
)
}
}
Literal::Bytes(b) => format!("b'{}'", escape_bytes(&b.value)),
Literal::Date(v) => format!("DATE {}", quote_string(v)),
Literal::Datetime(v) => format!("DATETIME {}", quote_string(v)),
Literal::Time(v) => format!("TIME {}", quote_string(v)),
Literal::Timestamp(v) => format!("TIMESTAMP {}", quote_string(v)),
Literal::Json(v) => format!("JSON {}", quote_string(v)),
Literal::Range { element, value } => {
format!("RANGE<{}> {}", self.data_type(element), quote_string(value))
}
Literal::Interval(interval) => {
let mut out = format!(
"INTERVAL {} {}",
self.operand(&interval.value, UNARY_PRECEDENCE, false, i),
interval.leading
);
if let Some(t) = &interval.trailing {
out.push_str(&format!(" TO {t}"));
}
out
}
}
}
fn function(&self, f: &Function, i: usize) -> String {
let name = function_name(&f.name);
if f.no_parens {
return name;
}
let mut out = format!("{name}(");
if f.distinct {
out.push_str("DISTINCT ");
}
out.push_str(&self.list(&f.args, |arg| match arg {
FunctionArg::Expr(e) => self.expr(e, i),
FunctionArg::Wildcard => "*".to_string(),
FunctionArg::Table(t) => format!("TABLE {}", object_name_to_sql(t)),
FunctionArg::Model(m) => format!("MODEL {}", object_name_to_sql(m)),
}));
match f.null_treatment {
Some(NullTreatment::IgnoreNulls) => out.push_str(" IGNORE NULLS"),
Some(NullTreatment::RespectNulls) => out.push_str(" RESPECT NULLS"),
None => {}
}
if let Some(h) = &f.having {
out.push_str(&format!(
" HAVING {} {}",
if h.max { "MAX" } else { "MIN" },
self.expr(&h.expr, i)
));
}
if !f.order_by.is_empty() {
out.push_str(&format!(" ORDER BY {}", self.order_by(&f.order_by, i)));
}
if let Some(l) = &f.limit {
out.push_str(&format!(" LIMIT {}", self.expr(l, i)));
}
out.push(')');
match &f.over {
Some(WindowType::Named(name)) => out.push_str(&format!(" OVER {}", ident_to_sql(name))),
Some(WindowType::Spec(spec)) => {
out.push_str(&format!(" OVER {}", self.window_spec(spec, i)))
}
None => {}
}
out
}
fn window_spec(&self, spec: &WindowSpec, i: usize) -> String {
let mut parts = Vec::new();
if let Some(b) = &spec.base {
parts.push(ident_to_sql(b));
}
if !spec.partition_by.is_empty() {
parts.push(format!(
"PARTITION BY {}",
self.list(&spec.partition_by, |e| self.expr(e, i))
));
}
if !spec.order_by.is_empty() {
parts.push(format!("ORDER BY {}", self.order_by(&spec.order_by, i)));
}
if let Some(frame) = &spec.frame {
let units = match frame.units {
FrameUnits::Rows => "ROWS",
FrameUnits::Range => "RANGE",
};
parts.push(match &frame.end {
Some(end) => format!(
"{units} BETWEEN {} AND {}",
self.frame_bound(&frame.start, i),
self.frame_bound(end, i)
),
None => format!("{units} {}", self.frame_bound(&frame.start, i)),
});
}
format!("({})", parts.join(" "))
}
fn frame_bound(&self, bound: &FrameBound, i: usize) -> String {
match bound {
FrameBound::UnboundedPreceding => "UNBOUNDED PRECEDING".to_string(),
FrameBound::UnboundedFollowing => "UNBOUNDED FOLLOWING".to_string(),
FrameBound::CurrentRow => "CURRENT ROW".to_string(),
FrameBound::Preceding(e) => format!(
"{} PRECEDING",
self.operand(e, COMPARISON_PRECEDENCE, true, i)
),
FrameBound::Following(e) => format!(
"{} FOLLOWING",
self.operand(e, COMPARISON_PRECEDENCE, true, i)
),
}
}
fn struct_fields(&self, fields: &[StructField]) -> String {
self.list(fields, |f| {
let mut s = match &f.name {
Some(n) => format!("{} {}", path_part(n), self.data_type(&f.data_type)),
None => self.data_type(&f.data_type),
};
if f.not_null {
s.push_str(" NOT NULL");
}
if !f.options.is_empty() {
s.push(' ');
s.push_str(&self.options(&f.options, 0));
}
s
})
}
fn data_type(&self, t: &DataType) -> String {
match t {
DataType::Int64 => "INT64".into(),
DataType::Float64 => "FLOAT64".into(),
DataType::Numeric(p) => format!("NUMERIC{}", precision(p)),
DataType::BigNumeric(p) => format!("BIGNUMERIC{}", precision(p)),
DataType::Bool => "BOOL".into(),
DataType::String(n) => n.map_or("STRING".into(), |n| format!("STRING({n})")),
DataType::Bytes(n) => n.map_or("BYTES".into(), |n| format!("BYTES({n})")),
DataType::Date => "DATE".into(),
DataType::Datetime => "DATETIME".into(),
DataType::Time => "TIME".into(),
DataType::Timestamp => "TIMESTAMP".into(),
DataType::Interval => "INTERVAL".into(),
DataType::Json => "JSON".into(),
DataType::Geography => "GEOGRAPHY".into(),
DataType::Array(inner) => format!("ARRAY<{}>", self.data_type(inner)),
DataType::Struct(fields) => format!("STRUCT<{}>", self.struct_fields(fields)),
DataType::Range(inner) => format!("RANGE<{}>", self.data_type(inner)),
DataType::Other(name) if is_plain_word(name) => name.clone(),
DataType::Other(name) => format!("`{}`", escape_identifier(name)),
}
}
}
fn precision(p: &Option<(u32, Option<u32>)>) -> String {
match p {
Some((precision, Some(scale))) => format!("({precision}, {scale})"),
Some((precision, None)) => format!("({precision})"),
None => String::new(),
}
}
fn not(negated: bool) -> &'static str {
if negated {
"NOT "
} else {
""
}
}
fn order_suffix(asc: Option<bool>, nulls_first: Option<bool>) -> String {
let mut s = String::new();
match asc {
Some(true) => s.push_str(" ASC"),
Some(false) => s.push_str(" DESC"),
None => {}
}
match nulls_first {
Some(true) => s.push_str(" NULLS FIRST"),
Some(false) => s.push_str(" NULLS LAST"),
None => {}
}
s
}
pub fn row_pattern(p: &RowPattern) -> String {
match p {
RowPattern::Empty => "()".to_string(),
RowPattern::Symbol(s) => ident_to_sql(s),
RowPattern::Start => "^".to_string(),
RowPattern::Concat(items) => items
.iter()
.map(|item| match item {
RowPattern::Alternation(_) => format!("({})", row_pattern(item)),
_ => row_pattern(item),
})
.collect::<Vec<_>>()
.join(" "),
RowPattern::Alternation(items) => items
.iter()
.map(row_pattern)
.collect::<Vec<_>>()
.join(" | "),
RowPattern::Group(inner) => match inner.as_ref() {
RowPattern::Empty => "()".to_string(),
other => format!("({})", row_pattern(other)),
},
RowPattern::Quantified {
pattern,
quantifier,
reluctant,
} => {
let base = match pattern.as_ref() {
RowPattern::Symbol(_)
| RowPattern::Group(_)
| RowPattern::Empty
| RowPattern::Start => row_pattern(pattern),
RowPattern::Quantified { .. } => row_pattern(pattern),
other => format!("({})", row_pattern(other)),
};
let q = match quantifier {
PatternQuantifier::ZeroOrMore => "*".to_string(),
PatternQuantifier::OneOrMore => "+".to_string(),
PatternQuantifier::ZeroOrOne => "?".to_string(),
PatternQuantifier::Exactly(n) => format!("{{{n}}}"),
PatternQuantifier::Range { min, max } => format!(
"{{{},{}}}",
min.map(|n| n.to_string()).unwrap_or_default(),
max.map(|n| n.to_string()).unwrap_or_default()
),
};
format!("{base}{q}{}", if *reluctant { "?" } else { "" })
}
}
}