Skip to main content

che_orm/
types.rs

1use std::marker::PhantomData;
2
3use time::OffsetDateTime;
4
5use crate::{DbEnum, OrderBy, OrderDirection};
6
7#[derive(Debug, Clone, PartialEq)]
8/// Values bound to SQL placeholders.
9pub enum DatabaseValue {
10    Integer(i64),
11    Text(String),
12    Binary(Vec<u8>),
13    Boolean(bool),
14    DateTime(OffsetDateTime),
15    Null,
16}
17
18pub trait QueryValue<T> {
19    fn into_query_value(self) -> DatabaseValue;
20}
21
22impl QueryValue<i64> for i64 {
23    fn into_query_value(self) -> DatabaseValue {
24        DatabaseValue::Integer(self)
25    }
26}
27
28impl QueryValue<String> for String {
29    fn into_query_value(self) -> DatabaseValue {
30        DatabaseValue::Text(self)
31    }
32}
33
34impl QueryValue<String> for &str {
35    fn into_query_value(self) -> DatabaseValue {
36        DatabaseValue::Text(self.to_owned())
37    }
38}
39
40impl QueryValue<Vec<u8>> for Vec<u8> {
41    fn into_query_value(self) -> DatabaseValue {
42        DatabaseValue::Binary(self)
43    }
44}
45
46impl QueryValue<bool> for bool {
47    fn into_query_value(self) -> DatabaseValue {
48        DatabaseValue::Boolean(self)
49    }
50}
51
52impl QueryValue<OffsetDateTime> for OffsetDateTime {
53    fn into_query_value(self) -> DatabaseValue {
54        DatabaseValue::DateTime(self)
55    }
56}
57
58impl<T: DbEnum> QueryValue<T> for T {
59    fn into_query_value(self) -> DatabaseValue {
60        DatabaseValue::Text(self.as_str().to_owned())
61    }
62}
63
64impl<T, V> QueryValue<Option<T>> for Option<V>
65where
66    V: QueryValue<T>,
67{
68    fn into_query_value(self) -> DatabaseValue {
69        self.map_or(DatabaseValue::Null, QueryValue::into_query_value)
70    }
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct TableRef {
75    pub name: &'static str,
76}
77
78impl TableRef {
79    pub const fn new(name: &'static str) -> Self {
80        Self { name }
81    }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct ColumnRef {
86    pub table: &'static str,
87    pub name: &'static str,
88}
89
90impl ColumnRef {
91    pub const fn new(table: &'static str, name: &'static str) -> Self {
92        Self { table, name }
93    }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum CompareOp {
98    Eq,
99    Ne,
100    Gt,
101    Gte,
102    Lt,
103    Lte,
104}
105
106#[derive(Debug, Clone)]
107/// Boolean and comparison expression tree used by query builders.
108pub enum Expr {
109    Column(ColumnRef),
110    Value(DatabaseValue),
111    Compare {
112        left: Box<Expr>,
113        op: CompareOp,
114        right: Box<Expr>,
115    },
116    Like {
117        left: Box<Expr>,
118        pattern: Box<Expr>,
119    },
120    In {
121        left: Box<Expr>,
122        values: Vec<DatabaseValue>,
123    },
124    And {
125        left: Box<Expr>,
126        right: Box<Expr>,
127    },
128    Or {
129        left: Box<Expr>,
130        right: Box<Expr>,
131    },
132    Not(Box<Expr>),
133    IsNull(Box<Expr>),
134    IsNotNull(Box<Expr>),
135}
136
137impl Expr {
138    pub fn and(self, other: Expr) -> Expr {
139        Expr::And {
140            left: Box::new(self),
141            right: Box::new(other),
142        }
143    }
144    pub fn or(self, other: Expr) -> Expr {
145        Expr::Or {
146            left: Box::new(self),
147            right: Box::new(other),
148        }
149    }
150    #[allow(clippy::should_implement_trait)]
151    pub fn not(self) -> Expr {
152        Expr::Not(Box::new(self))
153    }
154
155    pub fn like(self, pattern: impl Into<String>) -> Expr {
156        Expr::Like {
157            left: Box::new(self),
158            pattern: Box::new(Expr::Value(DatabaseValue::Text(pattern.into()))),
159        }
160    }
161}
162
163#[derive(Debug, Clone, Copy)]
164/// A typed reference to one model column.
165pub struct ModelField<M, T> {
166    table: &'static str,
167    column: &'static str,
168    _marker: PhantomData<fn() -> (M, T)>,
169}
170
171impl<M, T> ModelField<M, T> {
172    pub const fn new(table: &'static str, column: &'static str) -> Self {
173        Self {
174            table,
175            column,
176            _marker: PhantomData,
177        }
178    }
179
180    pub const fn column(&self) -> ColumnRef {
181        ColumnRef::new(self.table, self.column)
182    }
183
184    fn comparison<V>(self, op: CompareOp, value: V) -> Expr
185    where
186        V: QueryValue<T>,
187    {
188        Expr::Compare {
189            left: Box::new(Expr::Column(self.column())),
190            op,
191            right: Box::new(Expr::Value(value.into_query_value())),
192        }
193    }
194
195    pub fn eq<V>(self, value: V) -> Expr
196    where
197        V: QueryValue<T>,
198    {
199        self.comparison(CompareOp::Eq, value)
200    }
201    pub fn in_values<I, V>(self, values: I) -> Expr
202    where
203        I: IntoIterator<Item = V>,
204        V: QueryValue<T>,
205    {
206        Expr::In {
207            left: Box::new(Expr::Column(self.column())),
208            values: values
209                .into_iter()
210                .map(QueryValue::into_query_value)
211                .collect(),
212        }
213    }
214    pub fn ne<V>(self, value: V) -> Expr
215    where
216        V: QueryValue<T>,
217    {
218        self.comparison(CompareOp::Ne, value)
219    }
220    pub fn gt<V>(self, value: V) -> Expr
221    where
222        V: QueryValue<T>,
223    {
224        self.comparison(CompareOp::Gt, value)
225    }
226    pub fn gte<V>(self, value: V) -> Expr
227    where
228        V: QueryValue<T>,
229    {
230        self.comparison(CompareOp::Gte, value)
231    }
232    pub fn lt<V>(self, value: V) -> Expr
233    where
234        V: QueryValue<T>,
235    {
236        self.comparison(CompareOp::Lt, value)
237    }
238    pub fn lte<V>(self, value: V) -> Expr
239    where
240        V: QueryValue<T>,
241    {
242        self.comparison(CompareOp::Lte, value)
243    }
244    pub fn is_null(self) -> Expr {
245        Expr::IsNull(Box::new(Expr::Column(self.column())))
246    }
247    pub fn is_not_null(self) -> Expr {
248        Expr::IsNotNull(Box::new(Expr::Column(self.column())))
249    }
250
251    pub fn contains(self, value: impl Into<String>) -> Expr {
252        Expr::Column(self.column()).like(format!("%{}%", value.into()))
253    }
254    pub fn asc(self) -> OrderBy {
255        OrderBy {
256            column: self.column(),
257            direction: OrderDirection::Asc,
258        }
259    }
260    pub fn desc(self) -> OrderBy {
261        OrderBy {
262            column: self.column(),
263            direction: OrderDirection::Desc,
264        }
265    }
266}