1use 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#[derive(Debug, Clone, PartialEq)]
17pub struct RawFragment {
18 pub(crate) parts: Vec<String>,
20 pub(crate) binds: Vec<Value>,
22}
23
24impl RawFragment {
25 #[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 #[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 #[must_use]
51 pub fn binds(&self) -> &[Value] {
52 &self.binds
53 }
54}
55
56pub struct Subquery<T> {
61 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
103pub 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#[derive(Debug, Clone, PartialEq)]
152pub struct Cte {
153 pub name: &'static str,
155 pub compiled: CompiledSql,
157 pub recursive: bool,
159}
160
161impl Cte {
162 #[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#[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
203pub struct Filter<M> {
205 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 #[must_use]
234 pub const fn new(node: FilterNode) -> Self {
235 Self {
236 node,
237 _marker: PhantomData,
238 }
239 }
240
241 #[must_use]
243 pub fn and(self, other: Self) -> Self {
244 Self::new(flatten_and(vec![self.node, other.node]))
245 }
246
247 #[must_use]
249 pub fn or(self, other: Self) -> Self {
250 Self::new(flatten_or(vec![self.node, other.node]))
251 }
252
253 #[must_use]
255 pub fn raw(fragment: RawFragment) -> Self {
256 Self::new(FilterNode::Raw(fragment))
257 }
258
259 #[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 #[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#[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 InSubquery {
315 table: &'static str,
316 column: &'static str,
317 subquery: CompiledSql,
318 negated: bool,
319 },
320 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 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 ExistsSubquery {
339 subquery: CompiledSql,
340 negated: bool,
341 },
342 And(Vec<FilterNode>),
343 Or(Vec<FilterNode>),
344 Not(Box<FilterNode>),
345 Raw(RawFragment),
347 Json {
349 table: &'static str,
351 column: &'static str,
353 path: JsonPath,
355 text: bool,
357 op: JsonFilterOp,
359 value: Value,
361 },
362 Array {
364 table: &'static str,
366 column: &'static str,
368 op: ArrayFilterOp,
370 values: Vec<Value>,
372 },
373 FullTextMatch {
375 table: &'static str,
377 column: &'static str,
379 query: String,
381 },
382 Spatial {
384 table: &'static str,
386 column: &'static str,
388 op: SpatialOp,
390 geometry: String,
392 distance: Option<f64>,
394 },
395}
396
397#[derive(Debug, Clone, Copy, PartialEq, Eq)]
399pub enum SpatialOp {
400 WithinRadius,
402 Intersects,
404 Contains,
406 Within,
408}
409
410#[derive(Debug, Clone, Copy, PartialEq, Eq)]
412pub enum JsonFilterOp {
413 Cmp(CmpOp),
415 Contains,
417 HasKey,
419}
420
421#[derive(Debug, Clone, Copy, PartialEq, Eq)]
423#[allow(missing_docs)]
424pub enum ArrayFilterOp {
425 Has,
427 Contains,
429 ContainedBy,
431 Overlaps,
433 IsEmpty,
435 IsNotEmpty,
437}
438
439#[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
453pub 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
460pub 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}