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#[derive(Clone, Debug, PartialEq, Eq)]
137pub struct TableDef {
138    pub name: &'static str,
139    pub owner: &'static str,
140    pub columns: Vec<ColumnDef>,
141    positions: HashMap<&'static str, usize>,
142    id_storage: IdStorage,
143}
144
145impl TableDef {
146    fn new(name: &'static str, owner: &'static str) -> Self {
147        Self {
148            name,
149            owner,
150            columns: Vec::new(),
151            positions: HashMap::new(),
152            id_storage: IdStorage::default(),
153        }
154    }
155
156    /// How this table's [`ColumnType::Id`] columns are stored; the same for every table
157    /// in a schema.
158    pub fn id_storage(&self) -> IdStorage {
159        self.id_storage
160    }
161
162    pub fn position(&self, column: &str) -> Option<usize> {
163        self.positions.get(column).copied()
164    }
165
166    pub fn column(&self, column: &str) -> Option<&ColumnDef> {
167        self.position(column).map(|i| &self.columns[i])
168    }
169
170    pub fn primary_key(&self) -> Option<&ColumnDef> {
171        self.columns.iter().find(|c| c.primary_key)
172    }
173}
174
175/// The merged schema for one configuration: core tables, app fields, every plugin's tables
176/// and columns. Immutable after `.build()`.
177#[derive(Clone, Debug, Default)]
178pub struct Schema {
179    tables: Vec<Arc<TableDef>>,
180    by_name: HashMap<&'static str, usize>,
181    id_storage: IdStorage,
182}
183
184impl Schema {
185    /// How [`ColumnType::Id`] columns are stored, from the configured id strategy.
186    pub fn id_storage(&self) -> IdStorage {
187        self.id_storage
188    }
189
190    pub fn tables(&self) -> &[Arc<TableDef>] {
191        &self.tables
192    }
193
194    pub fn table(&self, name: &str) -> Option<&Arc<TableDef>> {
195        self.by_name.get(name).map(|&i| &self.tables[i])
196    }
197
198    /// Panics on a table name the schema doesn't have. Only for core's own tables and
199    /// models whose table was registered (checked at build time).
200    pub fn expect(&self, name: &str) -> &Arc<TableDef> {
201        self.table(name)
202            .unwrap_or_else(|| panic!("fastauth: table `{name}` is not in the schema"))
203    }
204}
205
206/// Collects tables and columns during `.build()` and reports clashes with both owners.
207#[derive(Debug, Default)]
208pub struct SchemaBuilder {
209    tables: Vec<TableDef>,
210    pub(crate) owner: &'static str,
211    pub(crate) errors: Vec<String>,
212}
213
214impl SchemaBuilder {
215    pub(crate) fn new() -> Self {
216        Self {
217            owner: "core",
218            ..Self::default()
219        }
220    }
221
222    /// Adds a new table owned by the current plugin.
223    pub fn table(&mut self, name: &'static str, columns: &[ColumnDef]) -> &mut Self {
224        if let Some(existing) = self.tables.iter().find(|t| t.name == name) {
225            self.errors.push(format!(
226                "table `{name}` is defined by both `{}` and `{}`",
227                existing.owner, self.owner
228            ));
229            return self;
230        }
231        self.tables.push(TableDef::new(name, self.owner));
232        self.extend(name, columns)
233    }
234
235    /// Adds columns to an existing table (usually `user` or `session`).
236    pub fn extend(&mut self, table: &'static str, columns: &[ColumnDef]) -> &mut Self {
237        let owner = self.owner;
238        let Some(def) = self.tables.iter_mut().find(|t| t.name == table) else {
239            self.errors
240                .push(format!("`{owner}` adds columns to unknown table `{table}`"));
241            return self;
242        };
243        for column in columns {
244            if let Some(clash) = def.column(column.name) {
245                self.errors.push(format!(
246                    "column `{table}.{}` is defined by both `{}` and `{owner}`",
247                    column.name, clash.owner
248                ));
249                continue;
250            }
251            let mut column = *column;
252            column.owner = owner;
253            def.positions.insert(column.name, def.columns.len());
254            def.columns.push(column);
255        }
256        self
257    }
258
259    /// Registers a model's table.
260    pub fn model<M: crate::model::Model>(&mut self) -> &mut Self {
261        self.table(M::TABLE, M::columns())
262    }
263
264    pub(crate) fn finish(self, id_storage: IdStorage) -> Result<Schema, Vec<String>> {
265        let mut errors = self.errors;
266        for table in &self.tables {
267            for column in &table.columns {
268                if let Some(r) = column.references {
269                    let target = self.tables.iter().find(|t| t.name == r.table);
270                    if target.and_then(|t| t.column(r.column)).is_none() {
271                        errors.push(format!(
272                            "column `{}.{}` references missing `{}.{}`",
273                            table.name, column.name, r.table, r.column
274                        ));
275                    }
276                }
277            }
278        }
279        if !errors.is_empty() {
280            return Err(errors);
281        }
282        let by_name = self
283            .tables
284            .iter()
285            .enumerate()
286            .map(|(i, t)| (t.name, i))
287            .collect();
288        Ok(Schema {
289            tables: self
290                .tables
291                .into_iter()
292                .map(|mut table| {
293                    table.id_storage = id_storage;
294                    Arc::new(table)
295                })
296                .collect(),
297            by_name,
298            id_storage,
299        })
300    }
301}