use std::borrow::Cow;
use std::fmt;
use crate::value::Value;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ColumnRef {
pub table: Option<Cow<'static, str>>,
pub name: Cow<'static, str>,
pub path: Vec<JsonSegment>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum JsonSegment {
Key(String),
Index(i64),
}
impl ColumnRef {
pub fn new(
table: Option<impl Into<Cow<'static, str>>>,
name: impl Into<Cow<'static, str>>,
) -> Self {
ColumnRef {
table: table.map(Into::into),
name: name.into(),
path: Vec::new(),
}
}
pub fn parse(text: impl Into<Cow<'static, str>>) -> Self {
let text = text.into();
let (head, path) = match text.split_once("->") {
Some((head, rest)) => (head.to_owned(), parse_json_path(rest)),
None if text.trim_end().ends_with(']') && text.contains('[') => {
(text.to_string(), Vec::new())
}
None => {
return Self::parse_head(text);
}
};
let (head, mut indexes) = match head.find('[') {
Some(at) if head.trim_end().ends_with(']') => {
(head[..at].to_owned(), parse_json_path(&head[at..]))
}
_ => (head, Vec::new()),
};
let mut column = Self::parse_head(Cow::Owned(head));
indexes.extend(path);
column.path = indexes;
column
}
fn parse_head(head: Cow<'static, str>) -> Self {
match head.rsplit_once('.') {
Some((table, name)) => ColumnRef {
table: Some(Cow::Owned(table.trim().to_owned())),
name: Cow::Owned(name.trim().to_owned()),
path: Vec::new(),
},
None => ColumnRef {
table: None,
name: match head {
Cow::Borrowed(name) => Cow::Borrowed(name.trim()),
Cow::Owned(name) => Cow::Owned(name.trim().to_owned()),
},
path: Vec::new(),
},
}
}
pub fn without_path(&self) -> Self {
ColumnRef {
table: self.table.clone(),
name: self.name.clone(),
path: Vec::new(),
}
}
}
fn parse_json_path(path: &str) -> Vec<JsonSegment> {
let mut segments = Vec::new();
for part in path.split("->") {
let part = part.trim().trim_matches(|c| c == '\'' || c == '"');
let (key, indexes) = match part.find('[') {
Some(at) if part.ends_with(']') => (&part[..at], &part[at..]),
_ => (part, ""),
};
if !key.is_empty() {
match key.parse::<i64>() {
Ok(index) => segments.push(JsonSegment::Index(index)),
Err(_) => segments.push(JsonSegment::Key(key.to_owned())),
}
}
for index in indexes.split(['[', ']']).filter(|piece| !piece.is_empty()) {
match index.trim().parse::<i64>() {
Ok(index) => segments.push(JsonSegment::Index(index)),
Err(_) => segments.push(JsonSegment::Key(index.to_owned())),
}
}
}
segments
}
impl fmt::Display for ColumnRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(table) = &self.table {
write!(f, "{table}.")?;
}
f.write_str(&self.name)?;
for segment in &self.path {
match segment {
JsonSegment::Key(key) => write!(f, "->{key}")?,
JsonSegment::Index(index) => write!(f, "->{index}")?,
}
}
Ok(())
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Expr {
Column(ColumnRef),
Value(Value),
Raw {
sql: Cow<'static, str>,
values: Vec<Value>,
},
Function {
name: Cow<'static, str>,
args: Vec<Expr>,
},
Aggregate {
function: AggregateFunction,
arg: Option<Box<Expr>>,
distinct: bool,
},
Arithmetic {
left: Box<Expr>,
op: ArithmeticOp,
right: Box<Expr>,
},
Subquery(Box<QueryIr>),
TimeBucket {
width: String,
expr: Box<Expr>,
origin: Option<Box<Expr>>,
},
First {
value: Box<Expr>,
time: Box<Expr>,
},
Last {
value: Box<Expr>,
time: Box<Expr>,
},
All {
table: Option<Cow<'static, str>>,
},
Exists(Box<QueryIr>),
RowNumber {
partition: Vec<Expr>,
order: Vec<Order>,
},
Excluded {
column: Cow<'static, str>,
},
Binary {
left: Box<Expr>,
op: Cow<'static, str>,
right: Box<Expr>,
},
VectorDistance {
expr: Box<Expr>,
vector: Vec<f32>,
metric: VectorMetric,
},
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum VectorMetric {
#[default]
Cosine,
Euclidean,
InnerProduct,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AggregateFunction {
Count,
Sum,
Avg,
Min,
Max,
}
impl AggregateFunction {
pub fn sql_name(self) -> &'static str {
match self {
AggregateFunction::Count => "COUNT",
AggregateFunction::Sum => "SUM",
AggregateFunction::Avg => "AVG",
AggregateFunction::Min => "MIN",
AggregateFunction::Max => "MAX",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ArithmeticOp {
Add,
Sub,
Mul,
Div,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Operator {
Eq,
Ne,
Lt,
Lte,
Gt,
Gte,
Like,
NotLike,
ILike,
NotILike,
NullSafeEq,
BitAnd,
BitOr,
BitXor,
ShiftLeft,
ShiftRight,
Regexp,
NotRegexp,
RegexpIgnoreCase,
NotRegexpIgnoreCase,
NullSafeNe,
Postgres(&'static str),
Raw(String),
Invalid(String),
}
const POSTGRES_OPERATORS: [&str; 13] = [
"~*",
"!~*",
"~",
"!~",
"similar to",
"not similar to",
"@>",
"<@",
"?",
"?|",
"?&",
"&&",
"||",
];
impl From<&str> for Operator {
fn from(text: &str) -> Self {
let normalized = text
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.to_lowercase();
match normalized.as_str() {
"=" | "==" => Operator::Eq,
"!=" | "<>" => Operator::Ne,
"<" => Operator::Lt,
"<=" => Operator::Lte,
">" => Operator::Gt,
">=" => Operator::Gte,
"like" => Operator::Like,
"not like" => Operator::NotLike,
"ilike" => Operator::ILike,
"not ilike" => Operator::NotILike,
"<=>" | "is not distinct from" => Operator::NullSafeEq,
"is distinct from" => Operator::NullSafeNe,
"&" => Operator::BitAnd,
"|" => Operator::BitOr,
"^" => Operator::BitXor,
"<<" => Operator::ShiftLeft,
">>" => Operator::ShiftRight,
"regexp" | "rlike" => Operator::Regexp,
"not regexp" | "not rlike" => Operator::NotRegexp,
other => match POSTGRES_OPERATORS.iter().find(|op| **op == other) {
Some(op) => Operator::Postgres(op),
None => Operator::Invalid(text.to_owned()),
},
}
}
}
impl From<String> for Operator {
fn from(text: String) -> Self {
Operator::from(text.as_str())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DatePart {
Date,
Time,
Day,
Month,
Year,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Boolean {
And,
Or,
}
#[derive(Clone, Debug)]
pub struct WhereClause {
pub boolean: Boolean,
pub negated: bool,
pub filter: Where,
}
impl WhereClause {
pub fn and(filter: Where) -> Self {
WhereClause {
boolean: Boolean::And,
negated: false,
filter,
}
}
pub fn or(filter: Where) -> Self {
WhereClause {
boolean: Boolean::Or,
negated: false,
filter,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Where {
Compare {
left: Expr,
op: Operator,
right: Expr,
},
Null {
expr: Expr,
not: bool,
},
In {
expr: Expr,
values: InValues,
not: bool,
},
Between {
expr: Expr,
low: Expr,
high: Expr,
not: bool,
},
Like {
expr: Expr,
pattern: Expr,
case_sensitive: bool,
not: bool,
},
IgnoreCase {
expr: Expr,
text: String,
mode: IgnoreCaseMode,
},
DatePart {
part: DatePart,
expr: Expr,
op: Operator,
value: Expr,
},
Exists {
query: Box<QueryIr>,
not: bool,
},
Group(Vec<WhereClause>),
JsonContains {
column: ColumnRef,
value: serde_json::Value,
not: bool,
},
JsonContainedBy {
column: ColumnRef,
value: serde_json::Value,
not: bool,
},
JsonOverlaps {
column: ColumnRef,
value: serde_json::Value,
not: bool,
},
JsonContainsKey {
column: ColumnRef,
not: bool,
},
JsonLength {
column: ColumnRef,
op: Operator,
length: i64,
},
FullText {
columns: Vec<Expr>,
query: String,
options: FullText,
},
Raw {
sql: Cow<'static, str>,
values: Vec<Value>,
},
Tree(Box<crate::render::ast::Expr>),
Native(NativeFilter),
Invalid(String),
}
#[derive(Clone)]
pub struct NativeFilter {
driver: &'static str,
value: std::sync::Arc<dyn NativeValue>,
}
trait NativeValue: std::any::Any + fmt::Debug + Send + Sync {
fn as_any(&self) -> &dyn std::any::Any;
}
impl<T: std::any::Any + fmt::Debug + Send + Sync> NativeValue for T {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
impl NativeFilter {
pub fn new<T: std::any::Any + fmt::Debug + Send + Sync>(
driver: &'static str,
value: T,
) -> Self {
NativeFilter {
driver,
value: std::sync::Arc::new(value),
}
}
pub fn driver(&self) -> &'static str {
self.driver
}
pub fn downcast_ref<T: std::any::Any>(&self) -> Option<&T> {
let value: &dyn NativeValue = &*self.value;
value.as_any().downcast_ref::<T>()
}
}
impl fmt::Debug for NativeFilter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "NativeFilter({}: {:?})", self.driver, self.value)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum IgnoreCaseMode {
Contains,
Equals,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FullTextMode {
#[default]
Natural,
Phrase,
Websearch,
Boolean,
Raw,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct FullText {
pub mode: FullTextMode,
pub language: Option<String>,
pub expanded: bool,
pub vectors: bool,
}
impl FullText {
pub fn english() -> Self {
FullText::default().language("english")
}
pub fn raw() -> Self {
FullText {
mode: FullTextMode::Raw,
..FullText::default()
}
}
pub fn vectors(mut self) -> Self {
self.vectors = true;
self
}
pub fn websearch_mode(mut self) -> Self {
self.mode = FullTextMode::Websearch;
self
}
pub fn phrase_mode(mut self) -> Self {
self.mode = FullTextMode::Phrase;
self
}
pub fn phrase() -> Self {
FullText {
mode: FullTextMode::Phrase,
..FullText::default()
}
}
pub fn websearch() -> Self {
FullText {
mode: FullTextMode::Websearch,
..FullText::default()
}
}
pub fn boolean() -> Self {
FullText {
mode: FullTextMode::Boolean,
..FullText::default()
}
}
pub fn language(mut self, language: impl Into<String>) -> Self {
self.language = Some(language.into());
self
}
pub fn expanded(mut self) -> Self {
self.expanded = true;
self
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum InValues {
List(Vec<Expr>),
Subquery(Box<QueryIr>),
}
#[derive(Clone, Debug)]
pub struct TableRef {
pub name: Cow<'static, str>,
pub alias: Option<Cow<'static, str>>,
pub subquery: Option<Box<QueryIr>>,
pub function: Option<Box<Expr>>,
}
impl TableRef {
pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
TableRef {
name: name.into(),
alias: None,
subquery: None,
function: None,
}
}
pub fn aliased(
name: impl Into<Cow<'static, str>>,
alias: impl Into<Cow<'static, str>>,
) -> Self {
TableRef {
name: name.into(),
alias: Some(alias.into()),
subquery: None,
function: None,
}
}
pub fn subquery(query: QueryIr, alias: impl Into<Cow<'static, str>>) -> Self {
let alias = alias.into();
TableRef {
name: alias.clone(),
alias: Some(alias),
subquery: Some(Box::new(query)),
function: None,
}
}
pub fn function(call: Expr, alias: impl Into<Cow<'static, str>>) -> Self {
let alias = alias.into();
TableRef {
name: alias.clone(),
alias: Some(alias),
subquery: None,
function: Some(Box::new(call)),
}
}
pub fn qualifier(&self) -> &str {
self.alias.as_deref().unwrap_or(&self.name)
}
}
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub enum Distinct {
#[default]
No,
Yes,
On(Vec<Expr>),
}
#[derive(Clone, Debug)]
pub struct SelectItem {
pub expr: Expr,
pub alias: Option<Cow<'static, str>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum JoinKind {
Inner,
Left,
Right,
Cross,
Lateral,
LeftLateral,
}
#[derive(Clone, Debug)]
pub struct GroupLimit {
pub limit: u64,
pub column: Expr,
}
#[derive(Clone, Debug)]
pub struct Join {
pub kind: JoinKind,
pub table: TableRef,
pub on: Vec<WhereClause>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Direction {
Asc,
Desc,
}
impl Direction {
pub fn reversed(self) -> Self {
match self {
Direction::Asc => Direction::Desc,
Direction::Desc => Direction::Asc,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Nulls {
First,
Last,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Order {
By {
expr: Expr,
direction: Direction,
nulls: Option<Nulls>,
},
Random,
Raw {
sql: Cow<'static, str>,
values: Vec<Value>,
},
}
impl Order {
pub fn raw(
sql: impl Into<Cow<'static, str>>,
values: impl IntoIterator<Item = impl Into<Value>>,
) -> Self {
Order::Raw {
sql: sql.into(),
values: values.into_iter().map(Into::into).collect(),
}
}
pub fn asc(expr: impl Into<Expr>) -> Self {
Order::By {
expr: expr.into(),
direction: Direction::Asc,
nulls: None,
}
}
pub fn desc(expr: impl Into<Expr>) -> Self {
Order::By {
expr: expr.into(),
direction: Direction::Desc,
nulls: None,
}
}
pub fn nulls_first(self) -> Self {
self.with_nulls(Nulls::First)
}
pub fn nulls_last(self) -> Self {
self.with_nulls(Nulls::Last)
}
fn with_nulls(self, which: Nulls) -> Self {
match self {
Order::By {
expr, direction, ..
} => Order::By {
expr,
direction,
nulls: Some(which),
},
other => other,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Lock {
pub mode: LockMode,
pub wait: LockWait,
}
impl Lock {
pub const fn new(mode: LockMode) -> Self {
Lock {
mode,
wait: LockWait::Wait,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LockMode {
Update,
NoKeyUpdate,
Share,
KeyShare,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LockWait {
#[default]
Wait,
NoWait,
SkipLocked,
}
#[derive(Clone, Debug)]
pub struct Union {
pub query: Box<QueryIr>,
pub all: bool,
}
#[derive(Clone, Debug)]
pub struct Aggregate {
pub function: AggregateFunction,
pub arg: Option<Expr>,
pub distinct: bool,
}
#[derive(Clone, Debug)]
pub struct QueryIr {
pub table: TableRef,
pub distinct: Distinct,
pub columns: Vec<SelectItem>,
pub joins: Vec<Join>,
pub wheres: Vec<WhereClause>,
pub groups: Vec<Expr>,
pub havings: Vec<WhereClause>,
pub orders: Vec<Order>,
pub limit: Option<u64>,
pub offset: Option<u64>,
pub lock: Option<Lock>,
pub unions: Vec<Union>,
pub group_limit: Option<GroupLimit>,
pub connection: Option<Cow<'static, str>>,
pub use_writer: bool,
pub timeout: Option<std::time::Duration>,
pub errors: Vec<String>,
}
impl QueryIr {
pub fn new(table: impl Into<Cow<'static, str>>) -> Self {
QueryIr {
table: TableRef::new(table),
distinct: Distinct::No,
columns: Vec::new(),
joins: Vec::new(),
wheres: Vec::new(),
groups: Vec::new(),
havings: Vec::new(),
orders: Vec::new(),
limit: None,
offset: None,
lock: None,
unions: Vec::new(),
group_limit: None,
connection: None,
use_writer: false,
timeout: None,
errors: Vec::new(),
}
}
pub fn route(&self, model: Option<&'static str>) -> crate::Route<'_> {
crate::Route::new()
.on(self.connection.as_deref())
.for_model(model)
.writer(self.use_writer)
}
pub fn check(&self) -> Result<(), crate::OrmError> {
match self.errors.first() {
Some(error) => Err(crate::OrmError::invalid(error.clone())),
None => Ok(()),
}
}
}
#[derive(Clone, Debug)]
pub struct InsertIr {
pub table: Cow<'static, str>,
pub columns: Vec<Cow<'static, str>>,
pub rows: Vec<Vec<Expr>>,
pub returning: Vec<Cow<'static, str>>,
pub select: Option<Box<QueryIr>>,
pub on_conflict: Option<OnConflict>,
}
impl InsertIr {
pub fn new(
table: impl Into<Cow<'static, str>>,
columns: Vec<Cow<'static, str>>,
rows: Vec<Vec<Expr>>,
) -> Self {
InsertIr {
table: table.into(),
columns,
rows,
returning: Vec::new(),
select: None,
on_conflict: None,
}
}
pub fn returning(mut self, columns: Vec<Cow<'static, str>>) -> Self {
self.returning = columns;
self
}
pub fn on_conflict(mut self, on_conflict: OnConflict) -> Self {
self.on_conflict = Some(on_conflict);
self
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum OnConflict {
Ignore {
target: Vec<Cow<'static, str>>,
},
Update {
target: Vec<Cow<'static, str>>,
sets: Vec<(Cow<'static, str>, Expr)>,
},
}
#[derive(Clone, Debug)]
pub struct UpdateIr {
pub table: TableRef,
pub sets: Vec<(Cow<'static, str>, Expr)>,
pub wheres: Vec<WhereClause>,
}
#[derive(Clone, Debug)]
pub struct DeleteIr {
pub table: TableRef,
pub wheres: Vec<WhereClause>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn column_refs_parse_tables_and_json_paths() {
assert_eq!(
ColumnRef::parse("title"),
ColumnRef::new(None::<&str>, "title")
);
assert_eq!(
ColumnRef::parse("deals.title"),
ColumnRef::new(Some("deals"), "title")
);
let column = ColumnRef::parse("meta->a->0->b");
assert_eq!(
column.path,
[
JsonSegment::Key("a".into()),
JsonSegment::Index(0),
JsonSegment::Key("b".into())
]
);
let indexed = ColumnRef::parse("deals.tags[1]");
assert_eq!(
(indexed.table.as_deref(), indexed.name.as_ref()),
(Some("deals"), "tags")
);
assert_eq!(indexed.path, [JsonSegment::Index(1)]);
let nested = ColumnRef::parse("tags[-1]->name");
assert_eq!(
nested.path,
[JsonSegment::Index(-1), JsonSegment::Key("name".into())]
);
assert_eq!(column.to_string(), "meta->a->0->b");
assert_eq!(column.without_path().to_string(), "meta");
}
#[test]
fn operators_parse_case_and_whitespace_insensitively() {
assert_eq!(Operator::from(" not LIKE "), Operator::NotLike);
assert_eq!(Operator::from("@>"), Operator::Postgres("@>"));
assert_eq!(Operator::from("rlike"), Operator::Regexp);
assert_eq!(Operator::from("bogus"), Operator::Invalid("bogus".into()));
}
}