use std::borrow::Cow;
use std::fmt;
use std::marker::PhantomData;
use crate::ir::{Boolean, ColumnRef, Expr, InValues, Operator, Order, QueryIr, Where, WhereClause};
use crate::row::Row;
use crate::value::{Field, FieldError, Value, ValueFor, is_null};
pub type Encoder<T> = fn(&T) -> Result<Value, String>;
pub type Decoder<T> = fn(&Row, &str) -> Result<T, FieldError>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Untyped;
pub struct Column<M, T> {
table: Option<Cow<'static, str>>,
name: Cow<'static, str>,
encode: Encoder<T>,
decode: Decoder<T>,
_model: PhantomData<fn() -> M>,
}
impl<M, T> Clone for Column<M, T> {
fn clone(&self) -> Self {
Column {
table: self.table.clone(),
name: self.name.clone(),
encode: self.encode,
decode: self.decode,
_model: PhantomData,
}
}
}
impl<M, T> fmt::Debug for Column<M, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Column")
.field(&self.column_ref().to_string())
.finish()
}
}
fn encode_field<T: Field>(value: &T) -> Result<Value, String> {
Ok(value.to_value())
}
fn decode_field<T: Field>(row: &Row, column: &str) -> Result<T, FieldError> {
row.field(column)
}
impl<M, T: Field> Column<M, T> {
pub const fn field(table: &'static str, name: &'static str) -> Self {
Column {
table: Some(Cow::Borrowed(table)),
name: Cow::Borrowed(name),
encode: encode_field::<T>,
decode: decode_field::<T>,
_model: PhantomData,
}
}
}
impl<M, T> Column<M, T> {
pub const fn with_codec(
table: &'static str,
name: &'static str,
encode: Encoder<T>,
decode: Decoder<T>,
) -> Self {
Column {
table: Some(Cow::Borrowed(table)),
name: Cow::Borrowed(name),
encode,
decode,
_model: PhantomData,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn table(&self) -> Option<&str> {
self.table.as_deref()
}
pub fn column_ref(&self) -> ColumnRef {
let mut column = ColumnRef::parse(self.name.clone());
if column.table.is_none() {
column.table = self.table.clone();
}
column
}
pub fn expr(&self) -> Expr {
Expr::Column(self.column_ref())
}
pub fn unqualified(&self) -> Self {
Column {
table: None,
..self.clone()
}
}
pub fn encode(&self, value: &T) -> Result<Value, String> {
(self.encode)(value)
}
pub fn decode(&self, row: &Row) -> Result<T, FieldError> {
(self.decode)(row, ColumnRef::parse(self.name.clone()).name.as_ref())
}
pub fn decode_as(&self, row: &Row, column: &str) -> Result<T, FieldError> {
(self.decode)(row, column)
}
pub fn json(&self, path: &str) -> Column<Untyped, Value> {
Column {
table: self.table.clone(),
name: Cow::Owned(format!("{}->{path}", self.name)),
encode: encode_field::<Value>,
decode: decode_field::<Value>,
_model: PhantomData,
}
}
fn value_operand(&self, value: &T) -> Result<Expr, String> {
(self.encode)(value)
.map(Expr::Value)
.map_err(|error| format!("cannot use a value for column `{}`: {error}", self.name))
}
fn compare(&self, op: Operator, value: T) -> Filter {
match self.value_operand(&value) {
Ok(right) => Filter::compare(self.expr(), op, right),
Err(error) => Filter(Where::Invalid(error)),
}
}
pub fn eq(&self, value: impl ValueFor<T>) -> Filter {
self.compare(Operator::Eq, value.into_value_for())
}
pub fn ne(&self, value: impl ValueFor<T>) -> Filter {
self.compare(Operator::Ne, value.into_value_for())
}
pub fn gt(&self, value: impl ValueFor<T>) -> Filter {
self.compare(Operator::Gt, value.into_value_for())
}
pub fn gte(&self, value: impl ValueFor<T>) -> Filter {
self.compare(Operator::Gte, value.into_value_for())
}
pub fn lt(&self, value: impl ValueFor<T>) -> Filter {
self.compare(Operator::Lt, value.into_value_for())
}
pub fn lte(&self, value: impl ValueFor<T>) -> Filter {
self.compare(Operator::Lte, value.into_value_for())
}
pub fn op(&self, op: impl Into<Operator>, value: impl ValueFor<T>) -> Filter {
self.compare(op.into(), value.into_value_for())
}
pub fn null_safe_eq(&self, value: impl ValueFor<T>) -> Filter {
match self.value_operand(&value.into_value_for()) {
Ok(right) => Filter(Where::Compare {
left: self.expr(),
op: Operator::NullSafeEq,
right,
}),
Err(error) => Filter(Where::Invalid(error)),
}
}
fn list(&self, values: impl IntoIterator<Item = impl ValueFor<T>>, not: bool) -> Filter {
let encoded: Result<Vec<Expr>, String> = values
.into_iter()
.map(|value| self.value_operand(&value.into_value_for()))
.collect();
match encoded {
Ok(values) => Filter(Where::In {
expr: self.expr(),
values: InValues::List(values),
not,
}),
Err(error) => Filter(Where::Invalid(error)),
}
}
pub fn is_in(&self, values: impl IntoIterator<Item = impl ValueFor<T>>) -> Filter {
self.list(values, false)
}
pub fn not_in(&self, values: impl IntoIterator<Item = impl ValueFor<T>>) -> Filter {
self.list(values, true)
}
pub fn in_subquery(&self, query: impl IntoQuery) -> Filter {
Filter(Where::In {
expr: self.expr(),
values: InValues::Subquery(Box::new(query.into_query())),
not: false,
})
}
pub fn not_in_subquery(&self, query: impl IntoQuery) -> Filter {
Filter(Where::In {
expr: self.expr(),
values: InValues::Subquery(Box::new(query.into_query())),
not: true,
})
}
pub fn is_null(&self) -> Filter {
Filter(Where::Null {
expr: self.expr(),
not: false,
})
}
pub fn is_not_null(&self) -> Filter {
Filter(Where::Null {
expr: self.expr(),
not: true,
})
}
fn range(&self, low: T, high: T, not: bool) -> Filter {
match (self.value_operand(&low), self.value_operand(&high)) {
(Ok(low), Ok(high)) => Filter(Where::Between {
expr: self.expr(),
low,
high,
not,
}),
(Err(error), _) | (_, Err(error)) => Filter(Where::Invalid(error)),
}
}
pub fn between(&self, low: impl ValueFor<T>, high: impl ValueFor<T>) -> Filter {
self.range(low.into_value_for(), high.into_value_for(), false)
}
pub fn not_between(&self, low: impl ValueFor<T>, high: impl ValueFor<T>) -> Filter {
self.range(low.into_value_for(), high.into_value_for(), true)
}
pub fn eq_column<N, U>(&self, other: &Column<N, U>) -> Filter {
Filter::compare(self.expr(), Operator::Eq, other.expr())
}
pub fn op_column<N, U>(&self, op: impl Into<Operator>, other: &Column<N, U>) -> Filter {
Filter::compare(self.expr(), op.into(), other.expr())
}
pub fn asc(&self) -> Order {
Order::asc(self.expr())
}
pub fn desc(&self) -> Order {
Order::desc(self.expr())
}
pub fn set(&self, value: impl ValueFor<T>) -> Assignment {
match (self.encode)(&value.into_value_for()) {
Ok(value) => Assignment::value(self.name.clone(), value),
Err(error) => Assignment::invalid(
self.name.clone(),
format!("cannot use a value for column `{}`: {error}", self.name),
),
}
}
pub fn set_expr(&self, expr: impl Into<Expr>) -> Assignment {
Assignment {
column: self.name.clone(),
value: AssignedValue::Expr(expr.into()),
}
}
pub fn set_null(&self) -> Assignment
where
T: Field,
{
Assignment::value(self.name.clone(), T::null())
}
pub fn count(&self) -> Expr {
Expr::count(self.expr())
}
pub fn sum(&self) -> Expr {
Expr::sum(self.expr())
}
pub fn avg(&self) -> Expr {
Expr::avg(self.expr())
}
pub fn min(&self) -> Expr {
Expr::min(self.expr())
}
pub fn max(&self) -> Expr {
Expr::max(self.expr())
}
}
impl<M> Column<M, String> {
pub fn like(&self, pattern: impl Into<String>) -> Filter {
Filter::like(self.expr(), pattern.into(), false, false)
}
pub fn not_like(&self, pattern: impl Into<String>) -> Filter {
Filter::like(self.expr(), pattern.into(), false, true)
}
pub fn like_case_sensitive(&self, pattern: impl Into<String>) -> Filter {
Filter::like(self.expr(), pattern.into(), true, false)
}
}
impl<M> Column<M, Option<String>> {
pub fn like(&self, pattern: impl Into<String>) -> Filter {
Filter::like(self.expr(), pattern.into(), false, false)
}
pub fn not_like(&self, pattern: impl Into<String>) -> Filter {
Filter::like(self.expr(), pattern.into(), false, true)
}
pub fn like_case_sensitive(&self, pattern: impl Into<String>) -> Filter {
Filter::like(self.expr(), pattern.into(), true, false)
}
}
impl<M> Column<M, Value> {
pub fn like(&self, pattern: impl Into<String>) -> Filter {
Filter::like(self.expr(), pattern.into(), false, false)
}
pub fn not_like(&self, pattern: impl Into<String>) -> Filter {
Filter::like(self.expr(), pattern.into(), false, true)
}
pub fn like_case_sensitive(&self, pattern: impl Into<String>) -> Filter {
Filter::like(self.expr(), pattern.into(), true, false)
}
}
pub fn col(name: impl Into<Cow<'static, str>>) -> Column<Untyped, Value> {
let column = ColumnRef::parse(name);
let name = match column.path.is_empty() {
true => column.name.clone(),
false => Cow::Owned(column.without_path().name.to_string() + &json_suffix(&column)),
};
Column {
table: column.table,
name,
encode: encode_field::<Value>,
decode: decode_field::<Value>,
_model: PhantomData,
}
}
pub fn col_as<T: Field>(name: impl Into<Cow<'static, str>>) -> Column<Untyped, T> {
let untyped = col(name);
Column {
table: untyped.table,
name: untyped.name,
encode: encode_field::<T>,
decode: decode_field::<T>,
_model: PhantomData,
}
}
fn json_suffix(column: &ColumnRef) -> String {
let text = column.to_string();
match text.find("->") {
Some(at) => text[at..].to_owned(),
None => String::new(),
}
}
#[derive(Clone, Debug)]
pub struct Filter(pub(crate) Where);
impl Filter {
pub(crate) fn compare(left: Expr, op: Operator, right: Expr) -> Filter {
if let Expr::Value(value) = &right
&& is_null(value)
{
return match op {
Operator::Eq => Filter(Where::Null {
expr: left,
not: false,
}),
Operator::Ne => Filter(Where::Null {
expr: left,
not: true,
}),
Operator::NullSafeEq => Filter(Where::Compare { left, op, right }),
other => Filter(Where::Invalid(format!(
"a NULL value cannot be compared with `{other:?}`; use is_null() or is_not_null()"
))),
};
}
Filter(Where::Compare { left, op, right })
}
pub(crate) fn like(expr: Expr, pattern: String, case_sensitive: bool, not: bool) -> Filter {
Filter(Where::Like {
expr,
pattern: Expr::Value(Value::from(pattern)),
case_sensitive,
not,
})
}
pub fn raw(
sql: impl Into<Cow<'static, str>>,
values: impl IntoIterator<Item = impl Into<Value>>,
) -> Filter {
Filter(Where::Raw {
sql: sql.into(),
values: values.into_iter().map(Into::into).collect(),
})
}
pub fn exists(query: impl IntoQuery) -> Filter {
Filter(Where::Exists {
query: Box::new(query.into_query()),
not: false,
})
}
pub fn not_exists(query: impl IntoQuery) -> Filter {
Filter(Where::Exists {
query: Box::new(query.into_query()),
not: true,
})
}
pub fn and(self, other: impl Into<Filter>) -> Filter {
Filter(Where::Group(vec![
WhereClause::and(self.0),
WhereClause::and(other.into().0),
]))
}
pub fn or(self, other: impl Into<Filter>) -> Filter {
Filter(Where::Group(vec![
WhereClause::and(self.0),
WhereClause::or(other.into().0),
]))
}
#[allow(clippy::should_implement_trait)]
pub fn not(self) -> Filter {
Filter(Where::Group(vec![WhereClause {
boolean: Boolean::And,
negated: true,
filter: self.0,
}]))
}
pub fn all(filters: impl IntoIterator<Item = impl Into<Filter>>) -> Filter {
Filter(Where::Group(
filters
.into_iter()
.map(|filter| WhereClause::and(filter.into().0))
.collect(),
))
}
pub fn any(filters: impl IntoIterator<Item = impl Into<Filter>>) -> Filter {
let clauses: Vec<WhereClause> = filters
.into_iter()
.map(|filter| WhereClause::or(filter.into().0))
.collect();
if clauses.is_empty() {
return Filter(Where::Raw {
sql: Cow::Borrowed("1 = 0"),
values: Vec::new(),
});
}
Filter(Where::Group(clauses))
}
pub fn into_where(self) -> Where {
self.0
}
pub fn to_sql(&self, dialect: crate::Dialect) -> Result<crate::Statement, crate::OrmError> {
crate::sql::render_filter(&self.0, dialect)
}
}
impl From<Where> for Filter {
fn from(filter: Where) -> Self {
Filter(filter)
}
}
impl From<crate::render::ast::Expr> for Filter {
fn from(condition: crate::render::ast::Expr) -> Self {
Filter(Where::Tree(Box::new(condition)))
}
}
impl From<navree_db::Statement> for Filter {
fn from(statement: navree_db::Statement) -> Self {
if let Some(backend) = statement.backend() {
return Filter(Where::Invalid(format!(
"a filter fragment must use portable `?` placeholders; this one was written for {backend}"
)));
}
let (sql, values) = statement.into_parts();
Filter(Where::Raw {
sql: Cow::Owned(sql),
values,
})
}
}
#[derive(Clone, Debug)]
pub struct Assignment {
pub(crate) column: Cow<'static, str>,
pub(crate) value: AssignedValue,
}
#[derive(Clone, Debug)]
pub(crate) enum AssignedValue {
Value(Value),
Expr(Expr),
Invalid(String),
}
impl Assignment {
pub fn value(column: impl Into<Cow<'static, str>>, value: impl Into<Value>) -> Self {
Assignment {
column: column.into(),
value: AssignedValue::Value(value.into()),
}
}
pub(crate) fn invalid(column: Cow<'static, str>, message: String) -> Self {
Assignment {
column,
value: AssignedValue::Invalid(message),
}
}
pub fn column(&self) -> &str {
&self.column
}
pub fn assigned_value(&self) -> Option<&Value> {
match &self.value {
AssignedValue::Value(value) => Some(value),
AssignedValue::Expr(_) | AssignedValue::Invalid(_) => None,
}
}
pub(crate) fn into_set(self) -> Result<(Cow<'static, str>, Expr), String> {
match self.value {
AssignedValue::Value(value) => Ok((self.column, Expr::Value(value))),
AssignedValue::Expr(expr) => Ok((self.column, expr)),
AssignedValue::Invalid(error) => Err(error),
}
}
pub(crate) fn to_filter(&self, table: Option<&'static str>) -> Filter {
let mut column = ColumnRef::parse(self.column.clone());
if column.table.is_none() {
column.table = table.map(Cow::Borrowed);
}
match &self.value {
AssignedValue::Value(value) => Filter::compare(
Expr::Column(column),
Operator::Eq,
Expr::Value(value.clone()),
),
AssignedValue::Expr(expr) => {
Filter::compare(Expr::Column(column), Operator::Eq, expr.clone())
}
AssignedValue::Invalid(error) => Filter(Where::Invalid(error.clone())),
}
}
}
pub trait ColumnName {
fn column_name(&self) -> Cow<'_, str>;
}
impl<M, T> ColumnName for Column<M, T> {
fn column_name(&self) -> Cow<'_, str> {
Cow::Owned(ColumnRef::parse(self.name.clone()).name.into_owned())
}
}
impl ColumnName for &str {
fn column_name(&self) -> Cow<'_, str> {
Cow::Borrowed(self)
}
}
impl ColumnName for String {
fn column_name(&self) -> Cow<'_, str> {
Cow::Borrowed(self)
}
}
pub trait ColumnOf<T> {
fn column_ref(&self) -> ColumnRef;
fn encode_value(&self, value: &T) -> Result<Value, String>;
}
impl<M, T> ColumnOf<T> for Column<M, T> {
fn column_ref(&self) -> ColumnRef {
Column::column_ref(self)
}
fn encode_value(&self, value: &T) -> Result<Value, String> {
(self.encode)(value)
}
}
impl ColumnOf<Value> for &str {
fn column_ref(&self) -> ColumnRef {
ColumnRef::parse(Cow::Owned((*self).to_owned()))
}
fn encode_value(&self, value: &Value) -> Result<Value, String> {
Ok(value.clone())
}
}
impl ColumnOf<Value> for String {
fn column_ref(&self) -> ColumnRef {
ColumnRef::parse(Cow::Owned(self.clone()))
}
fn encode_value(&self, value: &Value) -> Result<Value, String> {
Ok(value.clone())
}
}
pub trait IntoExpr {
fn into_expr(self) -> Expr;
}
impl<M, T> IntoExpr for Column<M, T> {
fn into_expr(self) -> Expr {
self.expr()
}
}
impl<M, T> IntoExpr for &Column<M, T> {
fn into_expr(self) -> Expr {
self.expr()
}
}
impl IntoExpr for &str {
fn into_expr(self) -> Expr {
column_or_all(Cow::Owned(self.to_owned()))
}
}
impl IntoExpr for String {
fn into_expr(self) -> Expr {
column_or_all(Cow::Owned(self))
}
}
impl IntoExpr for Expr {
fn into_expr(self) -> Expr {
self
}
}
impl IntoExpr for ColumnRef {
fn into_expr(self) -> Expr {
Expr::Column(self)
}
}
fn column_or_all(name: Cow<'static, str>) -> Expr {
let trimmed = name.trim();
if trimmed == "*" {
return Expr::All { table: None };
}
if let Some(table) = trimmed.strip_suffix(".*") {
return Expr::All {
table: Some(Cow::Owned(table.to_owned())),
};
}
Expr::Column(ColumnRef::parse(name))
}
pub trait IntoQuery {
fn into_query(self) -> QueryIr;
}
impl IntoQuery for QueryIr {
fn into_query(self) -> QueryIr {
self
}
}
impl<M, T> From<Column<M, T>> for Expr {
fn from(column: Column<M, T>) -> Self {
column.expr()
}
}
impl<M, T> From<&Column<M, T>> for Expr {
fn from(column: &Column<M, T>) -> Self {
column.expr()
}
}
impl<M, T> From<&Column<M, T>> for Order {
fn from(column: &Column<M, T>) -> Self {
column.asc()
}
}
impl<M, T> From<Column<M, T>> for Order {
fn from(column: Column<M, T>) -> Self {
column.asc()
}
}
impl From<&str> for Order {
fn from(column: &str) -> Self {
Order::asc(column.into_expr())
}
}