Skip to main content

dbkit_core/
expr.rs

1use std::marker::PhantomData;
2use std::ops::{Add, Mul, Sub};
3
4use crate::compile::CompiledSql;
5use crate::schema::{Column, ColumnRef};
6use crate::types::{PgInterval, PgVector};
7
8#[derive(Debug, Clone, PartialEq)]
9pub enum Value {
10    Null,
11    Bool(bool),
12    I16(i16),
13    I32(i32),
14    I64(i64),
15    F32(f32),
16    F64(f64),
17    String(String),
18    Array(Vec<String>),
19    Json(serde_json::Value),
20    Uuid(uuid::Uuid),
21    DateTime(chrono::NaiveDateTime),
22    DateTimeUtc(chrono::DateTime<chrono::Utc>),
23    Date(chrono::NaiveDate),
24    Time(chrono::NaiveTime),
25    Interval(PgInterval),
26    Vector(Vec<f32>),
27    Enum { type_name: &'static str, value: String },
28}
29
30pub trait ColumnValue<T> {
31    fn into_value(self) -> Option<Value>;
32}
33
34impl<T> ColumnValue<T> for T
35where
36    T: Into<Value>,
37{
38    fn into_value(self) -> Option<Value> {
39        Some(self.into())
40    }
41}
42
43impl<T> ColumnValue<T> for Option<T>
44where
45    T: Into<Value>,
46{
47    fn into_value(self) -> Option<Value> {
48        self.map(Into::into)
49    }
50}
51
52impl ColumnValue<String> for &str {
53    fn into_value(self) -> Option<Value> {
54        Some(Value::String(self.to_string()))
55    }
56}
57
58impl<T> ColumnValue<T> for &T
59where
60    T: Clone + Into<Value>,
61{
62    fn into_value(self) -> Option<Value> {
63        Some(self.clone().into())
64    }
65}
66
67impl<T> ColumnValue<Option<T>> for T
68where
69    T: Into<Value>,
70{
71    fn into_value(self) -> Option<Value> {
72        Some(self.into())
73    }
74}
75
76impl<T> ColumnValue<Option<T>> for &T
77where
78    T: Clone + Into<Value>,
79{
80    fn into_value(self) -> Option<Value> {
81        Some(self.clone().into())
82    }
83}
84
85impl ColumnValue<Option<String>> for &str {
86    fn into_value(self) -> Option<Value> {
87        Some(Value::String(self.to_string()))
88    }
89}
90
91impl From<bool> for Value {
92    fn from(value: bool) -> Self {
93        Self::Bool(value)
94    }
95}
96
97impl From<i16> for Value {
98    fn from(value: i16) -> Self {
99        Self::I16(value)
100    }
101}
102
103impl From<i32> for Value {
104    fn from(value: i32) -> Self {
105        Self::I32(value)
106    }
107}
108
109impl From<i64> for Value {
110    fn from(value: i64) -> Self {
111        Self::I64(value)
112    }
113}
114
115impl From<f32> for Value {
116    fn from(value: f32) -> Self {
117        Self::F32(value)
118    }
119}
120
121impl From<f64> for Value {
122    fn from(value: f64) -> Self {
123        Self::F64(value)
124    }
125}
126
127impl From<String> for Value {
128    fn from(value: String) -> Self {
129        Self::String(value)
130    }
131}
132
133impl From<&str> for Value {
134    fn from(value: &str) -> Self {
135        Self::String(value.to_string())
136    }
137}
138
139impl From<Vec<String>> for Value {
140    fn from(value: Vec<String>) -> Self {
141        Self::Array(value)
142    }
143}
144
145impl From<serde_json::Value> for Value {
146    fn from(value: serde_json::Value) -> Self {
147        Self::Json(value)
148    }
149}
150
151impl From<uuid::Uuid> for Value {
152    fn from(value: uuid::Uuid) -> Self {
153        Self::Uuid(value)
154    }
155}
156
157impl From<chrono::NaiveDateTime> for Value {
158    fn from(value: chrono::NaiveDateTime) -> Self {
159        Self::DateTime(value)
160    }
161}
162
163impl From<chrono::DateTime<chrono::Utc>> for Value {
164    fn from(value: chrono::DateTime<chrono::Utc>) -> Self {
165        Self::DateTimeUtc(value)
166    }
167}
168
169impl From<chrono::NaiveDate> for Value {
170    fn from(value: chrono::NaiveDate) -> Self {
171        Self::Date(value)
172    }
173}
174
175impl From<chrono::NaiveTime> for Value {
176    fn from(value: chrono::NaiveTime) -> Self {
177        Self::Time(value)
178    }
179}
180
181impl From<PgInterval> for Value {
182    fn from(value: PgInterval) -> Self {
183        Self::Interval(value)
184    }
185}
186
187impl<const N: usize> From<PgVector<N>> for Value {
188    fn from(value: PgVector<N>) -> Self {
189        Self::Vector(value.to_vec())
190    }
191}
192
193impl<T> From<Option<T>> for Value
194where
195    T: Into<Value>,
196{
197    fn from(value: Option<T>) -> Self {
198        match value {
199            Some(v) => v.into(),
200            None => Self::Null,
201        }
202    }
203}
204
205#[derive(Debug, Clone, Copy)]
206pub enum BinaryOp {
207    Add,
208    Sub,
209    Mul,
210    Eq,
211    Ne,
212    IsDistinctFrom,
213    IsNotDistinctFrom,
214    Lt,
215    Le,
216    Gt,
217    Ge,
218}
219
220#[derive(Debug, Clone, Copy)]
221pub enum BoolOp {
222    And,
223    Or,
224}
225
226#[derive(Debug, Clone, Copy)]
227pub enum UnaryOp {
228    Not,
229}
230
231#[derive(Debug, Clone, Copy)]
232pub enum VectorBinaryOp {
233    L2Distance,
234    CosineDistance,
235    InnerProductDistance,
236    L1Distance,
237}
238
239#[derive(Debug, Clone, Copy)]
240pub enum IntervalField {
241    Days,
242    Hours,
243    Minutes,
244    Seconds,
245}
246
247#[derive(Debug, Clone)]
248pub enum ExprNode {
249    Column(ColumnRef),
250    Value(Value),
251    Row {
252        values: Vec<ExprNode>,
253    },
254    Func {
255        name: &'static str,
256        args: Vec<ExprNode>,
257    },
258    VectorBinary {
259        left: Box<ExprNode>,
260        op: VectorBinaryOp,
261        right: Box<ExprNode>,
262    },
263    MakeInterval {
264        field: IntervalField,
265        value: Box<ExprNode>,
266    },
267    Binary {
268        left: Box<ExprNode>,
269        op: BinaryOp,
270        right: Box<ExprNode>,
271    },
272    Bool {
273        left: Box<ExprNode>,
274        op: BoolOp,
275        right: Box<ExprNode>,
276    },
277    Unary {
278        op: UnaryOp,
279        expr: Box<ExprNode>,
280    },
281    In {
282        expr: Box<ExprNode>,
283        values: Vec<Value>,
284    },
285    RowIn {
286        expr: Box<ExprNode>,
287        rows: Vec<Vec<Value>>,
288    },
289    IsNull {
290        expr: Box<ExprNode>,
291        negated: bool,
292    },
293    Like {
294        expr: Box<ExprNode>,
295        pattern: Value,
296        case_insensitive: bool,
297    },
298    Exists {
299        subquery: CompiledSql,
300    },
301}
302
303#[derive(Debug, Clone)]
304pub struct Expr<T> {
305    pub node: ExprNode,
306    _marker: PhantomData<T>,
307}
308
309#[derive(Debug, Clone)]
310pub struct RowExpr<T> {
311    node: ExprNode,
312    _marker: PhantomData<T>,
313}
314
315impl<T> Expr<T> {
316    pub fn new(node: ExprNode) -> Self {
317        Self {
318            node,
319            _marker: PhantomData,
320        }
321    }
322}
323
324impl<T> RowExpr<T> {
325    pub fn new(node: ExprNode) -> Self {
326        Self {
327            node,
328            _marker: PhantomData,
329        }
330    }
331}
332
333pub trait IntoExpr<T> {
334    fn into_expr(self) -> Expr<T>;
335}
336
337pub trait ExprOperand {
338    type Value;
339
340    fn into_operand_expr(self) -> Expr<Self::Value>;
341}
342
343#[doc(hidden)]
344pub struct ValueComparisonMarker;
345
346#[doc(hidden)]
347pub struct ExprComparisonMarker;
348
349pub trait ComparisonValue<T, Marker = ValueComparisonMarker> {
350    fn into_comparison_expr(self) -> Expr<T>;
351}
352
353pub trait SqlAdd<Rhs> {
354    type Output;
355}
356
357pub trait SqlSub<Rhs> {
358    type Output;
359}
360
361pub trait SqlMul<Rhs> {
362    type Output;
363}
364
365pub trait NumericExprType {}
366
367mod row_columns_private {
368    pub trait Sealed {}
369}
370
371pub trait RowColumns: row_columns_private::Sealed {
372    type ValueTuple;
373
374    fn into_row_expr(self) -> RowExpr<Self::ValueTuple>;
375}
376
377pub fn row<R>(columns: R) -> RowExpr<R::ValueTuple>
378where
379    R: RowColumns,
380{
381    columns.into_row_expr()
382}
383
384impl<T> IntoExpr<T> for Expr<T> {
385    fn into_expr(self) -> Expr<T> {
386        self
387    }
388}
389
390impl<T> ExprOperand for Expr<T> {
391    type Value = T;
392
393    fn into_operand_expr(self) -> Expr<Self::Value> {
394        self
395    }
396}
397
398impl<T> ComparisonValue<T, ExprComparisonMarker> for Expr<T> {
399    fn into_comparison_expr(self) -> Expr<T> {
400        self
401    }
402}
403
404impl<T> ComparisonValue<Option<T>, ExprComparisonMarker> for Expr<T> {
405    fn into_comparison_expr(self) -> Expr<Option<T>> {
406        Expr::new(self.node)
407    }
408}
409
410impl<M, T> IntoExpr<T> for Column<M, T> {
411    fn into_expr(self) -> Expr<T> {
412        Expr::new(ExprNode::Column(self.as_ref()))
413    }
414}
415
416impl<M, T> ExprOperand for Column<M, T> {
417    type Value = T;
418
419    fn into_operand_expr(self) -> Expr<Self::Value> {
420        self.into_expr()
421    }
422}
423
424impl<M, T> ComparisonValue<T, ExprComparisonMarker> for Column<M, T> {
425    fn into_comparison_expr(self) -> Expr<T> {
426        self.into_expr()
427    }
428}
429
430impl<M, T> ComparisonValue<Option<T>, ExprComparisonMarker> for Column<M, T> {
431    fn into_comparison_expr(self) -> Expr<Option<T>> {
432        Expr::new(ExprNode::Column(self.as_ref()))
433    }
434}
435
436macro_rules! impl_row_tuple_support {
437    ($(($($model:ident:$col_ty:ident:$col_ident:ident:$value_ty:ident:$value_ident:ident),+)),+ $(,)?) => {
438        $(
439            impl<$($model, $col_ty),+> RowColumns for ($(Column<$model, $col_ty>,)+) {
440                type ValueTuple = ($($col_ty,)+);
441
442                fn into_row_expr(self) -> RowExpr<Self::ValueTuple> {
443                    let ($($col_ident,)+) = self;
444                    RowExpr::new(ExprNode::Row {
445                        values: vec![$(ExprNode::Column($col_ident.as_ref())),+],
446                    })
447                }
448            }
449
450            impl<$($model, $col_ty),+> row_columns_private::Sealed for ($(Column<$model, $col_ty>,)+) {}
451
452            impl<$($col_ty),+> RowExpr<($($col_ty,)+)> {
453                pub fn in_<I, $($value_ty),+>(self, values: I) -> Expr<bool>
454                where
455                    I: IntoIterator<Item = ($($value_ty,)+)>,
456                    $($value_ty: ColumnValue<$col_ty>,)+
457                {
458                    let rows = values
459                        .into_iter()
460                        .map(|($($value_ident,)+)| vec![$($value_ident.into_value().unwrap_or(Value::Null)),+])
461                        .collect();
462
463                    Expr::new(ExprNode::RowIn {
464                        expr: Box::new(self.node),
465                        rows,
466                    })
467                }
468            }
469        )+
470    };
471}
472
473impl_row_tuple_support!(
474    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2),
475    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3),
476    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3, M4:T4:c4:V4:v4),
477    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3, M4:T4:c4:V4:v4, M5:T5:c5:V5:v5),
478    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3, M4:T4:c4:V4:v4, M5:T5:c5:V5:v5, M6:T6:c6:V6:v6),
479    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3, M4:T4:c4:V4:v4, M5:T5:c5:V5:v5, M6:T6:c6:V6:v6, M7:T7:c7:V7:v7),
480    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3, M4:T4:c4:V4:v4, M5:T5:c5:V5:v5, M6:T6:c6:V6:v6, M7:T7:c7:V7:v7, M8:T8:c8:V8:v8),
481    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3, M4:T4:c4:V4:v4, M5:T5:c5:V5:v5, M6:T6:c6:V6:v6, M7:T7:c7:V7:v7, M8:T8:c8:V8:v8, M9:T9:c9:V9:v9),
482    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3, M4:T4:c4:V4:v4, M5:T5:c5:V5:v5, M6:T6:c6:V6:v6, M7:T7:c7:V7:v7, M8:T8:c8:V8:v8, M9:T9:c9:V9:v9, M10:T10:c10:V10:v10),
483    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3, M4:T4:c4:V4:v4, M5:T5:c5:V5:v5, M6:T6:c6:V6:v6, M7:T7:c7:V7:v7, M8:T8:c8:V8:v8, M9:T9:c9:V9:v9, M10:T10:c10:V10:v10, M11:T11:c11:V11:v11),
484    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3, M4:T4:c4:V4:v4, M5:T5:c5:V5:v5, M6:T6:c6:V6:v6, M7:T7:c7:V7:v7, M8:T8:c8:V8:v8, M9:T9:c9:V9:v9, M10:T10:c10:V10:v10, M11:T11:c11:V11:v11, M12:T12:c12:V12:v12),
485    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3, M4:T4:c4:V4:v4, M5:T5:c5:V5:v5, M6:T6:c6:V6:v6, M7:T7:c7:V7:v7, M8:T8:c8:V8:v8, M9:T9:c9:V9:v9, M10:T10:c10:V10:v10, M11:T11:c11:V11:v11, M12:T12:c12:V12:v12, M13:T13:c13:V13:v13),
486    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3, M4:T4:c4:V4:v4, M5:T5:c5:V5:v5, M6:T6:c6:V6:v6, M7:T7:c7:V7:v7, M8:T8:c8:V8:v8, M9:T9:c9:V9:v9, M10:T10:c10:V10:v10, M11:T11:c11:V11:v11, M12:T12:c12:V12:v12, M13:T13:c13:V13:v13, M14:T14:c14:V14:v14),
487    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3, M4:T4:c4:V4:v4, M5:T5:c5:V5:v5, M6:T6:c6:V6:v6, M7:T7:c7:V7:v7, M8:T8:c8:V8:v8, M9:T9:c9:V9:v9, M10:T10:c10:V10:v10, M11:T11:c11:V11:v11, M12:T12:c12:V12:v12, M13:T13:c13:V13:v13, M14:T14:c14:V14:v14, M15:T15:c15:V15:v15),
488    (M1:T1:c1:V1:v1, M2:T2:c2:V2:v2, M3:T3:c3:V3:v3, M4:T4:c4:V4:v4, M5:T5:c5:V5:v5, M6:T6:c6:V6:v6, M7:T7:c7:V7:v7, M8:T8:c8:V8:v8, M9:T9:c9:V9:v9, M10:T10:c10:V10:v10, M11:T11:c11:V11:v11, M12:T12:c12:V12:v12, M13:T13:c13:V13:v13, M14:T14:c14:V14:v14, M15:T15:c15:V15:v15, M16:T16:c16:V16:v16)
489);
490
491impl<T, V> ComparisonValue<T, ValueComparisonMarker> for V
492where
493    V: Into<Value>,
494{
495    fn into_comparison_expr(self) -> Expr<T> {
496        Expr::new(ExprNode::Value(self.into()))
497    }
498}
499
500impl IntoExpr<String> for String {
501    fn into_expr(self) -> Expr<String> {
502        Expr::new(ExprNode::Value(Value::String(self)))
503    }
504}
505
506impl ExprOperand for String {
507    type Value = String;
508
509    fn into_operand_expr(self) -> Expr<Self::Value> {
510        self.into_expr()
511    }
512}
513
514impl IntoExpr<String> for &str {
515    fn into_expr(self) -> Expr<String> {
516        Expr::new(ExprNode::Value(Value::String(self.to_string())))
517    }
518}
519
520impl ExprOperand for &str {
521    type Value = String;
522
523    fn into_operand_expr(self) -> Expr<Self::Value> {
524        self.into_expr()
525    }
526}
527
528impl IntoExpr<bool> for bool {
529    fn into_expr(self) -> Expr<bool> {
530        Expr::new(ExprNode::Value(Value::Bool(self)))
531    }
532}
533
534impl ExprOperand for bool {
535    type Value = bool;
536
537    fn into_operand_expr(self) -> Expr<Self::Value> {
538        self.into_expr()
539    }
540}
541
542impl IntoExpr<i16> for i16 {
543    fn into_expr(self) -> Expr<i16> {
544        Expr::new(ExprNode::Value(Value::I16(self)))
545    }
546}
547
548impl ExprOperand for i16 {
549    type Value = i16;
550
551    fn into_operand_expr(self) -> Expr<Self::Value> {
552        self.into_expr()
553    }
554}
555
556impl NumericExprType for i16 {}
557
558impl IntoExpr<i32> for i32 {
559    fn into_expr(self) -> Expr<i32> {
560        Expr::new(ExprNode::Value(Value::I32(self)))
561    }
562}
563
564impl ExprOperand for i32 {
565    type Value = i32;
566
567    fn into_operand_expr(self) -> Expr<Self::Value> {
568        self.into_expr()
569    }
570}
571
572impl NumericExprType for i32 {}
573
574impl IntoExpr<i64> for i64 {
575    fn into_expr(self) -> Expr<i64> {
576        Expr::new(ExprNode::Value(Value::I64(self)))
577    }
578}
579
580impl ExprOperand for i64 {
581    type Value = i64;
582
583    fn into_operand_expr(self) -> Expr<Self::Value> {
584        self.into_expr()
585    }
586}
587
588impl NumericExprType for i64 {}
589
590impl IntoExpr<f32> for f32 {
591    fn into_expr(self) -> Expr<f32> {
592        Expr::new(ExprNode::Value(Value::F32(self)))
593    }
594}
595
596impl ExprOperand for f32 {
597    type Value = f32;
598
599    fn into_operand_expr(self) -> Expr<Self::Value> {
600        self.into_expr()
601    }
602}
603
604impl NumericExprType for f32 {}
605
606impl IntoExpr<f64> for f64 {
607    fn into_expr(self) -> Expr<f64> {
608        Expr::new(ExprNode::Value(Value::F64(self)))
609    }
610}
611
612impl ExprOperand for f64 {
613    type Value = f64;
614
615    fn into_operand_expr(self) -> Expr<Self::Value> {
616        self.into_expr()
617    }
618}
619
620impl NumericExprType for f64 {}
621
622impl IntoExpr<uuid::Uuid> for uuid::Uuid {
623    fn into_expr(self) -> Expr<uuid::Uuid> {
624        Expr::new(ExprNode::Value(Value::Uuid(self)))
625    }
626}
627
628impl ExprOperand for uuid::Uuid {
629    type Value = uuid::Uuid;
630
631    fn into_operand_expr(self) -> Expr<Self::Value> {
632        self.into_expr()
633    }
634}
635
636impl IntoExpr<chrono::NaiveDateTime> for chrono::NaiveDateTime {
637    fn into_expr(self) -> Expr<chrono::NaiveDateTime> {
638        Expr::new(ExprNode::Value(Value::DateTime(self)))
639    }
640}
641
642impl ExprOperand for chrono::NaiveDateTime {
643    type Value = chrono::NaiveDateTime;
644
645    fn into_operand_expr(self) -> Expr<Self::Value> {
646        self.into_expr()
647    }
648}
649
650impl IntoExpr<chrono::DateTime<chrono::Utc>> for chrono::DateTime<chrono::Utc> {
651    fn into_expr(self) -> Expr<chrono::DateTime<chrono::Utc>> {
652        Expr::new(ExprNode::Value(Value::DateTimeUtc(self)))
653    }
654}
655
656impl ExprOperand for chrono::DateTime<chrono::Utc> {
657    type Value = chrono::DateTime<chrono::Utc>;
658
659    fn into_operand_expr(self) -> Expr<Self::Value> {
660        self.into_expr()
661    }
662}
663
664impl IntoExpr<chrono::NaiveDate> for chrono::NaiveDate {
665    fn into_expr(self) -> Expr<chrono::NaiveDate> {
666        Expr::new(ExprNode::Value(Value::Date(self)))
667    }
668}
669
670impl ExprOperand for chrono::NaiveDate {
671    type Value = chrono::NaiveDate;
672
673    fn into_operand_expr(self) -> Expr<Self::Value> {
674        self.into_expr()
675    }
676}
677
678impl IntoExpr<chrono::NaiveTime> for chrono::NaiveTime {
679    fn into_expr(self) -> Expr<chrono::NaiveTime> {
680        Expr::new(ExprNode::Value(Value::Time(self)))
681    }
682}
683
684impl ExprOperand for chrono::NaiveTime {
685    type Value = chrono::NaiveTime;
686
687    fn into_operand_expr(self) -> Expr<Self::Value> {
688        self.into_expr()
689    }
690}
691
692impl IntoExpr<PgInterval> for PgInterval {
693    fn into_expr(self) -> Expr<PgInterval> {
694        Expr::new(ExprNode::Value(Value::Interval(self)))
695    }
696}
697
698impl ExprOperand for PgInterval {
699    type Value = PgInterval;
700
701    fn into_operand_expr(self) -> Expr<Self::Value> {
702        self.into_expr()
703    }
704}
705
706impl IntoExpr<Vec<String>> for Vec<String> {
707    fn into_expr(self) -> Expr<Vec<String>> {
708        Expr::new(ExprNode::Value(Value::Array(self)))
709    }
710}
711
712impl ExprOperand for Vec<String> {
713    type Value = Vec<String>;
714
715    fn into_operand_expr(self) -> Expr<Self::Value> {
716        self.into_expr()
717    }
718}
719
720impl IntoExpr<serde_json::Value> for serde_json::Value {
721    fn into_expr(self) -> Expr<serde_json::Value> {
722        Expr::new(ExprNode::Value(Value::Json(self)))
723    }
724}
725
726impl ExprOperand for serde_json::Value {
727    type Value = serde_json::Value;
728
729    fn into_operand_expr(self) -> Expr<Self::Value> {
730        self.into_expr()
731    }
732}
733
734impl<const N: usize> IntoExpr<PgVector<N>> for PgVector<N> {
735    fn into_expr(self) -> Expr<PgVector<N>> {
736        Expr::new(ExprNode::Value(Value::from(self)))
737    }
738}
739
740impl<const N: usize> ExprOperand for PgVector<N> {
741    type Value = PgVector<N>;
742
743    fn into_operand_expr(self) -> Expr<Self::Value> {
744        self.into_expr()
745    }
746}
747
748macro_rules! impl_numeric_arithmetic {
749    ($($ty:ty),* $(,)?) => {
750        $(
751            impl SqlAdd<$ty> for $ty {
752                type Output = $ty;
753            }
754
755            impl SqlSub<$ty> for $ty {
756                type Output = $ty;
757            }
758
759            impl SqlMul<$ty> for $ty {
760                type Output = $ty;
761            }
762        )*
763    };
764}
765
766impl SqlAdd<i16> for i16 {
767    type Output = i32;
768}
769
770impl SqlSub<i16> for i16 {
771    type Output = i32;
772}
773
774impl SqlMul<i16> for i16 {
775    type Output = i32;
776}
777
778impl_numeric_arithmetic!(i32, i64, f32, f64);
779
780impl SqlAdd<PgInterval> for chrono::NaiveDateTime {
781    type Output = chrono::NaiveDateTime;
782}
783
784impl SqlSub<PgInterval> for chrono::NaiveDateTime {
785    type Output = chrono::NaiveDateTime;
786}
787
788impl SqlAdd<PgInterval> for chrono::DateTime<chrono::Utc> {
789    type Output = chrono::DateTime<chrono::Utc>;
790}
791
792impl SqlSub<PgInterval> for chrono::DateTime<chrono::Utc> {
793    type Output = chrono::DateTime<chrono::Utc>;
794}
795
796impl Add<Expr<PgInterval>> for chrono::NaiveDateTime {
797    type Output = Expr<chrono::NaiveDateTime>;
798
799    fn add(self, rhs: Expr<PgInterval>) -> Self::Output {
800        arithmetic_expr(self.into_expr().node, BinaryOp::Add, rhs.node)
801    }
802}
803
804impl Sub<Expr<PgInterval>> for chrono::NaiveDateTime {
805    type Output = Expr<chrono::NaiveDateTime>;
806
807    fn sub(self, rhs: Expr<PgInterval>) -> Self::Output {
808        arithmetic_expr(self.into_expr().node, BinaryOp::Sub, rhs.node)
809    }
810}
811
812impl Add<Expr<PgInterval>> for chrono::DateTime<chrono::Utc> {
813    type Output = Expr<chrono::DateTime<chrono::Utc>>;
814
815    fn add(self, rhs: Expr<PgInterval>) -> Self::Output {
816        arithmetic_expr(self.into_expr().node, BinaryOp::Add, rhs.node)
817    }
818}
819
820impl Sub<Expr<PgInterval>> for chrono::DateTime<chrono::Utc> {
821    type Output = Expr<chrono::DateTime<chrono::Utc>>;
822
823    fn sub(self, rhs: Expr<PgInterval>) -> Self::Output {
824        arithmetic_expr(self.into_expr().node, BinaryOp::Sub, rhs.node)
825    }
826}
827
828fn arithmetic_expr<Out>(left: ExprNode, op: BinaryOp, right: ExprNode) -> Expr<Out> {
829    Expr::new(ExprNode::Binary {
830        left: Box::new(left),
831        op,
832        right: Box::new(right),
833    })
834}
835
836impl<Lhs, RhsExpr> Add<RhsExpr> for Expr<Lhs>
837where
838    RhsExpr: ExprOperand,
839    Lhs: SqlAdd<RhsExpr::Value>,
840{
841    type Output = Expr<<Lhs as SqlAdd<RhsExpr::Value>>::Output>;
842
843    fn add(self, rhs: RhsExpr) -> Self::Output {
844        arithmetic_expr(self.node, BinaryOp::Add, rhs.into_operand_expr().node)
845    }
846}
847
848impl<Lhs, RhsExpr> Sub<RhsExpr> for Expr<Lhs>
849where
850    RhsExpr: ExprOperand,
851    Lhs: SqlSub<RhsExpr::Value>,
852{
853    type Output = Expr<<Lhs as SqlSub<RhsExpr::Value>>::Output>;
854
855    fn sub(self, rhs: RhsExpr) -> Self::Output {
856        arithmetic_expr(self.node, BinaryOp::Sub, rhs.into_operand_expr().node)
857    }
858}
859
860impl<Lhs, RhsExpr> Mul<RhsExpr> for Expr<Lhs>
861where
862    RhsExpr: ExprOperand,
863    Lhs: SqlMul<RhsExpr::Value>,
864{
865    type Output = Expr<<Lhs as SqlMul<RhsExpr::Value>>::Output>;
866
867    fn mul(self, rhs: RhsExpr) -> Self::Output {
868        arithmetic_expr(self.node, BinaryOp::Mul, rhs.into_operand_expr().node)
869    }
870}
871
872impl<M, Lhs, RhsExpr> Add<RhsExpr> for Column<M, Lhs>
873where
874    RhsExpr: ExprOperand,
875    Lhs: SqlAdd<RhsExpr::Value>,
876{
877    type Output = Expr<<Lhs as SqlAdd<RhsExpr::Value>>::Output>;
878
879    fn add(self, rhs: RhsExpr) -> Self::Output {
880        arithmetic_expr(ExprNode::Column(self.as_ref()), BinaryOp::Add, rhs.into_operand_expr().node)
881    }
882}
883
884impl<M, Lhs, RhsExpr> Sub<RhsExpr> for Column<M, Lhs>
885where
886    RhsExpr: ExprOperand,
887    Lhs: SqlSub<RhsExpr::Value>,
888{
889    type Output = Expr<<Lhs as SqlSub<RhsExpr::Value>>::Output>;
890
891    fn sub(self, rhs: RhsExpr) -> Self::Output {
892        arithmetic_expr(ExprNode::Column(self.as_ref()), BinaryOp::Sub, rhs.into_operand_expr().node)
893    }
894}
895
896impl<M, Lhs, RhsExpr> Mul<RhsExpr> for Column<M, Lhs>
897where
898    RhsExpr: ExprOperand,
899    Lhs: SqlMul<RhsExpr::Value>,
900{
901    type Output = Expr<<Lhs as SqlMul<RhsExpr::Value>>::Output>;
902
903    fn mul(self, rhs: RhsExpr) -> Self::Output {
904        arithmetic_expr(ExprNode::Column(self.as_ref()), BinaryOp::Mul, rhs.into_operand_expr().node)
905    }
906}
907
908impl<T> Expr<T>
909where
910    T: 'static,
911{
912    pub fn eq<V>(self, value: V) -> Expr<bool>
913    where
914        V: ColumnValue<T>,
915    {
916        match value.into_value() {
917            Some(Value::Null) => Expr::new(ExprNode::IsNull {
918                expr: Box::new(self.node),
919                negated: false,
920            }),
921            Some(value) => Expr::new(ExprNode::Binary {
922                left: Box::new(self.node),
923                op: BinaryOp::Eq,
924                right: Box::new(ExprNode::Value(value)),
925            }),
926            None => Expr::new(ExprNode::IsNull {
927                expr: Box::new(self.node),
928                negated: false,
929            }),
930        }
931    }
932
933    pub fn eq_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
934        Expr::new(ExprNode::Binary {
935            left: Box::new(self.node),
936            op: BinaryOp::Eq,
937            right: Box::new(ExprNode::Column(other.as_ref())),
938        })
939    }
940
941    pub fn ne<V>(self, value: V) -> Expr<bool>
942    where
943        V: ColumnValue<T>,
944    {
945        match value.into_value() {
946            Some(Value::Null) => Expr::new(ExprNode::IsNull {
947                expr: Box::new(self.node),
948                negated: true,
949            }),
950            Some(value) => Expr::new(ExprNode::Binary {
951                left: Box::new(self.node),
952                op: BinaryOp::Ne,
953                right: Box::new(ExprNode::Value(value)),
954            }),
955            None => Expr::new(ExprNode::IsNull {
956                expr: Box::new(self.node),
957                negated: true,
958            }),
959        }
960    }
961
962    pub fn ne_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
963        Expr::new(ExprNode::Binary {
964            left: Box::new(self.node),
965            op: BinaryOp::Ne,
966            right: Box::new(ExprNode::Column(other.as_ref())),
967        })
968    }
969
970    pub fn is_distinct_from_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
971        Expr::new(ExprNode::Binary {
972            left: Box::new(self.node),
973            op: BinaryOp::IsDistinctFrom,
974            right: Box::new(ExprNode::Column(other.as_ref())),
975        })
976    }
977
978    pub fn is_not_distinct_from_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
979        Expr::new(ExprNode::Binary {
980            left: Box::new(self.node),
981            op: BinaryOp::IsNotDistinctFrom,
982            right: Box::new(ExprNode::Column(other.as_ref())),
983        })
984    }
985
986    pub fn lt<V>(self, value: V) -> Expr<bool>
987    where
988        V: ColumnValue<T>,
989    {
990        Expr::new(ExprNode::Binary {
991            left: Box::new(self.node),
992            op: BinaryOp::Lt,
993            right: Box::new(ExprNode::Value(value.into_value().unwrap_or(Value::Null))),
994        })
995    }
996
997    pub fn lt_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
998        Expr::new(ExprNode::Binary {
999            left: Box::new(self.node),
1000            op: BinaryOp::Lt,
1001            right: Box::new(ExprNode::Column(other.as_ref())),
1002        })
1003    }
1004
1005    pub fn le<V>(self, value: V) -> Expr<bool>
1006    where
1007        V: ColumnValue<T>,
1008    {
1009        Expr::new(ExprNode::Binary {
1010            left: Box::new(self.node),
1011            op: BinaryOp::Le,
1012            right: Box::new(ExprNode::Value(value.into_value().unwrap_or(Value::Null))),
1013        })
1014    }
1015
1016    pub fn le_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
1017        Expr::new(ExprNode::Binary {
1018            left: Box::new(self.node),
1019            op: BinaryOp::Le,
1020            right: Box::new(ExprNode::Column(other.as_ref())),
1021        })
1022    }
1023
1024    pub fn gt<V>(self, value: V) -> Expr<bool>
1025    where
1026        V: ColumnValue<T>,
1027    {
1028        Expr::new(ExprNode::Binary {
1029            left: Box::new(self.node),
1030            op: BinaryOp::Gt,
1031            right: Box::new(ExprNode::Value(value.into_value().unwrap_or(Value::Null))),
1032        })
1033    }
1034
1035    pub fn gt_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
1036        Expr::new(ExprNode::Binary {
1037            left: Box::new(self.node),
1038            op: BinaryOp::Gt,
1039            right: Box::new(ExprNode::Column(other.as_ref())),
1040        })
1041    }
1042
1043    pub fn ge<V>(self, value: V) -> Expr<bool>
1044    where
1045        V: ColumnValue<T>,
1046    {
1047        Expr::new(ExprNode::Binary {
1048            left: Box::new(self.node),
1049            op: BinaryOp::Ge,
1050            right: Box::new(ExprNode::Value(value.into_value().unwrap_or(Value::Null))),
1051        })
1052    }
1053
1054    pub fn ge_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
1055        Expr::new(ExprNode::Binary {
1056            left: Box::new(self.node),
1057            op: BinaryOp::Ge,
1058            right: Box::new(ExprNode::Column(other.as_ref())),
1059        })
1060    }
1061
1062    pub fn between<L, U>(self, low: L, high: U) -> Expr<bool>
1063    where
1064        L: ColumnValue<T>,
1065        U: ColumnValue<T>,
1066    {
1067        let low_value = low.into_value().unwrap_or(Value::Null);
1068        let high_value = high.into_value().unwrap_or(Value::Null);
1069        let node = self.node;
1070        let left = ExprNode::Binary {
1071            left: Box::new(node.clone()),
1072            op: BinaryOp::Ge,
1073            right: Box::new(ExprNode::Value(low_value)),
1074        };
1075        let right = ExprNode::Binary {
1076            left: Box::new(node),
1077            op: BinaryOp::Le,
1078            right: Box::new(ExprNode::Value(high_value)),
1079        };
1080        Expr::new(ExprNode::Bool {
1081            left: Box::new(left),
1082            op: BoolOp::And,
1083            right: Box::new(right),
1084        })
1085    }
1086
1087    pub fn like<V>(self, pattern: V) -> Expr<bool>
1088    where
1089        V: ColumnValue<T>,
1090    {
1091        Expr::new(ExprNode::Like {
1092            expr: Box::new(self.node),
1093            pattern: pattern.into_value().unwrap_or(Value::Null),
1094            case_insensitive: false,
1095        })
1096    }
1097
1098    pub fn ilike<V>(self, pattern: V) -> Expr<bool>
1099    where
1100        V: ColumnValue<T>,
1101    {
1102        Expr::new(ExprNode::Like {
1103            expr: Box::new(self.node),
1104            pattern: pattern.into_value().unwrap_or(Value::Null),
1105            case_insensitive: true,
1106        })
1107    }
1108
1109    pub fn is_null(self) -> Expr<bool> {
1110        Expr::new(ExprNode::IsNull {
1111            expr: Box::new(self.node),
1112            negated: false,
1113        })
1114    }
1115
1116    pub fn is_not_null(self) -> Expr<bool> {
1117        Expr::new(ExprNode::IsNull {
1118            expr: Box::new(self.node),
1119            negated: true,
1120        })
1121    }
1122
1123    pub fn in_<I, V>(self, values: I) -> Expr<bool>
1124    where
1125        I: IntoIterator<Item = V>,
1126        V: ColumnValue<T>,
1127    {
1128        let mut binds = Vec::new();
1129        for value in values {
1130            if let Some(value) = value.into_value() {
1131                binds.push(value);
1132            }
1133        }
1134        Expr::new(ExprNode::In {
1135            expr: Box::new(self.node),
1136            values: binds,
1137        })
1138    }
1139}
1140
1141impl Expr<bool> {
1142    pub fn and(self, other: Expr<bool>) -> Expr<bool> {
1143        Expr::new(ExprNode::Bool {
1144            left: Box::new(self.node),
1145            op: BoolOp::And,
1146            right: Box::new(other.node),
1147        })
1148    }
1149
1150    pub fn or(self, other: Expr<bool>) -> Expr<bool> {
1151        Expr::new(ExprNode::Bool {
1152            left: Box::new(self.node),
1153            op: BoolOp::Or,
1154            right: Box::new(other.node),
1155        })
1156    }
1157
1158    pub fn not(self) -> Expr<bool> {
1159        Expr::new(ExprNode::Unary {
1160            op: UnaryOp::Not,
1161            expr: Box::new(self.node),
1162        })
1163    }
1164}
1165
1166impl<M, T> Column<M, T>
1167where
1168    T: 'static,
1169{
1170    pub fn eq<V>(self, value: V) -> Expr<bool>
1171    where
1172        V: ColumnValue<T>,
1173    {
1174        match value.into_value() {
1175            Some(Value::Null) => Expr::new(ExprNode::IsNull {
1176                expr: Box::new(ExprNode::Column(self.as_ref())),
1177                negated: false,
1178            }),
1179            Some(value) => Expr::new(ExprNode::Binary {
1180                left: Box::new(ExprNode::Column(self.as_ref())),
1181                op: BinaryOp::Eq,
1182                right: Box::new(ExprNode::Value(value)),
1183            }),
1184            None => Expr::new(ExprNode::IsNull {
1185                expr: Box::new(ExprNode::Column(self.as_ref())),
1186                negated: false,
1187            }),
1188        }
1189    }
1190
1191    pub fn eq_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
1192        Expr::new(ExprNode::Binary {
1193            left: Box::new(ExprNode::Column(self.as_ref())),
1194            op: BinaryOp::Eq,
1195            right: Box::new(ExprNode::Column(other.as_ref())),
1196        })
1197    }
1198
1199    pub fn ne_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
1200        Expr::new(ExprNode::Binary {
1201            left: Box::new(ExprNode::Column(self.as_ref())),
1202            op: BinaryOp::Ne,
1203            right: Box::new(ExprNode::Column(other.as_ref())),
1204        })
1205    }
1206
1207    pub fn is_distinct_from_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
1208        Expr::new(ExprNode::Binary {
1209            left: Box::new(ExprNode::Column(self.as_ref())),
1210            op: BinaryOp::IsDistinctFrom,
1211            right: Box::new(ExprNode::Column(other.as_ref())),
1212        })
1213    }
1214
1215    pub fn is_not_distinct_from_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
1216        Expr::new(ExprNode::Binary {
1217            left: Box::new(ExprNode::Column(self.as_ref())),
1218            op: BinaryOp::IsNotDistinctFrom,
1219            right: Box::new(ExprNode::Column(other.as_ref())),
1220        })
1221    }
1222
1223    pub fn ne<V>(self, value: V) -> Expr<bool>
1224    where
1225        V: ColumnValue<T>,
1226    {
1227        match value.into_value() {
1228            Some(Value::Null) => Expr::new(ExprNode::IsNull {
1229                expr: Box::new(ExprNode::Column(self.as_ref())),
1230                negated: true,
1231            }),
1232            Some(value) => Expr::new(ExprNode::Binary {
1233                left: Box::new(ExprNode::Column(self.as_ref())),
1234                op: BinaryOp::Ne,
1235                right: Box::new(ExprNode::Value(value)),
1236            }),
1237            None => Expr::new(ExprNode::IsNull {
1238                expr: Box::new(ExprNode::Column(self.as_ref())),
1239                negated: true,
1240            }),
1241        }
1242    }
1243
1244    pub fn lt<V, Marker>(self, value: V) -> Expr<bool>
1245    where
1246        V: ComparisonValue<T, Marker>,
1247    {
1248        Expr::new(ExprNode::Binary {
1249            left: Box::new(ExprNode::Column(self.as_ref())),
1250            op: BinaryOp::Lt,
1251            right: Box::new(value.into_comparison_expr().node),
1252        })
1253    }
1254
1255    pub fn lt_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
1256        Expr::new(ExprNode::Binary {
1257            left: Box::new(ExprNode::Column(self.as_ref())),
1258            op: BinaryOp::Lt,
1259            right: Box::new(ExprNode::Column(other.as_ref())),
1260        })
1261    }
1262
1263    pub fn le<V, Marker>(self, value: V) -> Expr<bool>
1264    where
1265        V: ComparisonValue<T, Marker>,
1266    {
1267        Expr::new(ExprNode::Binary {
1268            left: Box::new(ExprNode::Column(self.as_ref())),
1269            op: BinaryOp::Le,
1270            right: Box::new(value.into_comparison_expr().node),
1271        })
1272    }
1273
1274    pub fn le_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
1275        Expr::new(ExprNode::Binary {
1276            left: Box::new(ExprNode::Column(self.as_ref())),
1277            op: BinaryOp::Le,
1278            right: Box::new(ExprNode::Column(other.as_ref())),
1279        })
1280    }
1281
1282    pub fn gt<V, Marker>(self, value: V) -> Expr<bool>
1283    where
1284        V: ComparisonValue<T, Marker>,
1285    {
1286        Expr::new(ExprNode::Binary {
1287            left: Box::new(ExprNode::Column(self.as_ref())),
1288            op: BinaryOp::Gt,
1289            right: Box::new(value.into_comparison_expr().node),
1290        })
1291    }
1292
1293    pub fn gt_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
1294        Expr::new(ExprNode::Binary {
1295            left: Box::new(ExprNode::Column(self.as_ref())),
1296            op: BinaryOp::Gt,
1297            right: Box::new(ExprNode::Column(other.as_ref())),
1298        })
1299    }
1300
1301    pub fn ge<V, Marker>(self, value: V) -> Expr<bool>
1302    where
1303        V: ComparisonValue<T, Marker>,
1304    {
1305        Expr::new(ExprNode::Binary {
1306            left: Box::new(ExprNode::Column(self.as_ref())),
1307            op: BinaryOp::Ge,
1308            right: Box::new(value.into_comparison_expr().node),
1309        })
1310    }
1311
1312    pub fn ge_col<M2>(self, other: Column<M2, T>) -> Expr<bool> {
1313        Expr::new(ExprNode::Binary {
1314            left: Box::new(ExprNode::Column(self.as_ref())),
1315            op: BinaryOp::Ge,
1316            right: Box::new(ExprNode::Column(other.as_ref())),
1317        })
1318    }
1319
1320    pub fn between<L, U>(self, low: L, high: U) -> Expr<bool>
1321    where
1322        L: Into<Value>,
1323        U: Into<Value>,
1324    {
1325        let left = ExprNode::Binary {
1326            left: Box::new(ExprNode::Column(self.as_ref())),
1327            op: BinaryOp::Ge,
1328            right: Box::new(ExprNode::Value(low.into())),
1329        };
1330        let right = ExprNode::Binary {
1331            left: Box::new(ExprNode::Column(self.as_ref())),
1332            op: BinaryOp::Le,
1333            right: Box::new(ExprNode::Value(high.into())),
1334        };
1335        Expr::new(ExprNode::Bool {
1336            left: Box::new(left),
1337            op: BoolOp::And,
1338            right: Box::new(right),
1339        })
1340    }
1341
1342    pub fn like<V>(self, pattern: V) -> Expr<bool>
1343    where
1344        V: Into<Value>,
1345    {
1346        Expr::new(ExprNode::Like {
1347            expr: Box::new(ExprNode::Column(self.as_ref())),
1348            pattern: pattern.into(),
1349            case_insensitive: false,
1350        })
1351    }
1352
1353    pub fn ilike<V>(self, pattern: V) -> Expr<bool>
1354    where
1355        V: Into<Value>,
1356    {
1357        Expr::new(ExprNode::Like {
1358            expr: Box::new(ExprNode::Column(self.as_ref())),
1359            pattern: pattern.into(),
1360            case_insensitive: true,
1361        })
1362    }
1363
1364    pub fn in_<I, V>(self, values: I) -> Expr<bool>
1365    where
1366        I: IntoIterator<Item = V>,
1367        V: Into<Value>,
1368    {
1369        Expr::new(ExprNode::In {
1370            expr: Box::new(ExprNode::Column(self.as_ref())),
1371            values: values.into_iter().map(Into::into).collect(),
1372        })
1373    }
1374
1375    pub fn is_null(self) -> Expr<bool> {
1376        Expr::new(ExprNode::IsNull {
1377            expr: Box::new(ExprNode::Column(self.as_ref())),
1378            negated: false,
1379        })
1380    }
1381
1382    pub fn is_not_null(self) -> Expr<bool> {
1383        Expr::new(ExprNode::IsNull {
1384            expr: Box::new(ExprNode::Column(self.as_ref())),
1385            negated: true,
1386        })
1387    }
1388}
1389
1390#[derive(Debug, Clone, Copy)]
1391pub enum ConditionKind {
1392    Any,
1393    All,
1394}
1395
1396#[derive(Debug, Clone)]
1397pub struct Condition {
1398    kind: ConditionKind,
1399    exprs: Vec<Expr<bool>>,
1400}
1401
1402impl Condition {
1403    pub fn any() -> Self {
1404        Self {
1405            kind: ConditionKind::Any,
1406            exprs: Vec::new(),
1407        }
1408    }
1409
1410    pub fn all() -> Self {
1411        Self {
1412            kind: ConditionKind::All,
1413            exprs: Vec::new(),
1414        }
1415    }
1416
1417    pub fn add(mut self, expr: Expr<bool>) -> Self {
1418        self.exprs.push(expr);
1419        self
1420    }
1421
1422    pub fn into_expr(self) -> Option<Expr<bool>> {
1423        let mut iter = self.exprs.into_iter();
1424        let first = iter.next()?;
1425        Some(iter.fold(first, |acc, expr| match self.kind {
1426            ConditionKind::Any => acc.or(expr),
1427            ConditionKind::All => acc.and(expr),
1428        }))
1429    }
1430}