use std::marker::PhantomData;
use crate::compile::CompiledSql;
use crate::json::JsonPath;
use crate::model::Model;
use crate::query::SelectQuery;
use crate::value::Value;
#[derive(Debug, Clone, PartialEq)]
pub struct RawFragment {
pub(crate) parts: Vec<String>,
pub(crate) binds: Vec<Value>,
}
impl RawFragment {
#[must_use]
pub fn new(parts: Vec<String>, binds: Vec<Value>) -> Self {
assert_eq!(
parts.len(),
binds.len() + 1,
"RawFragment parts must split the format string around each placeholder"
);
Self { parts, binds }
}
#[must_use]
pub fn sql(&self) -> String {
let mut out = String::new();
for (i, part) in self.parts.iter().enumerate() {
out.push_str(part);
if i < self.binds.len() {
out.push_str(&format!("${}", i + 1));
}
}
out
}
#[must_use]
pub fn binds(&self) -> &[Value] {
&self.binds
}
}
pub struct Subquery<T> {
pub(crate) compiled: CompiledSql,
_marker: PhantomData<fn() -> T>,
}
impl<T> Clone for Subquery<T> {
fn clone(&self) -> Self {
Self {
compiled: self.compiled.clone(),
_marker: PhantomData,
}
}
}
impl<T> std::fmt::Debug for Subquery<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Subquery")
.field("compiled", &self.compiled)
.finish()
}
}
impl<T> PartialEq for Subquery<T> {
fn eq(&self, other: &Self) -> bool {
self.compiled == other.compiled
}
}
impl<'db, M, T, I> From<SelectQuery<'db, M, (T,), I>> for Subquery<T>
where
M: Model,
{
fn from(query: SelectQuery<'db, M, (T,), I>) -> Self {
Self {
compiled: query.to_sql().unwrap_or_else(|_| {
unreachable!("subquery SQL compilation is an internal invariant")
}),
_marker: PhantomData,
}
}
}
pub struct ExistsSubquery {
pub(crate) compiled: CompiledSql,
}
impl Clone for ExistsSubquery {
fn clone(&self) -> Self {
Self {
compiled: self.compiled.clone(),
}
}
}
impl std::fmt::Debug for ExistsSubquery {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ExistsSubquery")
.field("compiled", &self.compiled)
.finish()
}
}
impl PartialEq for ExistsSubquery {
fn eq(&self, other: &Self) -> bool {
self.compiled == other.compiled
}
}
impl<'db, M, Out, I> From<SelectQuery<'db, M, Out, I>> for ExistsSubquery
where
M: Model,
{
fn from(query: SelectQuery<'db, M, Out, I>) -> Self {
Self {
compiled: query.to_sql().unwrap_or_else(|_| {
unreachable!("EXISTS subquery SQL compilation is an internal invariant")
}),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Cte {
pub name: &'static str,
pub compiled: CompiledSql,
pub recursive: bool,
}
impl Cte {
#[must_use]
pub fn new(name: &'static str, compiled: CompiledSql) -> Self {
Self {
name,
compiled,
recursive: false,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct CteQuery {
pub(crate) compiled: CompiledSql,
}
impl CteQuery {
pub(crate) fn new(compiled: CompiledSql) -> Self {
Self { compiled }
}
}
impl<'db, M, Out, I> From<SelectQuery<'db, M, Out, I>> for CteQuery
where
M: Model,
{
fn from(query: SelectQuery<'db, M, Out, I>) -> Self {
Self::new(
query
.to_sql()
.unwrap_or_else(|_| unreachable!("CTE SQL compilation is an internal invariant")),
)
}
}
pub struct Filter<M> {
pub node: FilterNode,
_marker: PhantomData<fn() -> M>,
}
impl<M> std::fmt::Debug for Filter<M> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Filter").field("node", &self.node).finish()
}
}
impl<M> Clone for Filter<M> {
fn clone(&self) -> Self {
Self {
node: self.node.clone(),
_marker: PhantomData,
}
}
}
impl<M> PartialEq for Filter<M> {
fn eq(&self, other: &Self) -> bool {
self.node == other.node
}
}
impl<M> Filter<M> {
#[must_use]
pub const fn new(node: FilterNode) -> Self {
Self {
node,
_marker: PhantomData,
}
}
#[must_use]
pub fn and(self, other: Self) -> Self {
Self::new(flatten_and(vec![self.node, other.node]))
}
#[must_use]
pub fn or(self, other: Self) -> Self {
Self::new(flatten_or(vec![self.node, other.node]))
}
#[must_use]
pub fn raw(fragment: RawFragment) -> Self {
Self::new(FilterNode::Raw(fragment))
}
#[must_use]
pub fn exists(subquery: impl Into<ExistsSubquery>) -> Self {
Self::new(FilterNode::ExistsSubquery {
subquery: subquery.into().compiled,
negated: false,
})
}
#[must_use]
pub fn not_exists(subquery: impl Into<ExistsSubquery>) -> Self {
Self::new(FilterNode::ExistsSubquery {
subquery: subquery.into().compiled,
negated: true,
})
}
}
impl<M> std::ops::Not for Filter<M> {
type Output = Self;
fn not(self) -> Self::Output {
Self::new(FilterNode::Not(Box::new(self.node)))
}
}
#[derive(Debug, Clone, PartialEq)]
#[allow(missing_docs)]
pub enum FilterNode {
Cmp {
table: &'static str,
column: &'static str,
op: CmpOp,
value: Value,
},
Between {
table: &'static str,
column: &'static str,
lo: Value,
hi: Value,
},
Null {
table: &'static str,
column: &'static str,
negated: bool,
},
In {
table: &'static str,
column: &'static str,
values: Vec<Value>,
negated: bool,
},
InSubquery {
table: &'static str,
column: &'static str,
subquery: CompiledSql,
negated: bool,
},
ColumnCmp {
left_table: &'static str,
left_col: &'static str,
op: CmpOp,
right_table: &'static str,
right_col: &'static str,
},
Exists {
child_table: &'static str,
child_col: &'static str,
parent_table: &'static str,
parent_col: &'static str,
filter: Box<FilterNode>,
negated: bool,
},
ExistsSubquery {
subquery: CompiledSql,
negated: bool,
},
And(Vec<FilterNode>),
Or(Vec<FilterNode>),
Not(Box<FilterNode>),
Raw(RawFragment),
Json {
table: &'static str,
column: &'static str,
path: JsonPath,
text: bool,
op: JsonFilterOp,
value: Value,
},
Array {
table: &'static str,
column: &'static str,
op: ArrayFilterOp,
values: Vec<Value>,
},
FullTextMatch {
table: &'static str,
column: &'static str,
query: String,
},
Spatial {
table: &'static str,
column: &'static str,
op: SpatialOp,
geometry: String,
distance: Option<f64>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpatialOp {
WithinRadius,
Intersects,
Contains,
Within,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JsonFilterOp {
Cmp(CmpOp),
Contains,
HasKey,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum ArrayFilterOp {
Has,
Contains,
ContainedBy,
Overlaps,
IsEmpty,
IsNotEmpty,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum CmpOp {
Eq,
Ne,
Gt,
Gte,
Lt,
Lte,
Like,
Ilike,
}
pub fn all<M>(filters: impl IntoIterator<Item = Filter<M>>) -> Filter<M> {
Filter::new(flatten_and(filters.into_iter().map(|f| f.node).collect()))
}
pub fn any<M>(filters: impl IntoIterator<Item = Filter<M>>) -> Filter<M> {
Filter::new(flatten_or(filters.into_iter().map(|f| f.node).collect()))
}
fn flatten_and(nodes: Vec<FilterNode>) -> FilterNode {
if nodes.is_empty() {
return FilterNode::And(Vec::new());
}
let mut out = Vec::with_capacity(nodes.len());
for node in nodes {
match node {
FilterNode::And(children) => out.extend(children),
other => out.push(other),
}
}
FilterNode::And(out)
}
fn flatten_or(nodes: Vec<FilterNode>) -> FilterNode {
if nodes.is_empty() {
return FilterNode::Or(Vec::new());
}
let mut out = Vec::with_capacity(nodes.len());
for node in nodes {
match node {
FilterNode::Or(children) => out.extend(children),
other => out.push(other),
}
}
FilterNode::Or(out)
}