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    Real(f64),
12    Text(String),
13    Binary(Vec<u8>),
14    Boolean(bool),
15    DateTime(OffsetDateTime),
16    Uuid(uuid::Uuid),
17    Null,
18}
19
20pub trait QueryValue<T> {
21    fn into_query_value(self) -> DatabaseValue;
22}
23
24impl QueryValue<uuid::Uuid> for uuid::Uuid {
25    fn into_query_value(self) -> DatabaseValue {
26        DatabaseValue::Uuid(self)
27    }
28}
29
30/// Supported model keys, including their automatic INSERT value.
31pub trait PrimaryKey:
32    Copy + Eq + std::hash::Hash + Send + Sync + 'static + QueryValue<Self> + crate::FromDatabaseValue
33{
34    fn generated_value() -> Option<DatabaseValue>;
35}
36
37impl PrimaryKey for i64 {
38    fn generated_value() -> Option<DatabaseValue> {
39        None
40    }
41}
42
43impl PrimaryKey for uuid::Uuid {
44    fn generated_value() -> Option<DatabaseValue> {
45        Some(DatabaseValue::Uuid(Self::now_v7()))
46    }
47}
48
49/// Extracts the owner key from a required or nullable foreign-key field.
50pub trait ForeignKeyValue<Key: PrimaryKey>: Copy + Send + 'static {
51    const OPTIONAL: bool;
52    fn owner_key(self) -> Option<Key>;
53}
54
55impl<Key: PrimaryKey> ForeignKeyValue<Key> for Key {
56    const OPTIONAL: bool = false;
57    fn owner_key(self) -> Option<Key> {
58        Some(self)
59    }
60}
61
62impl<Key: PrimaryKey> ForeignKeyValue<Key> for Option<Key> {
63    const OPTIONAL: bool = true;
64    fn owner_key(self) -> Option<Key> {
65        self
66    }
67}
68
69impl QueryValue<i64> for i64 {
70    fn into_query_value(self) -> DatabaseValue {
71        DatabaseValue::Integer(self)
72    }
73}
74
75impl QueryValue<f64> for f64 {
76    fn into_query_value(self) -> DatabaseValue {
77        DatabaseValue::Real(self)
78    }
79}
80
81impl QueryValue<String> for String {
82    fn into_query_value(self) -> DatabaseValue {
83        DatabaseValue::Text(self)
84    }
85}
86
87impl QueryValue<String> for &str {
88    fn into_query_value(self) -> DatabaseValue {
89        DatabaseValue::Text(self.to_owned())
90    }
91}
92
93impl QueryValue<Vec<u8>> for Vec<u8> {
94    fn into_query_value(self) -> DatabaseValue {
95        DatabaseValue::Binary(self)
96    }
97}
98
99impl QueryValue<bool> for bool {
100    fn into_query_value(self) -> DatabaseValue {
101        DatabaseValue::Boolean(self)
102    }
103}
104
105impl QueryValue<OffsetDateTime> for OffsetDateTime {
106    fn into_query_value(self) -> DatabaseValue {
107        DatabaseValue::DateTime(self)
108    }
109}
110
111impl<T: DbEnum> QueryValue<T> for T {
112    fn into_query_value(self) -> DatabaseValue {
113        DatabaseValue::Text(self.as_str().to_owned())
114    }
115}
116
117impl<T, V> QueryValue<Option<T>> for Option<V>
118where
119    V: QueryValue<T>,
120{
121    fn into_query_value(self) -> DatabaseValue {
122        self.map_or(DatabaseValue::Null, QueryValue::into_query_value)
123    }
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub struct TableRef {
128    pub name: &'static str,
129}
130
131impl TableRef {
132    pub const fn new(name: &'static str) -> Self {
133        Self { name }
134    }
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub struct ColumnRef {
139    pub table: &'static str,
140    pub name: &'static str,
141    /// Compare RFC3339 text chronologically on SQLite; other dialects ignore this hint.
142    pub datetime: bool,
143}
144
145impl ColumnRef {
146    pub const fn new(table: &'static str, name: &'static str) -> Self {
147        Self {
148            table,
149            name,
150            datetime: false,
151        }
152    }
153
154    pub const fn datetime(table: &'static str, name: &'static str) -> Self {
155        Self {
156            table,
157            name,
158            datetime: true,
159        }
160    }
161}
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
164pub enum CompareOp {
165    Eq,
166    Ne,
167    Gt,
168    Gte,
169    Lt,
170    Lte,
171}
172
173#[derive(Debug, Clone)]
174/// Boolean and comparison expression tree used by query builders.
175pub enum Expr {
176    Column(ColumnRef),
177    Value(DatabaseValue),
178    Compare {
179        left: Box<Expr>,
180        op: CompareOp,
181        right: Box<Expr>,
182    },
183    Like {
184        left: Box<Expr>,
185        pattern: Box<Expr>,
186    },
187    /// Membership in a single-column SELECT, with native key types.
188    InQuery {
189        left: Box<Expr>,
190        query: Box<crate::SelectAst>,
191    },
192    In {
193        left: Box<Expr>,
194        values: Vec<DatabaseValue>,
195    },
196    And {
197        left: Box<Expr>,
198        right: Box<Expr>,
199    },
200    Or {
201        left: Box<Expr>,
202        right: Box<Expr>,
203    },
204    Not(Box<Expr>),
205    IsNull(Box<Expr>),
206    IsNotNull(Box<Expr>),
207}
208
209impl Expr {
210    pub fn and(self, other: Expr) -> Expr {
211        Expr::And {
212            left: Box::new(self),
213            right: Box::new(other),
214        }
215    }
216    pub fn or(self, other: Expr) -> Expr {
217        Expr::Or {
218            left: Box::new(self),
219            right: Box::new(other),
220        }
221    }
222    #[allow(clippy::should_implement_trait)]
223    pub fn not(self) -> Expr {
224        Expr::Not(Box::new(self))
225    }
226
227    pub fn like(self, pattern: impl Into<String>) -> Expr {
228        Expr::Like {
229            left: Box::new(self),
230            pattern: Box::new(Expr::Value(DatabaseValue::Text(pattern.into()))),
231        }
232    }
233}
234
235#[derive(Debug, Clone, Copy)]
236/// A typed reference to one model column.
237pub struct ModelField<M, T> {
238    table: &'static str,
239    column: &'static str,
240    datetime: bool,
241    _marker: PhantomData<fn() -> (M, T)>,
242}
243
244impl<M, T> ModelField<M, T> {
245    pub const fn new(table: &'static str, column: &'static str) -> Self {
246        Self {
247            table,
248            column,
249            datetime: false,
250            _marker: PhantomData,
251        }
252    }
253
254    /// Constructs a timestamp field, including nullable timestamps.
255    pub const fn datetime(table: &'static str, column: &'static str) -> Self {
256        Self {
257            table,
258            column,
259            datetime: true,
260            _marker: PhantomData,
261        }
262    }
263
264    pub const fn column(&self) -> ColumnRef {
265        ColumnRef {
266            table: self.table,
267            name: self.column,
268            datetime: self.datetime,
269        }
270    }
271
272    fn comparison<V>(self, op: CompareOp, value: V) -> Expr
273    where
274        V: QueryValue<T>,
275    {
276        Expr::Compare {
277            left: Box::new(Expr::Column(self.column())),
278            op,
279            right: Box::new(Expr::Value(value.into_query_value())),
280        }
281    }
282
283    pub fn eq<V>(self, value: V) -> Expr
284    where
285        V: QueryValue<T>,
286    {
287        self.comparison(CompareOp::Eq, value)
288    }
289    pub fn in_values<I, V>(self, values: I) -> Expr
290    where
291        I: IntoIterator<Item = V>,
292        V: QueryValue<T>,
293    {
294        Expr::In {
295            left: Box::new(Expr::Column(self.column())),
296            values: values
297                .into_iter()
298                .map(QueryValue::into_query_value)
299                .collect(),
300        }
301    }
302    pub fn ne<V>(self, value: V) -> Expr
303    where
304        V: QueryValue<T>,
305    {
306        self.comparison(CompareOp::Ne, value)
307    }
308    pub fn gt<V>(self, value: V) -> Expr
309    where
310        V: QueryValue<T>,
311    {
312        self.comparison(CompareOp::Gt, value)
313    }
314    pub fn gte<V>(self, value: V) -> Expr
315    where
316        V: QueryValue<T>,
317    {
318        self.comparison(CompareOp::Gte, value)
319    }
320    pub fn lt<V>(self, value: V) -> Expr
321    where
322        V: QueryValue<T>,
323    {
324        self.comparison(CompareOp::Lt, value)
325    }
326    pub fn lte<V>(self, value: V) -> Expr
327    where
328        V: QueryValue<T>,
329    {
330        self.comparison(CompareOp::Lte, value)
331    }
332    pub fn is_null(self) -> Expr {
333        Expr::IsNull(Box::new(Expr::Column(self.column())))
334    }
335    pub fn is_not_null(self) -> Expr {
336        Expr::IsNotNull(Box::new(Expr::Column(self.column())))
337    }
338
339    pub fn contains(self, value: impl Into<String>) -> Expr {
340        Expr::Column(self.column()).like(format!("%{}%", value.into()))
341    }
342    pub fn asc(self) -> OrderBy {
343        OrderBy {
344            column: self.column(),
345            direction: OrderDirection::Asc,
346        }
347    }
348    pub fn desc(self) -> OrderBy {
349        OrderBy {
350            column: self.column(),
351            direction: OrderDirection::Desc,
352        }
353    }
354}