Skip to main content

ruprizzle/
filter.rs

1//! Filter algebra and constructors.
2
3use std::marker::PhantomData;
4
5use crate::compile::CompiledSql;
6use crate::json::JsonPath;
7use crate::model::Model;
8use crate::query::SelectQuery;
9use crate::value::Value;
10
11/// An injection-safe raw SQL fragment with bound parameters.
12///
13/// The literal parts are stored separately, and values are bound as
14/// parameters. Calling [`RawFragment::sql`] returns the fragment with
15/// PostgreSQL-style placeholders (`$1`, `$2`, ...).
16#[derive(Debug, Clone, PartialEq)]
17pub struct RawFragment {
18    /// Literal fragments of the SQL, between placeholders.
19    pub(crate) parts: Vec<String>,
20    /// Bound values for each placeholder.
21    pub(crate) binds: Vec<Value>,
22}
23
24impl RawFragment {
25    /// Creates a new raw fragment.
26    #[must_use]
27    pub fn new(parts: Vec<String>, binds: Vec<Value>) -> Self {
28        assert_eq!(
29            parts.len(),
30            binds.len() + 1,
31            "RawFragment parts must split the format string around each placeholder"
32        );
33        Self { parts, binds }
34    }
35
36    /// Returns the SQL fragment with `$1`, `$2`, ... placeholders.
37    #[must_use]
38    pub fn sql(&self) -> String {
39        let mut out = String::new();
40        for (i, part) in self.parts.iter().enumerate() {
41            out.push_str(part);
42            if i < self.binds.len() {
43                out.push_str(&format!("${}", i + 1));
44            }
45        }
46        out
47    }
48
49    /// Returns the bound values for this fragment.
50    #[must_use]
51    pub fn binds(&self) -> &[Value] {
52        &self.binds
53    }
54}
55
56/// A compiled `SELECT` subquery that returns a single column of type `T`.
57///
58/// It is typically produced by `SelectQuery::columns(...).into::<Subquery<T>>()`
59/// and consumed by [`Column::in_subquery`](crate::col::Column::in_subquery).
60pub struct Subquery<T> {
61    /// The compiled SQL of the subquery, including its bound values.
62    pub(crate) compiled: CompiledSql,
63    _marker: PhantomData<fn() -> T>,
64}
65
66impl<T> Clone for Subquery<T> {
67    fn clone(&self) -> Self {
68        Self {
69            compiled: self.compiled.clone(),
70            _marker: PhantomData,
71        }
72    }
73}
74
75impl<T> std::fmt::Debug for Subquery<T> {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        f.debug_struct("Subquery")
78            .field("compiled", &self.compiled)
79            .finish()
80    }
81}
82
83impl<T> PartialEq for Subquery<T> {
84    fn eq(&self, other: &Self) -> bool {
85        self.compiled == other.compiled
86    }
87}
88
89impl<'db, M, T, I> From<SelectQuery<'db, M, (T,), I>> for Subquery<T>
90where
91    M: Model,
92{
93    fn from(query: SelectQuery<'db, M, (T,), I>) -> Self {
94        Self {
95            compiled: query.to_sql().unwrap_or_else(|_| {
96                unreachable!("subquery SQL compilation is an internal invariant")
97            }),
98            _marker: PhantomData,
99        }
100    }
101}
102
103/// A compiled subquery used by `EXISTS` / `NOT EXISTS` filters.
104///
105/// Unlike [`Subquery`], `EXISTS` does not care about the projection shape,
106/// so any [`SelectQuery`] can be converted into an `ExistsSubquery`.
107pub struct ExistsSubquery {
108    pub(crate) compiled: CompiledSql,
109}
110
111impl Clone for ExistsSubquery {
112    fn clone(&self) -> Self {
113        Self {
114            compiled: self.compiled.clone(),
115        }
116    }
117}
118
119impl std::fmt::Debug for ExistsSubquery {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        f.debug_struct("ExistsSubquery")
122            .field("compiled", &self.compiled)
123            .finish()
124    }
125}
126
127impl PartialEq for ExistsSubquery {
128    fn eq(&self, other: &Self) -> bool {
129        self.compiled == other.compiled
130    }
131}
132
133impl<'db, M, Out, I> From<SelectQuery<'db, M, Out, I>> for ExistsSubquery
134where
135    M: Model,
136{
137    fn from(query: SelectQuery<'db, M, Out, I>) -> Self {
138        Self {
139            compiled: query.to_sql().unwrap_or_else(|_| {
140                unreachable!("EXISTS subquery SQL compilation is an internal invariant")
141            }),
142        }
143    }
144}
145
146/// A compiled common table expression (CTE).
147///
148/// Stored inside a [`SelectQuery`] and emitted as
149/// `WITH ... AS (...)` or `WITH RECURSIVE ... AS (...)` when the query is
150/// compiled.
151#[derive(Debug, Clone, PartialEq)]
152pub struct Cte {
153    /// The CTE name.
154    pub name: &'static str,
155    /// The compiled body.
156    pub compiled: CompiledSql,
157    /// Whether this CTE is recursive.
158    pub recursive: bool,
159}
160
161impl Cte {
162    /// Creates a new non-recursive CTE.
163    #[must_use]
164    pub fn new(name: &'static str, compiled: CompiledSql) -> Self {
165        Self {
166            name,
167            compiled,
168            recursive: false,
169        }
170    }
171}
172
173/// A compiled query that can be used as the body of a CTE.
174///
175/// This is a thin wrapper around [`CompiledSql`] so that
176/// [`SelectQuery::with`](crate::query::SelectQuery::with) and
177/// [`SelectQuery::with_recursive`](crate::query::SelectQuery::with_recursive)
178/// can accept anything that converts into it.
179#[derive(Debug, Clone, PartialEq)]
180pub struct CteQuery {
181    pub(crate) compiled: CompiledSql,
182}
183
184impl CteQuery {
185    pub(crate) fn new(compiled: CompiledSql) -> Self {
186        Self { compiled }
187    }
188}
189
190impl<'db, M, Out, I> From<SelectQuery<'db, M, Out, I>> for CteQuery
191where
192    M: Model,
193{
194    fn from(query: SelectQuery<'db, M, Out, I>) -> Self {
195        Self::new(
196            query
197                .to_sql()
198                .unwrap_or_else(|_| unreachable!("CTE SQL compilation is an internal invariant")),
199        )
200    }
201}
202
203/// A predicate that is tied to a model `M`.
204pub struct Filter<M> {
205    /// The root filter node.
206    pub node: FilterNode,
207    _marker: PhantomData<fn() -> M>,
208}
209
210impl<M> std::fmt::Debug for Filter<M> {
211    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212        f.debug_struct("Filter").field("node", &self.node).finish()
213    }
214}
215
216impl<M> Clone for Filter<M> {
217    fn clone(&self) -> Self {
218        Self {
219            node: self.node.clone(),
220            _marker: PhantomData,
221        }
222    }
223}
224
225impl<M> PartialEq for Filter<M> {
226    fn eq(&self, other: &Self) -> bool {
227        self.node == other.node
228    }
229}
230
231impl<M> Filter<M> {
232    /// Creates a new filter.
233    #[must_use]
234    pub const fn new(node: FilterNode) -> Self {
235        Self {
236            node,
237            _marker: PhantomData,
238        }
239    }
240
241    /// Combines two filters with `AND`.
242    #[must_use]
243    pub fn and(self, other: Self) -> Self {
244        Self::new(flatten_and(vec![self.node, other.node]))
245    }
246
247    /// Combines two filters with `OR`.
248    #[must_use]
249    pub fn or(self, other: Self) -> Self {
250        Self::new(flatten_or(vec![self.node, other.node]))
251    }
252
253    /// Creates a filter from a raw SQL fragment.
254    #[must_use]
255    pub fn raw(fragment: RawFragment) -> Self {
256        Self::new(FilterNode::Raw(fragment))
257    }
258
259    /// `EXISTS (subquery)`.
260    #[must_use]
261    pub fn exists(subquery: impl Into<ExistsSubquery>) -> Self {
262        Self::new(FilterNode::ExistsSubquery {
263            subquery: subquery.into().compiled,
264            negated: false,
265        })
266    }
267
268    /// `NOT EXISTS (subquery)`.
269    #[must_use]
270    pub fn not_exists(subquery: impl Into<ExistsSubquery>) -> Self {
271        Self::new(FilterNode::ExistsSubquery {
272            subquery: subquery.into().compiled,
273            negated: true,
274        })
275    }
276}
277
278impl<M> std::ops::Not for Filter<M> {
279    type Output = Self;
280
281    fn not(self) -> Self::Output {
282        Self::new(FilterNode::Not(Box::new(self.node)))
283    }
284}
285
286/// A filter node, independent of the model it operates on.
287#[derive(Debug, Clone, PartialEq)]
288#[allow(missing_docs)]
289pub enum FilterNode {
290    Cmp {
291        table: &'static str,
292        column: &'static str,
293        op: CmpOp,
294        value: Value,
295    },
296    Between {
297        table: &'static str,
298        column: &'static str,
299        lo: Value,
300        hi: Value,
301    },
302    Null {
303        table: &'static str,
304        column: &'static str,
305        negated: bool,
306    },
307    In {
308        table: &'static str,
309        column: &'static str,
310        values: Vec<Value>,
311        negated: bool,
312    },
313    /// `column [NOT] IN (subquery)`.
314    InSubquery {
315        table: &'static str,
316        column: &'static str,
317        subquery: CompiledSql,
318        negated: bool,
319    },
320    /// A comparison between two columns, used for join `ON` clauses.
321    ColumnCmp {
322        left_table: &'static str,
323        left_col: &'static str,
324        op: CmpOp,
325        right_table: &'static str,
326        right_col: &'static str,
327    },
328    /// Correlated `EXISTS (SELECT 1 FROM child_table WHERE child_fk = parent_pk AND filter)`.
329    Exists {
330        child_table: &'static str,
331        child_col: &'static str,
332        parent_table: &'static str,
333        parent_col: &'static str,
334        filter: Box<FilterNode>,
335        negated: bool,
336    },
337    /// Correlated `[NOT] EXISTS (<subquery>)`.
338    ExistsSubquery {
339        subquery: CompiledSql,
340        negated: bool,
341    },
342    And(Vec<FilterNode>),
343    Or(Vec<FilterNode>),
344    Not(Box<FilterNode>),
345    /// A raw SQL fragment with bound parameters.
346    Raw(RawFragment),
347    /// A JSON column operation.
348    Json {
349        /// The SQL table name.
350        table: &'static str,
351        /// The SQL column name.
352        column: &'static str,
353        /// The JSON path inside the column.
354        path: JsonPath,
355        /// `true` for text extraction, `false` for JSON.
356        text: bool,
357        /// The JSON-specific operator.
358        op: JsonFilterOp,
359        /// The bound value.
360        value: Value,
361    },
362    /// A scalar/enum array column operation.
363    Array {
364        /// The SQL table name.
365        table: &'static str,
366        /// The SQL column name.
367        column: &'static str,
368        /// The array-specific operator.
369        op: ArrayFilterOp,
370        /// The bound element values.
371        values: Vec<Value>,
372    },
373    /// A full-text search match operation.
374    FullTextMatch {
375        /// The SQL table name.
376        table: &'static str,
377        /// The SQL column name.
378        column: &'static str,
379        /// The text query or terms to match.
380        query: String,
381    },
382    /// A spatial / geospatial column operation.
383    Spatial {
384        /// The SQL table name.
385        table: &'static str,
386        /// The SQL column name.
387        column: &'static str,
388        /// The spatial operator.
389        op: SpatialOp,
390        /// The geometry value (WKT formatted).
391        geometry: String,
392        /// Optional distance in meters (e.g. for `WithinRadius`).
393        distance: Option<f64>,
394    },
395}
396
397/// Spatial / PostGIS filter operations.
398#[derive(Debug, Clone, Copy, PartialEq, Eq)]
399pub enum SpatialOp {
400    /// Distance between geometries is within radius (`ST_DWithin`).
401    WithinRadius,
402    /// Geometries spatially intersect (`ST_Intersects`).
403    Intersects,
404    /// Geometry A completely contains geometry B (`ST_Contains`).
405    Contains,
406    /// Geometry A is completely within geometry B (`ST_Within`).
407    Within,
408}
409
410/// JSON-specific filter operations.
411#[derive(Debug, Clone, Copy, PartialEq, Eq)]
412pub enum JsonFilterOp {
413    /// A scalar comparison (`=`, `<>`, `>`, ...).
414    Cmp(CmpOp),
415    /// JSON containment (`@>`).
416    Contains,
417    /// Top-level or nested key existence (`?`).
418    HasKey,
419}
420
421/// Array-specific filter operations.
422#[derive(Debug, Clone, Copy, PartialEq, Eq)]
423#[allow(missing_docs)]
424pub enum ArrayFilterOp {
425    /// The column contains a specific single element (`= ANY(column)` / `JSON_CONTAINS`).
426    Has,
427    /// The column contains all of the supplied values (`@>` / `JSON_CONTAINS`).
428    Contains,
429    /// The column is contained by the supplied set (`<@` / `JSON_CONTAINS` reversed).
430    ContainedBy,
431    /// The column and the supplied set share at least one element (`&&` / `JSON_OVERLAPS`).
432    Overlaps,
433    /// The array is empty (`cardinality(col) = 0` / `JSON_LENGTH(col) = 0` or NULL).
434    IsEmpty,
435    /// The array is non-empty (`cardinality(col) > 0` / `JSON_LENGTH(col) > 0`).
436    IsNotEmpty,
437}
438
439/// Comparison operators.
440#[derive(Debug, Clone, Copy, PartialEq, Eq)]
441#[allow(missing_docs)]
442pub enum CmpOp {
443    Eq,
444    Ne,
445    Gt,
446    Gte,
447    Lt,
448    Lte,
449    Like,
450    Ilike,
451}
452
453/// Combines a list of filters with `AND`.
454///
455/// `all([])` is `TRUE`.
456pub fn all<M>(filters: impl IntoIterator<Item = Filter<M>>) -> Filter<M> {
457    Filter::new(flatten_and(filters.into_iter().map(|f| f.node).collect()))
458}
459
460/// Combines a list of filters with `OR`.
461///
462/// `any([])` is `FALSE`.
463pub fn any<M>(filters: impl IntoIterator<Item = Filter<M>>) -> Filter<M> {
464    Filter::new(flatten_or(filters.into_iter().map(|f| f.node).collect()))
465}
466
467fn flatten_and(nodes: Vec<FilterNode>) -> FilterNode {
468    if nodes.is_empty() {
469        return FilterNode::And(Vec::new());
470    }
471    let mut out = Vec::with_capacity(nodes.len());
472    for node in nodes {
473        match node {
474            FilterNode::And(children) => out.extend(children),
475            other => out.push(other),
476        }
477    }
478    FilterNode::And(out)
479}
480
481fn flatten_or(nodes: Vec<FilterNode>) -> FilterNode {
482    if nodes.is_empty() {
483        return FilterNode::Or(Vec::new());
484    }
485    let mut out = Vec::with_capacity(nodes.len());
486    for node in nodes {
487        match node {
488            FilterNode::Or(children) => out.extend(children),
489            other => out.push(other),
490        }
491    }
492    FilterNode::Or(out)
493}