use std::fmt;
use std::marker::PhantomData;
use std::ops::Not;
use std::sync::Arc;
use crate::sql::Sql;
use crate::{Model, Projected, Select, Value};
pub struct Column<M> {
name: &'static str,
_model: PhantomData<fn() -> M>,
}
impl<M> Column<M> {
pub const fn new(name: &'static str) -> Self {
Self {
name,
_model: PhantomData,
}
}
pub const fn name(&self) -> &'static str {
self.name
}
fn cmp(self, op: &'static str, value: impl Into<Value>) -> Expr<M> {
Expr::new(Cond::Cmp {
term: Term::Column(self.name),
op,
value: value.into(),
})
}
pub fn eq(self, value: impl Into<Value>) -> Expr<M> {
self.cmp("=", value)
}
pub fn ne(self, value: impl Into<Value>) -> Expr<M> {
self.cmp("<>", value)
}
pub fn gt(self, value: impl Into<Value>) -> Expr<M> {
self.cmp(">", value)
}
pub fn gte(self, value: impl Into<Value>) -> Expr<M> {
self.cmp(">=", value)
}
pub fn lt(self, value: impl Into<Value>) -> Expr<M> {
self.cmp("<", value)
}
pub fn lte(self, value: impl Into<Value>) -> Expr<M> {
self.cmp("<=", value)
}
pub fn like(self, pattern: impl Into<Value>) -> Expr<M> {
self.cmp("LIKE", pattern)
}
pub fn not_like(self, pattern: impl Into<Value>) -> Expr<M> {
self.cmp("NOT LIKE", pattern)
}
pub fn ilike(self, pattern: impl Into<Value>) -> Expr<M> {
self.cmp("ILIKE", pattern)
}
pub fn contains(self, text: &str) -> Expr<M> {
self.like(format!("%{}%", escape_like(text)))
}
pub fn starts_with(self, text: &str) -> Expr<M> {
self.like(format!("{}%", escape_like(text)))
}
pub fn ends_with(self, text: &str) -> Expr<M> {
self.like(format!("%{}", escape_like(text)))
}
pub fn is_in<V: Into<Value>>(self, values: impl IntoIterator<Item = V>) -> Expr<M> {
Expr::new(Cond::In {
column: self.name,
values: values.into_iter().map(Into::into).collect(),
negated: false,
})
}
pub fn not_in<V: Into<Value>>(self, values: impl IntoIterator<Item = V>) -> Expr<M> {
Expr::new(Cond::In {
column: self.name,
values: values.into_iter().map(Into::into).collect(),
negated: true,
})
}
pub fn in_subquery<N: Model>(self, subquery: Projected<N>) -> Expr<M> {
Expr::new(Cond::Sub {
kind: SubKind::In {
column: self.name,
negated: false,
},
render: Render::new(move |sql| subquery.write_into(sql)),
})
}
pub fn not_in_subquery<N: Model>(self, subquery: Projected<N>) -> Expr<M> {
Expr::new(Cond::Sub {
kind: SubKind::In {
column: self.name,
negated: true,
},
render: Render::new(move |sql| subquery.write_into(sql)),
})
}
pub fn eq_outer<O: Model>(self, outer: Column<O>) -> Expr<M>
where
M: Model,
{
Expr::new(Cond::Columns {
left: (M::TABLE, self.name),
op: "=",
right: (O::TABLE, outer.name),
})
}
pub fn between(self, low: impl Into<Value>, high: impl Into<Value>) -> Expr<M> {
Expr::new(Cond::Between {
column: self.name,
low: low.into(),
high: high.into(),
})
}
pub fn is_null(self) -> Expr<M> {
Expr::new(Cond::Null {
column: self.name,
negated: false,
})
}
pub fn is_not_null(self) -> Expr<M> {
Expr::new(Cond::Null {
column: self.name,
negated: true,
})
}
pub fn eq_any<T>(self, values: impl IntoIterator<Item = T>) -> Expr<M>
where
Vec<T>: Into<Value>,
{
let values: Vec<T> = values.into_iter().collect();
Expr::raw(format!("{} = ANY(?)", quoted(self.name)), [values.into()])
}
pub fn array_contains(self, values: impl Into<Value>) -> Expr<M> {
self.cmp("@>", values)
}
pub fn array_overlaps(self, values: impl Into<Value>) -> Expr<M> {
self.cmp("&&", values)
}
pub fn array_has(self, value: impl Into<Value>) -> Expr<M> {
Expr::raw(format!("? = ANY({})", quoted(self.name)), [value.into()])
}
pub fn json_has_key(self, key: &str) -> Expr<M> {
self.cmp("?", key)
}
pub fn json_has_any_key<K: Into<String>>(self, keys: impl IntoIterator<Item = K>) -> Expr<M> {
let keys: Vec<String> = keys.into_iter().map(Into::into).collect();
self.cmp("?|", keys)
}
pub fn json_has_all_keys<K: Into<String>>(self, keys: impl IntoIterator<Item = K>) -> Expr<M> {
let keys: Vec<String> = keys.into_iter().map(Into::into).collect();
self.cmp("?&", keys)
}
#[cfg(feature = "json")]
pub fn json_contains(self, json: serde_json::Value) -> Expr<M> {
self.cmp("@>", json)
}
pub fn json_text(self, key: &str) -> Projection<M> {
Projection::raw(format!("{} ->> ?", quoted(self.name)), [key])
}
pub fn json_path_text<K: Into<String>>(
self,
path: impl IntoIterator<Item = K>,
) -> Projection<M> {
let path: Vec<String> = path.into_iter().map(Into::into).collect();
Projection::raw(format!("{} #>> ?", quoted(self.name)), [path])
}
pub fn search(self, query: &str) -> Expr<M> {
Expr::raw(
format!(
"to_tsvector({}) @@ websearch_to_tsquery(?)",
quoted(self.name)
),
[query],
)
}
pub fn search_in(self, config: &str, query: &str) -> Expr<M> {
Expr::raw(
format!(
"to_tsvector(?::regconfig, {}) @@ websearch_to_tsquery(?::regconfig, ?)",
quoted(self.name)
),
[config, config, query],
)
}
pub fn ts_matches(self, query: &str) -> Expr<M> {
Expr::raw(
format!("{} @@ websearch_to_tsquery(?)", quoted(self.name)),
[query],
)
}
pub fn search_rank(self, query: &str) -> Projection<M> {
Projection::raw(
format!(
"ts_rank(to_tsvector({}), websearch_to_tsquery(?))",
quoted(self.name)
),
[query],
)
}
pub fn count(self) -> Projection<M> {
Projection::func("COUNT", Some(self.name), false)
}
pub fn count_distinct(self) -> Projection<M> {
Projection::func("COUNT", Some(self.name), true)
}
pub fn sum(self) -> Projection<M> {
Projection::func("SUM", Some(self.name), false)
}
pub fn avg(self) -> Projection<M> {
Projection::func("AVG", Some(self.name), false)
}
pub fn min(self) -> Projection<M> {
Projection::func("MIN", Some(self.name), false)
}
pub fn max(self) -> Projection<M> {
Projection::func("MAX", Some(self.name), false)
}
pub fn asc(self) -> Order<M> {
Order::new(self.name, Direction::Asc)
}
pub fn desc(self) -> Order<M> {
Order::new(self.name, Direction::Desc)
}
}
impl<M> Clone for Column<M> {
fn clone(&self) -> Self {
*self
}
}
impl<M> Copy for Column<M> {}
impl<M> fmt::Debug for Column<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Column").field(&self.name).finish()
}
}
impl<M> fmt::Display for Column<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name)
}
}
fn quoted(ident: &str) -> String {
let mut s = String::new();
crate::sql::push_ident(&mut s, ident);
s
}
fn escape_like(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
if matches!(c, '%' | '_' | '\\') {
out.push('\\');
}
out.push(c);
}
out
}
pub struct Expr<M> {
pub(crate) cond: Cond,
_model: PhantomData<fn() -> M>,
}
impl<M> Expr<M> {
fn new(cond: Cond) -> Self {
Self {
cond,
_model: PhantomData,
}
}
pub fn raw<V: Into<Value>>(
sql: impl Into<String>,
params: impl IntoIterator<Item = V>,
) -> Self {
Self::new(Cond::Raw {
sql: sql.into(),
params: params.into_iter().map(Into::into).collect(),
})
}
pub fn all() -> Self {
Self::new(Cond::And(Vec::new()))
}
pub fn none() -> Self {
Self::new(Cond::Or(Vec::new()))
}
pub fn exists<N: Model>(subquery: Select<N>) -> Self {
Self::new(Cond::Sub {
kind: SubKind::Exists { negated: false },
render: Render::new(move |sql| subquery.write_exists_body(sql)),
})
}
pub fn not_exists<N: Model>(subquery: Select<N>) -> Self {
Self::new(Cond::Sub {
kind: SubKind::Exists { negated: true },
render: Render::new(move |sql| subquery.write_exists_body(sql)),
})
}
pub fn and(self, other: Expr<M>) -> Self {
Self::new(match self.cond {
Cond::And(mut list) => {
list.push(other.cond);
Cond::And(list)
}
cond => Cond::And(vec![cond, other.cond]),
})
}
pub fn or(self, other: Expr<M>) -> Self {
Self::new(match self.cond {
Cond::Or(mut list) if !list.is_empty() => {
list.push(other.cond);
Cond::Or(list)
}
cond => Cond::Or(vec![cond, other.cond]),
})
}
pub fn all_of(exprs: impl IntoIterator<Item = Expr<M>>) -> Self {
Self::new(Cond::And(exprs.into_iter().map(|e| e.cond).collect()))
}
pub fn any_of(exprs: impl IntoIterator<Item = Expr<M>>) -> Self {
Self::new(Cond::Or(exprs.into_iter().map(|e| e.cond).collect()))
}
}
impl<M> Not for Expr<M> {
type Output = Expr<M>;
fn not(self) -> Self::Output {
Self::new(Cond::Not(Box::new(self.cond)))
}
}
impl<M> Clone for Expr<M> {
fn clone(&self) -> Self {
Self::new(self.cond.clone())
}
}
impl<M> fmt::Debug for Expr<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.cond.fmt(f)
}
}
#[derive(Debug, Clone)]
pub(crate) enum Term {
Column(&'static str),
Func {
func: &'static str,
arg: Option<&'static str>,
distinct: bool,
},
Cast(Box<Term>, &'static str),
Raw(String, Vec<Value>),
}
impl Term {
pub(crate) fn write(&self, sql: &mut Sql) {
match self {
Term::Column(name) => {
sql.push_ident(name);
}
Term::Func {
func,
arg,
distinct,
} => {
sql.push(func).push("(");
if *distinct {
sql.push("DISTINCT ");
}
match arg {
Some(arg) => sql.push_ident(arg),
None => sql.push("*"),
};
sql.push(")");
}
Term::Cast(inner, ty) => {
sql.push("CAST(");
inner.write(sql);
sql.push(" AS ").push(ty).push(")");
}
Term::Raw(raw, params) => {
sql.push("(").push_raw(raw, params).push(")");
}
}
}
}
#[derive(Clone)]
pub(crate) struct Render(Arc<dyn Fn(&mut Sql) + Send + Sync>);
impl Render {
fn new(f: impl Fn(&mut Sql) + Send + Sync + 'static) -> Self {
Self(Arc::new(f))
}
}
impl fmt::Debug for Render {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut sql = Sql::new();
(self.0)(&mut sql);
f.write_str(sql.as_str())
}
}
#[derive(Debug, Clone)]
pub(crate) enum SubKind {
In { column: &'static str, negated: bool },
Exists { negated: bool },
}
#[derive(Debug, Clone)]
pub(crate) enum Cond {
Sub {
kind: SubKind,
render: Render,
},
Columns {
left: (&'static str, &'static str),
op: &'static str,
right: (&'static str, &'static str),
},
Cmp {
term: Term,
op: &'static str,
value: Value,
},
In {
column: &'static str,
values: Vec<Value>,
negated: bool,
},
Between {
column: &'static str,
low: Value,
high: Value,
},
Null {
column: &'static str,
negated: bool,
},
Raw {
sql: String,
params: Vec<Value>,
},
And(Vec<Cond>),
Or(Vec<Cond>),
Not(Box<Cond>),
}
impl Cond {
pub(crate) fn write(&self, sql: &mut Sql) {
match self {
Cond::Sub { kind, render } => {
match kind {
SubKind::In { column, negated } => {
sql.push_ident(column)
.push(if *negated { " NOT IN (" } else { " IN (" });
}
SubKind::Exists { negated } => {
sql.push(if *negated { "NOT EXISTS (" } else { "EXISTS (" });
}
}
(render.0)(sql);
sql.push(")");
}
Cond::Columns { left, op, right } => {
sql.push_ident(left.0).push(".").push_ident(left.1);
sql.push(" ").push(op).push(" ");
sql.push_ident(right.0).push(".").push_ident(right.1);
}
Cond::Cmp { term, op, value } => {
term.write(sql);
sql.push(" ").push(op).push(" ");
sql.bind(value.clone());
}
Cond::In {
column,
values,
negated,
} => {
if values.is_empty() {
sql.push(if *negated { "TRUE" } else { "FALSE" });
return;
}
sql.push_ident(column)
.push(if *negated { " NOT IN (" } else { " IN (" });
sql.push_list(values, ", ", |sql, v| {
sql.bind(v.clone());
});
sql.push(")");
}
Cond::Between { column, low, high } => {
sql.push_ident(column).push(" BETWEEN ");
sql.bind(low.clone()).push(" AND ").bind(high.clone());
}
Cond::Null { column, negated } => {
sql.push_ident(column)
.push(if *negated { " IS NOT NULL" } else { " IS NULL" });
}
Cond::Raw { sql: raw, params } => {
sql.push("(").push_raw(raw, params).push(")");
}
Cond::And(list) => Self::write_group(sql, list, " AND ", "TRUE"),
Cond::Or(list) => Self::write_group(sql, list, " OR ", "FALSE"),
Cond::Not(inner) => {
sql.push("NOT (");
inner.write(sql);
sql.push(")");
}
}
}
fn write_group(sql: &mut Sql, list: &[Cond], sep: &str, empty: &str) {
match list {
[] => {
sql.push(empty);
}
[single] => single.write(sql),
many => {
sql.push("(");
sql.push_list(many, sep, |sql, c| c.write(sql));
sql.push(")");
}
}
}
}
pub struct Projection<M> {
pub(crate) term: Term,
pub(crate) alias: Option<&'static str>,
_model: PhantomData<fn() -> M>,
}
impl<M> Projection<M> {
fn new(term: Term) -> Self {
Self {
term,
alias: None,
_model: PhantomData,
}
}
fn func(func: &'static str, arg: Option<&'static str>, distinct: bool) -> Self {
Self::new(Term::Func {
func,
arg,
distinct,
})
}
pub fn count_all() -> Self {
Self::func("COUNT", None, false)
}
pub fn raw<V: Into<Value>>(
sql: impl Into<String>,
params: impl IntoIterator<Item = V>,
) -> Self {
Self::new(Term::Raw(
sql.into(),
params.into_iter().map(Into::into).collect(),
))
}
pub fn cast(self, sql_type: &'static str) -> Self {
Self {
term: Term::Cast(Box::new(self.term), sql_type),
..self
}
}
pub fn alias(mut self, alias: &'static str) -> Self {
self.alias = Some(alias);
self
}
fn cmp(self, op: &'static str, value: impl Into<Value>) -> Expr<M> {
Expr::new(Cond::Cmp {
term: self.term,
op,
value: value.into(),
})
}
pub fn eq(self, value: impl Into<Value>) -> Expr<M> {
self.cmp("=", value)
}
pub fn ne(self, value: impl Into<Value>) -> Expr<M> {
self.cmp("<>", value)
}
pub fn gt(self, value: impl Into<Value>) -> Expr<M> {
self.cmp(">", value)
}
pub fn gte(self, value: impl Into<Value>) -> Expr<M> {
self.cmp(">=", value)
}
pub fn lt(self, value: impl Into<Value>) -> Expr<M> {
self.cmp("<", value)
}
pub fn lte(self, value: impl Into<Value>) -> Expr<M> {
self.cmp("<=", value)
}
pub fn asc(self) -> Order<M> {
Order::with_target(OrderTarget::Term(self.term), Direction::Asc)
}
pub fn desc(self) -> Order<M> {
Order::with_target(OrderTarget::Term(self.term), Direction::Desc)
}
pub(crate) fn write(&self, sql: &mut Sql) {
self.term.write(sql);
if let Some(alias) = self.alias {
sql.push(" AS ").push_ident(alias);
}
}
}
impl<M> From<Column<M>> for Projection<M> {
fn from(column: Column<M>) -> Self {
Self::new(Term::Column(column.name()))
}
}
impl<M> Clone for Projection<M> {
fn clone(&self) -> Self {
Self {
term: self.term.clone(),
alias: self.alias,
_model: PhantomData,
}
}
}
impl<M> fmt::Debug for Projection<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut sql = Sql::new();
self.write(&mut sql);
f.debug_tuple("Projection").field(&sql.as_str()).finish()
}
}
pub trait IntoProjections<M> {
fn into_projections(self) -> Vec<Projection<M>>;
}
impl<M> IntoProjections<M> for Column<M> {
fn into_projections(self) -> Vec<Projection<M>> {
vec![self.into()]
}
}
impl<M> IntoProjections<M> for Projection<M> {
fn into_projections(self) -> Vec<Projection<M>> {
vec![self]
}
}
impl<M, P: Into<Projection<M>>> IntoProjections<M> for Vec<P> {
fn into_projections(self) -> Vec<Projection<M>> {
self.into_iter().map(Into::into).collect()
}
}
impl<M, P: Into<Projection<M>>, const N: usize> IntoProjections<M> for [P; N] {
fn into_projections(self) -> Vec<Projection<M>> {
self.into_iter().map(Into::into).collect()
}
}
macro_rules! impl_into_projections_for_tuples {
($(($($t:ident),+)),+ $(,)?) => {$(
#[allow(non_snake_case)]
impl<M, $($t: Into<Projection<M>>),+> IntoProjections<M> for ($($t,)+) {
fn into_projections(self) -> Vec<Projection<M>> {
let ($($t,)+) = self;
vec![$($t.into()),+]
}
}
)+};
}
impl_into_projections_for_tuples! {
(A),
(A, B),
(A, B, C),
(A, B, C, D),
(A, B, C, D, E),
(A, B, C, D, E, F),
(A, B, C, D, E, F, G),
(A, B, C, D, E, F, G, H),
(A, B, C, D, E, F, G, H, I),
(A, B, C, D, E, F, G, H, I, J),
(A, B, C, D, E, F, G, H, I, J, K),
(A, B, C, D, E, F, G, H, I, J, K, L),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
Asc,
Desc,
}
pub struct Order<M> {
pub(crate) target: OrderTarget,
pub(crate) direction: Direction,
pub(crate) nulls: Option<bool>,
_model: PhantomData<fn() -> M>,
}
#[derive(Debug, Clone)]
pub(crate) enum OrderTarget {
Column(&'static str),
Term(Term),
}
impl<M> Order<M> {
pub(crate) fn new(column: &'static str, direction: Direction) -> Self {
Self::with_target(OrderTarget::Column(column), direction)
}
fn with_target(target: OrderTarget, direction: Direction) -> Self {
Self {
target,
direction,
nulls: None,
_model: PhantomData,
}
}
pub(crate) fn column(&self) -> Option<&'static str> {
match self.target {
OrderTarget::Column(c) => Some(c),
OrderTarget::Term(_) => None,
}
}
pub fn nulls_first(mut self) -> Self {
self.nulls = Some(true);
self
}
pub fn nulls_last(mut self) -> Self {
self.nulls = Some(false);
self
}
pub(crate) fn write_key(&self, sql: &mut Sql, prefix: &str, alias: Option<&str>) {
match (&self.target, alias) {
(OrderTarget::Column(c), _) => {
sql.push(prefix).push_ident(c);
}
(OrderTarget::Term(_), Some(alias)) => {
sql.push(prefix).push_ident(alias);
}
(OrderTarget::Term(term), None) => term.write(sql),
}
}
pub(crate) fn write_direction(&self, sql: &mut Sql) {
sql.push(match self.direction {
Direction::Asc => " ASC",
Direction::Desc => " DESC",
});
match self.nulls {
Some(true) => sql.push(" NULLS FIRST"),
Some(false) => sql.push(" NULLS LAST"),
None => sql,
};
}
pub(crate) fn write(&self, sql: &mut Sql) {
self.write_key(sql, "", None);
self.write_direction(sql);
}
}
impl<M> Clone for Order<M> {
fn clone(&self) -> Self {
Self {
target: self.target.clone(),
direction: self.direction,
nulls: self.nulls,
_model: PhantomData,
}
}
}
impl<M> fmt::Debug for Order<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut sql = Sql::new();
self.write(&mut sql);
f.debug_tuple("Order").field(&sql.as_str()).finish()
}
}
impl<M> From<Column<M>> for Order<M> {
fn from(column: Column<M>) -> Self {
column.asc()
}
}
#[cfg(test)]
mod tests {
use super::*;
struct T;
const A: Column<T> = Column::new("a");
const B: Column<T> = Column::new("b");
fn render(e: Expr<T>) -> String {
let mut sql = Sql::new();
e.cond.write(&mut sql);
sql.as_str().to_owned()
}
#[test]
fn renders_conditions() {
assert_eq!(render(A.eq(1)), r#""a" = $1"#);
assert_eq!(render(A.eq(1).and(B.gt(2))), r#"("a" = $1 AND "b" > $2)"#);
assert_eq!(
render(A.eq(1).or(B.is_null()).and(!A.is_in([1, 2]))),
r#"(("a" = $1 OR "b" IS NULL) AND NOT ("a" IN ($2, $3)))"#
);
assert_eq!(render(A.is_in(Vec::<i32>::new())), "FALSE");
assert_eq!(render(A.not_in(Vec::<i32>::new())), "TRUE");
assert_eq!(render(A.between(1, 5)), r#""a" BETWEEN $1 AND $2"#);
assert_eq!(render(Expr::all()), "TRUE");
assert_eq!(render(Expr::any_of([])), "FALSE");
assert_eq!(render(Expr::raw("lower(a) = ?", ["x"])), "(lower(a) = $1)");
assert_eq!(
render(A.sum().cast("BIGINT").gt(5)),
r#"CAST(SUM("a") AS BIGINT) > $1"#
);
assert_eq!(render(Projection::count_all().gte(2)), "COUNT(*) >= $1");
assert_eq!(
render(B.count_distinct().eq(1)),
r#"COUNT(DISTINCT "b") = $1"#
);
}
#[test]
fn escapes_like_patterns() {
let mut sql = Sql::new();
A.contains("50%_off").cond.write(&mut sql);
assert_eq!(sql.params()[0], Value::from(r"%50\%\_off%"));
}
}