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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum DefaultValue {
17    Bool(bool),
18    Int(i64),
19    Text(&'static str),
20    /// The current time at insert.
21    Now,
22}
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum OnDelete {
26    Cascade,
27    SetNull,
28    Restrict,
29}
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub struct Reference {
33    pub table: &'static str,
34    pub column: &'static str,
35    pub on_delete: OnDelete,
36}
37
38/// One column. Built with const fns so `Fields` and `Model` impls can return `&'static [ColumnDef]`.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub struct ColumnDef {
41    pub name: &'static str,
42    pub ty: ColumnType,
43    pub nullable: bool,
44    pub primary_key: bool,
45    pub unique: bool,
46    pub index: bool,
47    pub default: Option<DefaultValue>,
48    pub references: Option<Reference>,
49    /// Clients may set it through sign-up and update-user bodies.
50    pub input: bool,
51    /// Serialized to clients.
52    pub returned: bool,
53    /// The plugin id, `"core"` or `"app"`. Filled in when the column joins the schema.
54    pub owner: &'static str,
55}
56
57impl ColumnDef {
58    pub const fn new(name: &'static str, ty: ColumnType) -> Self {
59        Self {
60            name,
61            ty,
62            nullable: false,
63            primary_key: false,
64            unique: false,
65            index: false,
66            default: None,
67            references: None,
68            input: false,
69            returned: true,
70            owner: "",
71        }
72    }
73
74    pub const fn primary_key(mut self) -> Self {
75        self.primary_key = true;
76        self
77    }
78
79    pub const fn nullable(mut self) -> Self {
80        self.nullable = true;
81        self
82    }
83
84    pub const fn unique(mut self) -> Self {
85        self.unique = true;
86        self
87    }
88
89    pub const fn index(mut self) -> Self {
90        self.index = true;
91        self
92    }
93
94    pub const fn default(mut self, value: DefaultValue) -> Self {
95        self.default = Some(value);
96        self
97    }
98
99    pub const fn references(
100        mut self,
101        table: &'static str,
102        column: &'static str,
103        on_delete: OnDelete,
104    ) -> Self {
105        self.references = Some(Reference {
106            table,
107            column,
108            on_delete,
109        });
110        self
111    }
112
113    pub const fn input(mut self) -> Self {
114        self.input = true;
115        self
116    }
117
118    pub const fn hidden(mut self) -> Self {
119        self.returned = false;
120        self
121    }
122}
123
124#[derive(Clone, Debug, PartialEq, Eq)]
125pub struct TableDef {
126    pub name: &'static str,
127    pub owner: &'static str,
128    pub columns: Vec<ColumnDef>,
129    positions: HashMap<&'static str, usize>,
130}
131
132impl TableDef {
133    fn new(name: &'static str, owner: &'static str) -> Self {
134        Self {
135            name,
136            owner,
137            columns: Vec::new(),
138            positions: HashMap::new(),
139        }
140    }
141
142    pub fn position(&self, column: &str) -> Option<usize> {
143        self.positions.get(column).copied()
144    }
145
146    pub fn column(&self, column: &str) -> Option<&ColumnDef> {
147        self.position(column).map(|i| &self.columns[i])
148    }
149
150    pub fn primary_key(&self) -> Option<&ColumnDef> {
151        self.columns.iter().find(|c| c.primary_key)
152    }
153}
154
155/// The merged schema for one configuration: core tables, app fields, every plugin's tables
156/// and columns. Immutable after `.build()`.
157#[derive(Clone, Debug, Default)]
158pub struct Schema {
159    tables: Vec<Arc<TableDef>>,
160    by_name: HashMap<&'static str, usize>,
161}
162
163impl Schema {
164    pub fn tables(&self) -> &[Arc<TableDef>] {
165        &self.tables
166    }
167
168    pub fn table(&self, name: &str) -> Option<&Arc<TableDef>> {
169        self.by_name.get(name).map(|&i| &self.tables[i])
170    }
171
172    /// Panics on a table name the schema doesn't have. Only for core's own tables and
173    /// models whose table was registered (checked at build time).
174    pub fn expect(&self, name: &str) -> &Arc<TableDef> {
175        self.table(name)
176            .unwrap_or_else(|| panic!("fastauth: table `{name}` is not in the schema"))
177    }
178}
179
180/// Collects tables and columns during `.build()` and reports clashes with both owners.
181#[derive(Debug, Default)]
182pub struct SchemaBuilder {
183    tables: Vec<TableDef>,
184    pub(crate) owner: &'static str,
185    pub(crate) errors: Vec<String>,
186}
187
188impl SchemaBuilder {
189    pub(crate) fn new() -> Self {
190        Self {
191            owner: "core",
192            ..Self::default()
193        }
194    }
195
196    /// Adds a new table owned by the current plugin.
197    pub fn table(&mut self, name: &'static str, columns: &[ColumnDef]) -> &mut Self {
198        if let Some(existing) = self.tables.iter().find(|t| t.name == name) {
199            self.errors.push(format!(
200                "table `{name}` is defined by both `{}` and `{}`",
201                existing.owner, self.owner
202            ));
203            return self;
204        }
205        self.tables.push(TableDef::new(name, self.owner));
206        self.extend(name, columns)
207    }
208
209    /// Adds columns to an existing table (usually `user` or `session`).
210    pub fn extend(&mut self, table: &'static str, columns: &[ColumnDef]) -> &mut Self {
211        let owner = self.owner;
212        let Some(def) = self.tables.iter_mut().find(|t| t.name == table) else {
213            self.errors
214                .push(format!("`{owner}` adds columns to unknown table `{table}`"));
215            return self;
216        };
217        for column in columns {
218            if let Some(clash) = def.column(column.name) {
219                self.errors.push(format!(
220                    "column `{table}.{}` is defined by both `{}` and `{owner}`",
221                    column.name, clash.owner
222                ));
223                continue;
224            }
225            let mut column = *column;
226            column.owner = owner;
227            def.positions.insert(column.name, def.columns.len());
228            def.columns.push(column);
229        }
230        self
231    }
232
233    /// Registers a model's table.
234    pub fn model<M: crate::model::Model>(&mut self) -> &mut Self {
235        self.table(M::TABLE, M::columns())
236    }
237
238    pub(crate) fn finish(self) -> Result<Schema, Vec<String>> {
239        let mut errors = self.errors;
240        for table in &self.tables {
241            for column in &table.columns {
242                if let Some(r) = column.references {
243                    let target = self.tables.iter().find(|t| t.name == r.table);
244                    if target.and_then(|t| t.column(r.column)).is_none() {
245                        errors.push(format!(
246                            "column `{}.{}` references missing `{}.{}`",
247                            table.name, column.name, r.table, r.column
248                        ));
249                    }
250                }
251            }
252        }
253        if !errors.is_empty() {
254            return Err(errors);
255        }
256        let by_name = self
257            .tables
258            .iter()
259            .enumerate()
260            .map(|(i, t)| (t.name, i))
261            .collect();
262        Ok(Schema {
263            tables: self.tables.into_iter().map(Arc::new).collect(),
264            by_name,
265        })
266    }
267}