use std::borrow::Cow;
use crate::ir::JsonSegment;
use crate::value::Value;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Ident(pub Cow<'static, str>);
impl Ident {
pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
Ident(name.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<&'static str> for Ident {
fn from(name: &'static str) -> Self {
Ident::new(name)
}
}
impl From<String> for Ident {
fn from(name: String) -> Self {
Ident::new(name)
}
}
impl From<Cow<'static, str>> for Ident {
fn from(name: Cow<'static, str>) -> Self {
Ident(name)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ObjectName(pub Vec<Ident>);
impl ObjectName {
pub fn single(name: impl Into<Ident>) -> Self {
ObjectName(vec![name.into()])
}
pub fn parse(text: impl Into<Cow<'static, str>>) -> Self {
let text = text.into();
if !text.contains('.') {
return ObjectName(vec![Ident(text)]);
}
ObjectName(
text.split('.')
.map(|part| Ident::new(part.to_owned()))
.collect(),
)
}
pub fn last(&self) -> Option<&Ident> {
self.0.last()
}
}
impl From<&'static str> for ObjectName {
fn from(name: &'static str) -> Self {
ObjectName::parse(name)
}
}
impl From<String> for ObjectName {
fn from(name: String) -> Self {
ObjectName::parse(name)
}
}
impl From<Ident> for ObjectName {
fn from(name: Ident) -> Self {
ObjectName(vec![name])
}
}
#[derive(Clone, Debug)]
pub enum Statement {
Query(Box<Query>),
Insert(Box<Insert>),
Update(Box<Update>),
Delete(Box<Delete>),
Truncate(Truncate),
}
impl From<Query> for Statement {
fn from(query: Query) -> Self {
Statement::Query(Box::new(query))
}
}
impl From<Insert> for Statement {
fn from(insert: Insert) -> Self {
Statement::Insert(Box::new(insert))
}
}
impl From<Update> for Statement {
fn from(update: Update) -> Self {
Statement::Update(Box::new(update))
}
}
impl From<Delete> for Statement {
fn from(delete: Delete) -> Self {
Statement::Delete(Box::new(delete))
}
}
impl From<Truncate> for Statement {
fn from(truncate: Truncate) -> Self {
Statement::Truncate(truncate)
}
}
#[derive(Clone, Debug)]
pub struct Query {
pub with: Option<With>,
pub body: SetExpr,
pub order_by: Vec<OrderBy>,
pub limit: Option<u64>,
pub offset: Option<u64>,
pub lock: Option<Lock>,
pub max_execution_time: Option<u64>,
}
impl Query {
pub fn new(body: SetExpr) -> Self {
Query {
with: None,
body,
order_by: Vec::new(),
limit: None,
offset: None,
lock: None,
max_execution_time: None,
}
}
pub fn with(mut self, ctes: impl IntoIterator<Item = Cte>) -> Self {
self.with = Some(With {
recursive: false,
ctes: ctes.into_iter().collect(),
});
self
}
pub fn with_recursive(mut self, ctes: impl IntoIterator<Item = Cte>) -> Self {
self.with = Some(With {
recursive: true,
ctes: ctes.into_iter().collect(),
});
self
}
pub fn order_by(mut self, order: OrderBy) -> Self {
self.order_by.push(order);
self
}
pub fn limit(mut self, limit: u64) -> Self {
self.limit = Some(limit);
self
}
pub fn offset(mut self, offset: u64) -> Self {
self.offset = Some(offset);
self
}
pub fn lock(mut self, lock: Lock) -> Self {
self.lock = Some(lock);
self
}
pub fn union(self, other: impl Into<Query>, all: bool) -> Self {
self.combine(SetOperator::Union, all, other.into())
}
pub fn intersect(self, other: impl Into<Query>, all: bool) -> Self {
self.combine(SetOperator::Intersect, all, other.into())
}
pub fn except(self, other: impl Into<Query>, all: bool) -> Self {
self.combine(SetOperator::Except, all, other.into())
}
fn combine(self, op: SetOperator, all: bool, other: Query) -> Self {
Query::new(SetExpr::Operation {
op,
all,
left: Box::new(self.into_set_expr()),
right: Box::new(other.into_set_expr()),
})
}
pub fn into_set_expr(self) -> SetExpr {
if self.with.is_none()
&& self.order_by.is_empty()
&& self.limit.is_none()
&& self.offset.is_none()
&& self.lock.is_none()
&& self.max_execution_time.is_none()
{
self.body
} else {
SetExpr::Query(Box::new(self))
}
}
}
impl From<Select> for Query {
fn from(select: Select) -> Self {
Query::new(SetExpr::Select(Box::new(select)))
}
}
#[derive(Clone, Debug)]
pub struct With {
pub recursive: bool,
pub ctes: Vec<Cte>,
}
#[derive(Clone, Debug)]
pub struct Cte {
pub name: Ident,
pub columns: Vec<Ident>,
pub query: Box<Query>,
}
impl Cte {
pub fn new(name: impl Into<Ident>, query: impl Into<Query>) -> Self {
Cte {
name: name.into(),
columns: Vec::new(),
query: Box::new(query.into()),
}
}
pub fn columns(mut self, columns: impl IntoIterator<Item = impl Into<Ident>>) -> Self {
self.columns = columns.into_iter().map(Into::into).collect();
self
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum SetExpr {
Select(Box<Select>),
Query(Box<Query>),
Operation {
op: SetOperator,
all: bool,
left: Box<SetExpr>,
right: Box<SetExpr>,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SetOperator {
Union,
Intersect,
Except,
}
#[derive(Clone, Debug, Default)]
pub struct Select {
pub distinct: Distinct,
pub items: Vec<SelectItem>,
pub from: Vec<Source>,
pub joins: Vec<Join>,
pub filter: Option<Expr>,
pub group_by: Vec<Expr>,
pub having: Option<Expr>,
}
impl Select {
pub fn new() -> Self {
Select::default()
}
pub fn from_table(table: impl Into<ObjectName>) -> Self {
Select {
from: vec![Source::table(table)],
..Select::default()
}
}
pub fn from_source(source: Source) -> Self {
Select {
from: vec![source],
..Select::default()
}
}
pub fn column(mut self, expr: impl Into<Expr>) -> Self {
self.items.push(SelectItem {
expr: expr.into(),
alias: None,
});
self
}
pub fn column_as(mut self, expr: impl Into<Expr>, alias: impl Into<Ident>) -> Self {
self.items.push(SelectItem {
expr: expr.into(),
alias: Some(alias.into()),
});
self
}
pub fn distinct(mut self) -> Self {
self.distinct = Distinct::Distinct;
self
}
pub fn join(mut self, join: Join) -> Self {
self.joins.push(join);
self
}
pub fn filter(mut self, condition: Expr) -> Self {
self.filter = Some(match self.filter.take() {
Some(existing) => existing.and(condition),
None => condition,
});
self
}
pub fn group_by(mut self, expr: impl Into<Expr>) -> Self {
self.group_by.push(expr.into());
self
}
pub fn having(mut self, condition: Expr) -> Self {
self.having = Some(match self.having.take() {
Some(existing) => existing.and(condition),
None => condition,
});
self
}
}
#[derive(Clone, Debug, Default)]
pub enum Distinct {
#[default]
All,
Distinct,
On(Vec<Expr>),
}
#[derive(Clone, Debug)]
pub struct SelectItem {
pub expr: Expr,
pub alias: Option<Ident>,
}
impl SelectItem {
pub fn new(expr: impl Into<Expr>) -> Self {
SelectItem {
expr: expr.into(),
alias: None,
}
}
pub fn aliased(expr: impl Into<Expr>, alias: impl Into<Ident>) -> Self {
SelectItem {
expr: expr.into(),
alias: Some(alias.into()),
}
}
}
#[derive(Clone, Debug)]
pub enum Source {
Table {
name: ObjectName,
alias: Option<Ident>,
},
Derived {
query: Box<Query>,
alias: Ident,
lateral: bool,
},
Function {
call: Box<Expr>,
alias: Option<Ident>,
},
}
impl Source {
pub fn table(name: impl Into<ObjectName>) -> Self {
Source::Table {
name: name.into(),
alias: None,
}
}
pub fn aliased(name: impl Into<ObjectName>, alias: impl Into<Ident>) -> Self {
Source::Table {
name: name.into(),
alias: Some(alias.into()),
}
}
pub fn derived(query: impl Into<Query>, alias: impl Into<Ident>) -> Self {
Source::Derived {
query: Box::new(query.into()),
alias: alias.into(),
lateral: false,
}
}
pub fn lateral(query: impl Into<Query>, alias: impl Into<Ident>) -> Self {
Source::Derived {
query: Box::new(query.into()),
alias: alias.into(),
lateral: true,
}
}
pub fn function(call: Expr, alias: impl Into<Ident>) -> Self {
Source::Function {
call: Box::new(call),
alias: Some(alias.into()),
}
}
}
#[derive(Clone, Debug)]
pub struct Join {
pub kind: JoinKind,
pub source: Source,
pub on: Option<Expr>,
}
impl Join {
pub fn inner(source: Source, on: Expr) -> Self {
Join {
kind: JoinKind::Inner,
source,
on: Some(on),
}
}
pub fn left(source: Source, on: Expr) -> Self {
Join {
kind: JoinKind::Left,
source,
on: Some(on),
}
}
pub fn cross(source: Source) -> Self {
Join {
kind: JoinKind::Cross,
source,
on: None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum JoinKind {
Inner,
Left,
Right,
Full,
Cross,
}
#[derive(Clone, Debug)]
pub struct OrderBy {
pub expr: Expr,
pub descending: bool,
pub nulls: Option<NullsOrder>,
}
impl OrderBy {
pub fn nulls_first(mut self) -> Self {
self.nulls = Some(NullsOrder::First);
self
}
pub fn nulls_last(mut self) -> Self {
self.nulls = Some(NullsOrder::Last);
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NullsOrder {
First,
Last,
}
#[derive(Clone, Debug)]
pub struct Lock {
pub strength: LockStrength,
pub of: Vec<ObjectName>,
pub wait: LockWait,
}
impl Lock {
pub fn new(strength: LockStrength) -> Self {
Lock {
strength,
of: Vec::new(),
wait: LockWait::Wait,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LockStrength {
Update,
NoKeyUpdate,
Share,
KeyShare,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum LockWait {
#[default]
Wait,
NoWait,
SkipLocked,
}
#[derive(Clone, Debug)]
pub struct Insert {
pub table: ObjectName,
pub columns: Vec<Ident>,
pub source: InsertSource,
pub on_conflict: Option<OnConflict>,
pub returning: Vec<SelectItem>,
}
impl Insert {
pub fn values(
table: impl Into<ObjectName>,
columns: impl IntoIterator<Item = impl Into<Ident>>,
rows: Vec<Vec<Expr>>,
) -> Self {
Insert {
table: table.into(),
columns: columns.into_iter().map(Into::into).collect(),
source: InsertSource::Values(rows),
on_conflict: None,
returning: Vec::new(),
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum InsertSource {
Values(Vec<Vec<Expr>>),
Query(Box<Query>),
DefaultValues,
}
#[derive(Clone, Debug)]
pub struct OnConflict {
pub target: Vec<Ident>,
pub action: ConflictAction,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ConflictAction {
Ignore,
Update {
sets: Vec<Assignment>,
filter: Option<Expr>,
},
}
#[derive(Clone, Debug)]
pub struct Assignment {
pub column: Ident,
pub value: Expr,
}
impl Assignment {
pub fn new(column: impl Into<Ident>, value: impl Into<Expr>) -> Self {
Assignment {
column: column.into(),
value: value.into(),
}
}
}
#[derive(Clone, Debug)]
pub struct Update {
pub table: ObjectName,
pub alias: Option<Ident>,
pub sets: Vec<Assignment>,
pub from: Vec<Source>,
pub filter: Option<Expr>,
pub order_by: Vec<OrderBy>,
pub limit: Option<u64>,
pub returning: Vec<SelectItem>,
}
impl Update {
pub fn new(table: impl Into<ObjectName>, sets: Vec<Assignment>) -> Self {
Update {
table: table.into(),
alias: None,
sets,
from: Vec::new(),
filter: None,
order_by: Vec::new(),
limit: None,
returning: Vec::new(),
}
}
pub fn filter(mut self, condition: Expr) -> Self {
self.filter = Some(match self.filter.take() {
Some(existing) => existing.and(condition),
None => condition,
});
self
}
}
#[derive(Clone, Debug)]
pub struct Delete {
pub table: ObjectName,
pub alias: Option<Ident>,
pub using: Vec<Source>,
pub filter: Option<Expr>,
pub order_by: Vec<OrderBy>,
pub limit: Option<u64>,
pub returning: Vec<SelectItem>,
}
impl Delete {
pub fn new(table: impl Into<ObjectName>) -> Self {
Delete {
table: table.into(),
alias: None,
using: Vec::new(),
filter: None,
order_by: Vec::new(),
limit: None,
returning: Vec::new(),
}
}
pub fn filter(mut self, condition: Expr) -> Self {
self.filter = Some(match self.filter.take() {
Some(existing) => existing.and(condition),
None => condition,
});
self
}
}
#[derive(Clone, Debug)]
pub struct Truncate {
pub table: ObjectName,
pub restart_identity: bool,
pub cascade: bool,
}
#[derive(Clone, Debug)]
pub enum Expr {
Column(ColumnName),
Value(Value),
Literal(Literal),
Raw {
sql: Cow<'static, str>,
values: Vec<Value>,
},
Template {
sql: Cow<'static, str>,
args: Vec<Expr>,
},
Function(Function),
Wildcard(Option<ObjectName>),
Neg(Box<Expr>),
Binary {
left: Box<Expr>,
op: BinaryOp,
right: Box<Expr>,
},
And(Vec<Expr>),
Or(Vec<Expr>),
Not(Box<Expr>),
IsNull {
expr: Box<Expr>,
negated: bool,
},
InList {
expr: Box<Expr>,
list: Vec<Expr>,
negated: bool,
},
InQuery {
expr: Box<Expr>,
query: Box<Query>,
negated: bool,
},
Between {
expr: Box<Expr>,
low: Box<Expr>,
high: Box<Expr>,
negated: bool,
},
Like {
expr: Box<Expr>,
pattern: Box<Expr>,
escape: Option<char>,
negated: bool,
case: LikeCase,
},
Exists {
query: Box<Query>,
negated: bool,
},
Cast {
expr: Box<Expr>,
ty: SqlType,
},
Subquery(Box<Query>),
Tuple(Vec<Expr>),
Case {
operand: Option<Box<Expr>>,
whens: Vec<(Expr, Expr)>,
otherwise: Option<Box<Expr>>,
},
JsonPath {
expr: Box<Expr>,
path: Vec<JsonSegment>,
mode: JsonMode,
},
Excluded(Ident),
Window {
function: Box<Expr>,
partition_by: Vec<Expr>,
order_by: Vec<OrderBy>,
},
Random,
DefaultValue,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ColumnName {
pub table: Option<ObjectName>,
pub name: Ident,
}
#[derive(Clone, Debug)]
pub struct Function {
pub name: Cow<'static, str>,
pub args: Vec<Expr>,
pub distinct: bool,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum Literal {
Null,
Bool(bool),
Int(i64),
String(Cow<'static, str>),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BinaryOp {
Eq,
NotEq,
Lt,
LtEq,
Gt,
GtEq,
NullSafeEq,
NullSafeNotEq,
Add,
Sub,
Mul,
Div,
Mod,
BitAnd,
BitOr,
BitXor,
ShiftLeft,
ShiftRight,
Concat,
Custom(Cow<'static, str>),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum LikeCase {
#[default]
Database,
Ignore,
Match,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum JsonMode {
Text,
Json,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SqlType {
Text,
Integer,
Double,
Decimal {
precision: u8,
scale: u8,
},
Date,
Time,
DateTime,
Json,
Custom(Cow<'static, str>),
}
impl From<Value> for Expr {
fn from(value: Value) -> Self {
Expr::Value(value)
}
}
impl From<Literal> for Expr {
fn from(literal: Literal) -> Self {
Expr::Literal(literal)
}
}
impl From<ColumnName> for Expr {
fn from(column: ColumnName) -> Self {
Expr::Column(column)
}
}
impl From<Query> for Expr {
fn from(query: Query) -> Self {
Expr::Subquery(Box::new(query))
}
}
impl Expr {
pub fn col(name: impl Into<Cow<'static, str>>) -> Expr {
let name = name.into();
match name.rsplit_once('.') {
Some((table, column)) => Expr::qualified(table.to_owned(), column.to_owned()),
None => Expr::Column(ColumnName {
table: None,
name: Ident(name),
}),
}
}
pub fn qualified(table: impl Into<ObjectName>, name: impl Into<Ident>) -> Expr {
Expr::Column(ColumnName {
table: Some(table.into()),
name: name.into(),
})
}
pub fn value(value: impl Into<Value>) -> Expr {
Expr::Value(value.into())
}
pub fn int(value: i64) -> Expr {
Expr::Literal(Literal::Int(value))
}
pub fn string(text: impl Into<Cow<'static, str>>) -> Expr {
Expr::Literal(Literal::String(text.into()))
}
pub fn bool(value: bool) -> Expr {
Expr::Literal(Literal::Bool(value))
}
pub fn null() -> Expr {
Expr::Literal(Literal::Null)
}
pub fn raw(
sql: impl Into<Cow<'static, str>>,
values: impl IntoIterator<Item = impl Into<Value>>,
) -> Expr {
Expr::Raw {
sql: sql.into(),
values: values.into_iter().map(Into::into).collect(),
}
}
pub fn template(sql: impl Into<Cow<'static, str>>, args: Vec<Expr>) -> Expr {
Expr::Template {
sql: sql.into(),
args,
}
}
pub fn func(name: impl Into<Cow<'static, str>>, args: Vec<Expr>) -> Expr {
Expr::Function(Function {
name: name.into(),
args,
distinct: false,
})
}
pub fn func_distinct(name: impl Into<Cow<'static, str>>, args: Vec<Expr>) -> Expr {
Expr::Function(Function {
name: name.into(),
args,
distinct: true,
})
}
pub fn count_all() -> Expr {
Expr::func("COUNT", vec![Expr::Wildcard(None)])
}
pub fn row_number() -> Expr {
Expr::func("ROW_NUMBER", Vec::new())
}
pub fn over(self, partition_by: Vec<Expr>, order_by: Vec<OrderBy>) -> Expr {
Expr::Window {
function: Box::new(self),
partition_by,
order_by,
}
}
pub fn binary(self, op: BinaryOp, right: impl Into<Expr>) -> Expr {
Expr::Binary {
left: Box::new(self),
op,
right: Box::new(right.into()),
}
}
pub fn eq(self, other: impl Into<Expr>) -> Expr {
self.binary(BinaryOp::Eq, other)
}
pub fn ne(self, other: impl Into<Expr>) -> Expr {
self.binary(BinaryOp::NotEq, other)
}
pub fn lt(self, other: impl Into<Expr>) -> Expr {
self.binary(BinaryOp::Lt, other)
}
pub fn lte(self, other: impl Into<Expr>) -> Expr {
self.binary(BinaryOp::LtEq, other)
}
pub fn gt(self, other: impl Into<Expr>) -> Expr {
self.binary(BinaryOp::Gt, other)
}
pub fn gte(self, other: impl Into<Expr>) -> Expr {
self.binary(BinaryOp::GtEq, other)
}
#[allow(clippy::should_implement_trait)]
pub fn add(self, other: impl Into<Expr>) -> Expr {
self.binary(BinaryOp::Add, other)
}
#[allow(clippy::should_implement_trait)]
pub fn sub(self, other: impl Into<Expr>) -> Expr {
self.binary(BinaryOp::Sub, other)
}
#[allow(clippy::should_implement_trait)]
pub fn mul(self, other: impl Into<Expr>) -> Expr {
self.binary(BinaryOp::Mul, other)
}
#[allow(clippy::should_implement_trait)]
pub fn div(self, other: impl Into<Expr>) -> Expr {
self.binary(BinaryOp::Div, other)
}
pub fn and(self, other: Expr) -> Expr {
let mut items = match self {
Expr::And(items) => items,
single => vec![single],
};
match other {
Expr::And(more) => items.extend(more),
single => items.push(single),
}
Expr::And(items)
}
pub fn or(self, other: Expr) -> Expr {
let mut items = match self {
Expr::Or(items) => items,
single => vec![single],
};
match other {
Expr::Or(more) => items.extend(more),
single => items.push(single),
}
Expr::Or(items)
}
#[allow(clippy::should_implement_trait)]
pub fn not(self) -> Expr {
Expr::Not(Box::new(self))
}
pub fn is_null(self) -> Expr {
Expr::IsNull {
expr: Box::new(self),
negated: false,
}
}
pub fn is_not_null(self) -> Expr {
Expr::IsNull {
expr: Box::new(self),
negated: true,
}
}
pub fn in_list(self, list: Vec<Expr>) -> Expr {
Expr::InList {
expr: Box::new(self),
list,
negated: false,
}
}
pub fn not_in_list(self, list: Vec<Expr>) -> Expr {
Expr::InList {
expr: Box::new(self),
list,
negated: true,
}
}
pub fn in_query(self, query: impl Into<Query>) -> Expr {
Expr::InQuery {
expr: Box::new(self),
query: Box::new(query.into()),
negated: false,
}
}
pub fn between(self, low: impl Into<Expr>, high: impl Into<Expr>) -> Expr {
Expr::Between {
expr: Box::new(self),
low: Box::new(low.into()),
high: Box::new(high.into()),
negated: false,
}
}
pub fn like(self, pattern: impl Into<Expr>) -> Expr {
Expr::Like {
expr: Box::new(self),
pattern: Box::new(pattern.into()),
escape: None,
negated: false,
case: LikeCase::Database,
}
}
pub fn exists(query: impl Into<Query>) -> Expr {
Expr::Exists {
query: Box::new(query.into()),
negated: false,
}
}
pub fn cast(self, ty: SqlType) -> Expr {
Expr::Cast {
expr: Box::new(self),
ty,
}
}
pub fn json_text(self, path: Vec<JsonSegment>) -> Expr {
Expr::JsonPath {
expr: Box::new(self),
path,
mode: JsonMode::Text,
}
}
pub fn json(self, path: Vec<JsonSegment>) -> Expr {
Expr::JsonPath {
expr: Box::new(self),
path,
mode: JsonMode::Json,
}
}
pub fn asc(self) -> OrderBy {
OrderBy {
expr: self,
descending: false,
nulls: None,
}
}
pub fn desc(self) -> OrderBy {
OrderBy {
expr: self,
descending: true,
nulls: None,
}
}
pub fn case(whens: Vec<(Expr, Expr)>, otherwise: Option<Expr>) -> Expr {
Expr::Case {
operand: None,
whens,
otherwise: otherwise.map(Box::new),
}
}
}