Skip to main content

fastauth_core/
schema.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
5pub enum ColumnType {
6    Id,
7    Text,
8    Bool,
9    Int,
10    Timestamp,
11    Json,
12    Bytes,
13}
14
15/// How [`ColumnType::Id`] columns are stored. The configured
16/// [`IdStrategy`](crate::config::IdStrategy) decides it, and adapters read it from
17/// [`Schema::id_storage`] or [`TableDef::id_storage`] when they create columns and bind ids.
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
19pub enum IdStorage {
20    /// The database's native UUID type where it has one (Postgres `uuid`), else text.
21    Uuid,
22    /// Text on every database.
23    #[default]
24    Text,
25}
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum DefaultValue {
29    Bool(bool),
30    Int(i64),
31    Text(&'static str),
32    /// The current time at insert.
33    Now,
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum OnDelete {
38    Cascade,
39    SetNull,
40    Restrict,
41}
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub struct Reference {
45    pub table: &'static str,
46    pub column: &'static str,
47    pub on_delete: OnDelete,
48}
49
50/// One column. Built with const fns so `Fields` and `Model` impls can return `&'static [ColumnDef]`.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub struct ColumnDef {
53    pub name: &'static str,
54    pub ty: ColumnType,
55    pub nullable: bool,
56    pub primary_key: bool,
57    pub unique: bool,
58    pub index: bool,
59    pub default: Option<DefaultValue>,
60    pub references: Option<Reference>,
61    /// Clients may set it through sign-up and update-user bodies.
62    pub input: bool,
63    /// Serialized to clients.
64    pub returned: bool,
65    /// The plugin id, `"core"` or `"app"`. Filled in when the column joins the schema.
66    pub owner: &'static str,
67}
68
69impl ColumnDef {
70    pub const fn new(name: &'static str, ty: ColumnType) -> Self {
71        Self {
72            name,
73            ty,
74            nullable: false,
75            primary_key: false,
76            unique: false,
77            index: false,
78            default: None,
79            references: None,
80            input: false,
81            returned: true,
82            owner: "",
83        }
84    }
85
86    pub const fn primary_key(mut self) -> Self {
87        self.primary_key = true;
88        self
89    }
90
91    pub const fn nullable(mut self) -> Self {
92        self.nullable = true;
93        self
94    }
95
96    pub const fn unique(mut self) -> Self {
97        self.unique = true;
98        self
99    }
100
101    pub const fn index(mut self) -> Self {
102        self.index = true;
103        self
104    }
105
106    pub const fn default(mut self, value: DefaultValue) -> Self {
107        self.default = Some(value);
108        self
109    }
110
111    pub const fn references(
112        mut self,
113        table: &'static str,
114        column: &'static str,
115        on_delete: OnDelete,
116    ) -> Self {
117        self.references = Some(Reference {
118            table,
119            column,
120            on_delete,
121        });
122        self
123    }
124
125    pub const fn input(mut self) -> Self {
126        self.input = true;
127        self
128    }
129
130    pub const fn hidden(mut self) -> Self {
131        self.returned = false;
132        self
133    }
134}
135
136/// A unique constraint over several columns of one table, added with
137/// [`SchemaBuilder::unique`]. A single unique column is [`ColumnDef::unique`] instead.
138#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct UniqueDef {
140    pub columns: Vec<&'static str>,
141    /// The plugin id, `"core"` or `"app"`.
142    pub owner: &'static str,
143}
144
145#[derive(Clone, Debug, PartialEq, Eq)]
146pub struct TableDef {
147    pub name: &'static str,
148    pub owner: &'static str,
149    pub columns: Vec<ColumnDef>,
150    /// Unique constraints over several columns. Single unique columns aren't listed here.
151    pub uniques: Vec<UniqueDef>,
152    positions: HashMap<&'static str, usize>,
153    id_storage: IdStorage,
154}
155
156impl TableDef {
157    fn new(name: &'static str, owner: &'static str) -> Self {
158        Self {
159            name,
160            owner,
161            columns: Vec::new(),
162            uniques: Vec::new(),
163            positions: HashMap::new(),
164            id_storage: IdStorage::default(),
165        }
166    }
167
168    /// How this table's [`ColumnType::Id`] columns are stored; the same for every table
169    /// in a schema.
170    pub fn id_storage(&self) -> IdStorage {
171        self.id_storage
172    }
173
174    pub fn position(&self, column: &str) -> Option<usize> {
175        self.positions.get(column).copied()
176    }
177
178    pub fn column(&self, column: &str) -> Option<&ColumnDef> {
179        self.position(column).map(|i| &self.columns[i])
180    }
181
182    pub fn primary_key(&self) -> Option<&ColumnDef> {
183        self.columns.iter().find(|c| c.primary_key)
184    }
185
186    /// Every set of columns the database keeps unique, primary key aside: each unique
187    /// column on its own, then each [`UniqueDef`].
188    pub fn unique_sets(&self) -> impl Iterator<Item = Vec<&'static str>> + '_ {
189        self.columns
190            .iter()
191            .filter(|c| c.unique && !c.primary_key)
192            .map(|c| vec![c.name])
193            .chain(self.uniques.iter().map(|u| u.columns.clone()))
194    }
195}
196
197/// The merged schema for one configuration: core tables, app fields, every plugin's tables
198/// and columns. Immutable after `.build()`.
199#[derive(Clone, Debug, Default)]
200pub struct Schema {
201    tables: Vec<Arc<TableDef>>,
202    by_name: HashMap<&'static str, usize>,
203    id_storage: IdStorage,
204}
205
206impl Schema {
207    /// How [`ColumnType::Id`] columns are stored, from the configured id strategy.
208    pub fn id_storage(&self) -> IdStorage {
209        self.id_storage
210    }
211
212    pub fn tables(&self) -> &[Arc<TableDef>] {
213        &self.tables
214    }
215
216    pub fn table(&self, name: &str) -> Option<&Arc<TableDef>> {
217        self.by_name.get(name).map(|&i| &self.tables[i])
218    }
219
220    /// Panics on a table name the schema doesn't have. Only for core's own tables and
221    /// models whose table was registered (checked at build time).
222    pub fn expect(&self, name: &str) -> &Arc<TableDef> {
223        self.table(name)
224            .unwrap_or_else(|| panic!("fastauth: table `{name}` is not in the schema"))
225    }
226}
227
228/// Collects tables and columns during `.build()` and reports clashes with both owners.
229#[derive(Debug, Default)]
230pub struct SchemaBuilder {
231    tables: Vec<TableDef>,
232    pub(crate) owner: &'static str,
233    pub(crate) errors: Vec<String>,
234}
235
236impl SchemaBuilder {
237    pub(crate) fn new() -> Self {
238        Self {
239            owner: "core",
240            ..Self::default()
241        }
242    }
243
244    /// Adds a new table owned by the current plugin.
245    pub fn table(&mut self, name: &'static str, columns: &[ColumnDef]) -> &mut Self {
246        if let Some(existing) = self.tables.iter().find(|t| t.name == name) {
247            self.errors.push(format!(
248                "table `{name}` is defined by both `{}` and `{}`",
249                existing.owner, self.owner
250            ));
251            return self;
252        }
253        self.tables.push(TableDef::new(name, self.owner));
254        self.extend(name, columns)
255    }
256
257    /// Adds columns to an existing table (usually `user` or `session`).
258    pub fn extend(&mut self, table: &'static str, columns: &[ColumnDef]) -> &mut Self {
259        let owner = self.owner;
260        let Some(def) = self.tables.iter_mut().find(|t| t.name == table) else {
261            self.errors
262                .push(format!("`{owner}` adds columns to unknown table `{table}`"));
263            return self;
264        };
265        for column in columns {
266            if let Some(clash) = def.column(column.name) {
267                self.errors.push(format!(
268                    "column `{table}.{}` is defined by both `{}` and `{owner}`",
269                    column.name, clash.owner
270                ));
271                continue;
272            }
273            let mut column = *column;
274            column.owner = owner;
275            def.positions.insert(column.name, def.columns.len());
276            def.columns.push(column);
277        }
278        self
279    }
280
281    /// Makes `columns` of `table` unique together, enforced by the database. Adapters
282    /// report a violation as `DbError::UniqueViolation` on `table` with no column.
283    pub fn unique(&mut self, table: &'static str, columns: &[&'static str]) -> &mut Self {
284        let owner = self.owner;
285        let Some(def) = self.tables.iter_mut().find(|t| t.name == table) else {
286            self.errors.push(format!(
287                "`{owner}` adds a unique constraint to unknown table `{table}`"
288            ));
289            return self;
290        };
291        if columns.len() < 2 {
292            self.errors.push(format!(
293                "`{owner}`: a unique constraint on `{table}` needs two or more columns; \
294                 use `ColumnDef::unique` for one"
295            ));
296            return self;
297        }
298        if let Some(missing) = columns.iter().find(|c| def.column(c).is_none()) {
299            self.errors.push(format!(
300                "`{owner}` adds a unique constraint on missing column `{table}.{missing}`"
301            ));
302            return self;
303        }
304        if !def.uniques.iter().any(|u| u.columns == columns) {
305            def.uniques.push(UniqueDef {
306                columns: columns.to_vec(),
307                owner,
308            });
309        }
310        self
311    }
312
313    /// Registers a model's table.
314    pub fn model<M: crate::model::Model>(&mut self) -> &mut Self {
315        self.table(M::TABLE, M::columns())
316    }
317
318    pub(crate) fn finish(self, id_storage: IdStorage) -> Result<Schema, Vec<String>> {
319        let mut errors = self.errors;
320        for table in &self.tables {
321            for column in &table.columns {
322                if let Some(r) = column.references {
323                    let target = self.tables.iter().find(|t| t.name == r.table);
324                    if target.and_then(|t| t.column(r.column)).is_none() {
325                        errors.push(format!(
326                            "column `{}.{}` references missing `{}.{}`",
327                            table.name, column.name, r.table, r.column
328                        ));
329                    }
330                }
331            }
332        }
333        if !errors.is_empty() {
334            return Err(errors);
335        }
336        let by_name = self
337            .tables
338            .iter()
339            .enumerate()
340            .map(|(i, t)| (t.name, i))
341            .collect();
342        Ok(Schema {
343            tables: self
344                .tables
345                .into_iter()
346                .map(|mut table| {
347                    table.id_storage = id_storage;
348                    Arc::new(table)
349                })
350                .collect(),
351            by_name,
352            id_storage,
353        })
354    }
355}