rust_query/
writable.rs

1use std::marker::PhantomData;
2
3use crate::{
4    Expr, IntoExpr, Table,
5    value::{DynTypedExpr, NumTyp},
6};
7
8/// Defines a column update.
9pub struct Update<'t, S, Typ> {
10    inner: Box<dyn 't + Fn(Expr<'t, S, Typ>) -> Expr<'t, S, Typ>>,
11}
12
13impl<S, Typ> Default for Update<'_, S, Typ> {
14    fn default() -> Self {
15        Self {
16            inner: Box::new(|x| x),
17        }
18    }
19}
20
21impl<'t, S: 't, Typ: 't> Update<'t, S, Typ> {
22    /// Set the new value of the column.
23    pub fn set(val: impl IntoExpr<'t, S, Typ = Typ>) -> Self {
24        let val = val.into_expr();
25        Self {
26            inner: Box::new(move |_| val.clone()),
27        }
28    }
29
30    #[doc(hidden)]
31    pub fn apply(&self, val: impl IntoExpr<'t, S, Typ = Typ>) -> Expr<'t, S, Typ> {
32        (self.inner)(val.into_expr())
33    }
34}
35
36impl<'t, S: 't, Typ: NumTyp> Update<'t, S, Typ> {
37    /// Update the column value to the old value plus some new value.
38    pub fn add(val: impl IntoExpr<'t, S, Typ = Typ>) -> Self {
39        let val = val.into_expr();
40        Self {
41            inner: Box::new(move |old| old.add(&val)),
42        }
43    }
44}
45
46/// this trait has to be implemented by the `schema` macro.
47pub trait TableInsert<'t> {
48    type T: Table;
49    fn into_insert(self) -> <Self::T as Table>::Insert<'t>;
50}
51
52pub struct Reader<'t, S> {
53    pub(crate) builder: Vec<(&'static str, DynTypedExpr)>,
54    pub(crate) _p: PhantomData<S>,
55    pub(crate) _p2: PhantomData<fn(&'t ()) -> &'t ()>,
56}
57
58impl<'t, S> Default for Reader<'t, S> {
59    fn default() -> Self {
60        Self {
61            builder: Default::default(),
62            _p: Default::default(),
63            _p2: Default::default(),
64        }
65    }
66}
67
68impl<'t, S> Reader<'t, S> {
69    pub fn col(&mut self, name: &'static str, val: impl IntoExpr<'t, S>) {
70        self.col_erased(name, val.into_expr().inner.erase());
71    }
72
73    pub(crate) fn col_erased(&mut self, name: &'static str, val: DynTypedExpr) {
74        self.builder.push((name, val));
75    }
76}