Skip to main content

fastauth_core/
query.rs

1//! The typed query builder plugins use through `ctx.db()`.
2
3use std::marker::PhantomData;
4use std::sync::Arc;
5
6use crate::adapter::{
7    DbError, DbResult, Delete, Filter, Insert, Op, Order, Queries, Select, Update,
8};
9use crate::model::{Col, Model, OnTable};
10use crate::schema::{DefaultValue, Schema, TableDef};
11use crate::value::{ColumnValue, Row, Value};
12
13#[derive(Clone, Debug, PartialEq)]
14enum Expr {
15    All,
16    Cmp(&'static str, Op, Value),
17    In(&'static str, Vec<Value>),
18    Null(&'static str, bool),
19    StartsWith(&'static str, String),
20    Contains(&'static str, String),
21    EndsWith(&'static str, String),
22    And(Vec<Expr>),
23    Or(Vec<Expr>),
24}
25
26/// A filter on model `M`'s table, built from typed columns.
27#[derive(Clone, Debug, PartialEq)]
28pub struct Where<M> {
29    expr: Expr,
30    _model: PhantomData<fn() -> M>,
31}
32
33impl<M> Where<M> {
34    fn wrap(expr: Expr) -> Self {
35        Self {
36            expr,
37            _model: PhantomData,
38        }
39    }
40
41    pub fn all() -> Self {
42        Self::wrap(Expr::All)
43    }
44
45    pub(crate) fn cmp(column: &'static str, op: Op, value: Value) -> Self {
46        Self::wrap(Expr::Cmp(column, op, value))
47    }
48
49    pub(crate) fn in_list(column: &'static str, values: Vec<Value>) -> Self {
50        Self::wrap(Expr::In(column, values))
51    }
52
53    pub(crate) fn null(column: &'static str, is_null: bool) -> Self {
54        Self::wrap(Expr::Null(column, is_null))
55    }
56
57    pub(crate) fn starts_with(column: &'static str, prefix: String) -> Self {
58        Self::wrap(Expr::StartsWith(column, prefix))
59    }
60
61    pub(crate) fn contains(column: &'static str, substring: String) -> Self {
62        Self::wrap(Expr::Contains(column, substring))
63    }
64
65    pub(crate) fn ends_with(column: &'static str, suffix: String) -> Self {
66        Self::wrap(Expr::EndsWith(column, suffix))
67    }
68
69    pub fn and(self, other: Where<M>) -> Self {
70        Self::wrap(Expr::And(vec![self.expr, other.expr]))
71    }
72
73    pub fn or(self, other: Where<M>) -> Self {
74        Self::wrap(Expr::Or(vec![self.expr, other.expr]))
75    }
76
77    pub(crate) fn resolve(&self, table: &TableDef) -> DbResult<Filter> {
78        resolve(&self.expr, table)
79    }
80}
81
82fn position(table: &TableDef, column: &str) -> DbResult<usize> {
83    table
84        .position(column)
85        .ok_or_else(|| DbError::Schema(format!("`{}` has no column `{column}`", table.name)))
86}
87
88fn resolve(expr: &Expr, table: &TableDef) -> DbResult<Filter> {
89    Ok(match expr {
90        Expr::All => Filter::All,
91        Expr::Cmp(c, op, v) => Filter::Cmp {
92            column: position(table, c)?,
93            op: *op,
94            value: v.clone(),
95        },
96        Expr::In(c, vs) => Filter::In {
97            column: position(table, c)?,
98            values: vs.clone(),
99        },
100        Expr::Null(c, n) => Filter::Null {
101            column: position(table, c)?,
102            is_null: *n,
103        },
104        Expr::StartsWith(c, p) => Filter::StartsWith {
105            column: position(table, c)?,
106            prefix: p.clone(),
107        },
108        Expr::Contains(c, s) => Filter::Contains {
109            column: position(table, c)?,
110            substring: s.clone(),
111        },
112        Expr::EndsWith(c, s) => Filter::EndsWith {
113            column: position(table, c)?,
114            suffix: s.clone(),
115        },
116        Expr::And(es) => Filter::And(
117            es.iter()
118                .map(|e| resolve(e, table))
119                .collect::<DbResult<_>>()?,
120        ),
121        Expr::Or(es) => Filter::Or(
122            es.iter()
123                .map(|e| resolve(e, table))
124                .collect::<DbResult<_>>()?,
125        ),
126    })
127}
128
129/// Builds a full row for `table`: given values, then defaults, then NULL.
130pub(crate) fn full_row(table: &TableDef, given: Vec<(&str, Value)>) -> DbResult<Vec<Value>> {
131    let mut values: Vec<Option<Value>> = vec![None; table.columns.len()];
132    for (name, value) in given {
133        values[position(table, name)?] = Some(value);
134    }
135    let now = time::OffsetDateTime::now_utc();
136    table
137        .columns
138        .iter()
139        .zip(values)
140        .map(|(column, value)| {
141            Ok(match (value, column.default) {
142                (Some(v), _) => v,
143                (None, Some(DefaultValue::Bool(b))) => Value::Bool(b),
144                (None, Some(DefaultValue::Int(i))) => Value::Int(i),
145                (None, Some(DefaultValue::Text(s))) => Value::Text(s.to_owned()),
146                (None, Some(DefaultValue::Now)) => Value::Timestamp(now),
147                (None, None) if column.nullable => Value::Null,
148                (None, None) => {
149                    return Err(DbError::Schema(format!(
150                        "`{}.{}` needs a value",
151                        table.name, column.name
152                    )));
153                }
154            })
155        })
156        .collect()
157}
158
159/// Typed access to the database, over the adapter or a transaction.
160pub struct Db<'a, Q: ?Sized> {
161    queries: &'a Q,
162    schema: &'a Schema,
163}
164
165impl<Q: ?Sized> Clone for Db<'_, Q> {
166    fn clone(&self) -> Self {
167        *self
168    }
169}
170
171impl<Q: ?Sized> Copy for Db<'_, Q> {}
172
173impl<'a, Q: Queries + ?Sized> Db<'a, Q> {
174    pub fn new(queries: &'a Q, schema: &'a Schema) -> Self {
175        Self { queries, schema }
176    }
177
178    pub fn schema(&self) -> &'a Schema {
179        self.schema
180    }
181
182    pub fn raw(&self) -> &'a Q {
183        self.queries
184    }
185
186    fn table<M: Model>(&self) -> DbResult<&'a Arc<TableDef>> {
187        self.schema
188            .table(M::TABLE)
189            .ok_or_else(|| DbError::Schema(format!("table `{}` is not registered", M::TABLE)))
190    }
191
192    pub fn find<M: Model>(&self, filter: Where<M>) -> Find<'a, Q, M> {
193        Find {
194            db: *self,
195            filter,
196            order: Vec::new(),
197            limit: None,
198            offset: None,
199        }
200    }
201
202    pub async fn insert<M: Model>(&self, model: &M) -> DbResult<M> {
203        let table = self.table::<M>()?;
204        let values = full_row(table, model.encode())?;
205        let row = self.queries.insert(Insert { table, values }).await?;
206        Ok(M::decode(&row)?)
207    }
208
209    /// Inserts raw column values into `M`'s table, filling defaults. Returns the stored row.
210    pub async fn insert_row<M: Model>(&self, values: Vec<(&str, Value)>) -> DbResult<Row> {
211        let table = self.table::<M>()?;
212        let values = full_row(table, values)?;
213        self.queries.insert(Insert { table, values }).await
214    }
215
216    pub fn update<M: Model>(&self, filter: Where<M>) -> UpdateBuilder<'a, Q, M> {
217        UpdateBuilder {
218            db: *self,
219            filter,
220            set: Vec::new(),
221        }
222    }
223
224    pub async fn delete<M: Model>(&self, filter: Where<M>) -> DbResult<u64> {
225        let table = self.table::<M>()?;
226        let filter = filter.resolve(table)?;
227        self.queries.delete(Delete { table, filter }).await
228    }
229
230    pub async fn count<M: Model>(&self, filter: Where<M>) -> DbResult<u64> {
231        let table = self.table::<M>()?;
232        let filter = filter.resolve(table)?;
233        self.queries
234            .count(Select {
235                table,
236                filter,
237                order: Vec::new(),
238                limit: None,
239                offset: None,
240            })
241            .await
242    }
243}
244
245pub struct Find<'a, Q: ?Sized, M> {
246    db: Db<'a, Q>,
247    filter: Where<M>,
248    order: Vec<(&'static str, Order)>,
249    limit: Option<u64>,
250    offset: Option<u64>,
251}
252
253impl<'a, Q: Queries + ?Sized, M: Model> Find<'a, Q, M> {
254    pub fn order_by(mut self, (column, order): (&'static str, Order)) -> Self {
255        self.order.push((column, order));
256        self
257    }
258
259    pub fn limit(mut self, limit: u64) -> Self {
260        self.limit = Some(limit);
261        self
262    }
263
264    pub fn offset(mut self, offset: u64) -> Self {
265        self.offset = Some(offset);
266        self
267    }
268
269    fn select(&self, limit: Option<u64>) -> DbResult<Select<'a>> {
270        let table = self.db.table::<M>()?;
271        let order = self
272            .order
273            .iter()
274            .map(|(c, o)| Ok((position(table, c)?, *o)))
275            .collect::<DbResult<_>>()?;
276        Ok(Select {
277            table,
278            filter: self.filter.resolve(table)?,
279            order,
280            limit,
281            offset: self.offset,
282        })
283    }
284
285    pub async fn one(self) -> DbResult<Option<M>> {
286        Ok(self.one_row().await?.map(|r| M::decode(&r)).transpose()?)
287    }
288
289    pub async fn all(self) -> DbResult<Vec<M>> {
290        let rows = self.db.queries.find_many(self.select(self.limit)?).await?;
291        Ok(rows.iter().map(M::decode).collect::<Result<_, _>>()?)
292    }
293
294    /// The raw row, including columns plugins added (decode them with `Fields::decode`).
295    pub async fn one_row(self) -> DbResult<Option<Row>> {
296        self.db.queries.find_one(self.select(Some(1))?).await
297    }
298
299    pub async fn all_rows(self) -> DbResult<Vec<Row>> {
300        self.db.queries.find_many(self.select(self.limit)?).await
301    }
302}
303
304pub struct UpdateBuilder<'a, Q: ?Sized, M> {
305    db: Db<'a, Q>,
306    filter: Where<M>,
307    set: Vec<(&'static str, Value)>,
308}
309
310impl<Q: Queries + ?Sized, M: Model> UpdateBuilder<'_, Q, M> {
311    pub fn set<O: OnTable<Table = M>, T: ColumnValue>(
312        mut self,
313        column: Col<O, T>,
314        value: impl Into<T>,
315    ) -> Self {
316        self.set.push((column.name(), value.into().into_value()));
317        self
318    }
319
320    /// Sets a column by name, for values whose column isn't known at compile time.
321    pub fn set_raw(mut self, column: &'static str, value: Value) -> Self {
322        self.set.push((column, value));
323        self
324    }
325
326    pub async fn exec(self) -> DbResult<u64> {
327        let table = self.db.table::<M>()?;
328        let mut set = self
329            .set
330            .iter()
331            .map(|(c, v)| Ok((position(table, c)?, v.clone())))
332            .collect::<DbResult<Vec<_>>>()?;
333        if let Some(updated_at) = table.position("updated_at")
334            && !set.iter().any(|(i, _)| *i == updated_at)
335        {
336            set.push((
337                updated_at,
338                Value::Timestamp(time::OffsetDateTime::now_utc()),
339            ));
340        }
341        let filter = self.filter.resolve(table)?;
342        self.db.queries.update(Update { table, filter, set }).await
343    }
344}