Skip to main content

fastauth_core/
model.rs

1use std::marker::PhantomData;
2
3use crate::query::Where;
4use crate::schema::ColumnDef;
5use crate::value::{ColumnValue, DecodeError, Row, Value};
6
7/// A typed view over some columns of an existing table (`user` or `session`).
8/// The app's `.user_fields::<U>()` and each plugin's `UserFields`/`SessionFields` implement it.
9/// `#[derive(Fields)]` writes this.
10pub trait Fields: Clone + Send + Sync + 'static {
11    fn columns() -> &'static [ColumnDef];
12    fn decode(row: &Row) -> Result<Self, DecodeError>;
13}
14
15impl Fields for () {
16    fn columns() -> &'static [ColumnDef] {
17        &[]
18    }
19    fn decode(_: &Row) -> Result<(), DecodeError> {
20        Ok(())
21    }
22}
23
24/// A table owned by core or a plugin. `#[derive(Model)]` writes this.
25pub trait Model: Sized + Send + Sync + 'static {
26    const TABLE: &'static str;
27    fn columns() -> &'static [ColumnDef];
28    fn decode(row: &Row) -> Result<Self, DecodeError>;
29    /// Column values for an insert. Columns not listed get their default or NULL.
30    fn encode(&self) -> Vec<(&'static str, Value)>;
31}
32
33/// Which table a typed column lives on. Models point at themselves; `Fields` point at the
34/// table they extend, so `TwoFactorUser::TWO_FACTOR_ENABLED` can filter `find::<User>`.
35pub trait OnTable {
36    type Table: Model;
37}
38
39/// A typed column: comparing it with the wrong Rust type, or using it on another table,
40/// does not compile.
41pub struct Col<O, T> {
42    name: &'static str,
43    _marker: PhantomData<fn() -> (O, T)>,
44}
45
46impl<O, T> Clone for Col<O, T> {
47    fn clone(&self) -> Self {
48        *self
49    }
50}
51
52impl<O, T> Copy for Col<O, T> {}
53
54impl<O, T> std::fmt::Debug for Col<O, T> {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        write!(f, "Col({})", self.name)
57    }
58}
59
60impl<O: OnTable, T: ColumnValue> Col<O, T> {
61    pub const fn new(name: &'static str) -> Self {
62        Self {
63            name,
64            _marker: PhantomData,
65        }
66    }
67
68    pub const fn name(&self) -> &'static str {
69        self.name
70    }
71
72    /// The column paired with a value, for raw column lists such as a social profile mapping.
73    pub fn value(self, value: impl Into<T>) -> (&'static str, Value) {
74        (self.name, value.into().into_value())
75    }
76
77    pub fn eq(self, value: impl Into<T>) -> Where<O::Table> {
78        Where::cmp(self.name, crate::adapter::Op::Eq, value.into().into_value())
79    }
80
81    pub fn ne(self, value: impl Into<T>) -> Where<O::Table> {
82        Where::cmp(self.name, crate::adapter::Op::Ne, value.into().into_value())
83    }
84
85    pub fn lt(self, value: impl Into<T>) -> Where<O::Table> {
86        Where::cmp(self.name, crate::adapter::Op::Lt, value.into().into_value())
87    }
88
89    pub fn lte(self, value: impl Into<T>) -> Where<O::Table> {
90        Where::cmp(
91            self.name,
92            crate::adapter::Op::Lte,
93            value.into().into_value(),
94        )
95    }
96
97    pub fn gt(self, value: impl Into<T>) -> Where<O::Table> {
98        Where::cmp(self.name, crate::adapter::Op::Gt, value.into().into_value())
99    }
100
101    pub fn gte(self, value: impl Into<T>) -> Where<O::Table> {
102        Where::cmp(
103            self.name,
104            crate::adapter::Op::Gte,
105            value.into().into_value(),
106        )
107    }
108
109    pub fn in_(self, values: impl IntoIterator<Item = T>) -> Where<O::Table> {
110        Where::in_list(
111            self.name,
112            values.into_iter().map(ColumnValue::into_value).collect(),
113        )
114    }
115
116    pub fn is_null(self) -> Where<O::Table> {
117        Where::null(self.name, true)
118    }
119
120    pub fn is_not_null(self) -> Where<O::Table> {
121        Where::null(self.name, false)
122    }
123
124    pub fn asc(self) -> (&'static str, crate::adapter::Order) {
125        (self.name, crate::adapter::Order::Asc)
126    }
127
128    pub fn desc(self) -> (&'static str, crate::adapter::Order) {
129        (self.name, crate::adapter::Order::Desc)
130    }
131}
132
133/// Case-sensitive text matches. The string matches literally: `%`, `_` and `*` are not
134/// wildcards.
135impl<O: OnTable> Col<O, String> {
136    pub fn starts_with(self, prefix: impl Into<String>) -> Where<O::Table> {
137        Where::starts_with(self.name, prefix.into())
138    }
139
140    pub fn contains(self, substring: impl Into<String>) -> Where<O::Table> {
141        Where::contains(self.name, substring.into())
142    }
143
144    pub fn ends_with(self, suffix: impl Into<String>) -> Where<O::Table> {
145        Where::ends_with(self.name, suffix.into())
146    }
147}