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, Default, PartialEq, Eq, Hash)]
19pub enum IdStorage {
20 Uuid,
22 #[default]
24 Text,
25}
26
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
32pub enum ColumnNaming {
33 #[default]
35 SnakeCase,
36 CamelCase,
39}
40
41impl ColumnNaming {
42 pub fn apply(self, name: &str) -> String {
44 match self {
45 ColumnNaming::SnakeCase => name.to_owned(),
46 ColumnNaming::CamelCase => {
47 let mut out = String::with_capacity(name.len());
48 let mut upper = false;
49 for (i, ch) in name.char_indices() {
50 if ch == '_' && i > 0 && i + 1 < name.len() {
51 upper = true;
52 } else if upper {
53 out.extend(ch.to_uppercase());
54 upper = false;
55 } else {
56 out.push(ch);
57 }
58 }
59 out
60 }
61 }
62 }
63}
64
65#[derive(Clone, Debug, Default)]
68pub(crate) struct Storage {
69 pub(crate) naming: ColumnNaming,
70 pub(crate) renames: Vec<(String, String, String)>,
72 pub(crate) hex_text: Vec<(String, String)>,
74 pub(crate) utf8_text: Vec<(String, String)>,
76}
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
81pub enum BytesText {
82 Hex,
84 Utf8,
89}
90
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub enum DefaultValue {
93 Bool(bool),
94 Int(i64),
95 Text(&'static str),
96 Now,
98}
99
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub enum OnDelete {
102 Cascade,
103 SetNull,
104 Restrict,
105}
106
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct Reference {
109 pub table: &'static str,
110 pub column: &'static str,
111 pub on_delete: OnDelete,
112}
113
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
116pub struct ColumnDef {
117 pub name: &'static str,
118 pub ty: ColumnType,
119 pub nullable: bool,
120 pub primary_key: bool,
121 pub unique: bool,
122 pub index: bool,
123 pub default: Option<DefaultValue>,
124 pub references: Option<Reference>,
125 pub input: bool,
127 pub returned: bool,
129 pub owner: &'static str,
131}
132
133impl ColumnDef {
134 pub const fn new(name: &'static str, ty: ColumnType) -> Self {
135 Self {
136 name,
137 ty,
138 nullable: false,
139 primary_key: false,
140 unique: false,
141 index: false,
142 default: None,
143 references: None,
144 input: false,
145 returned: true,
146 owner: "",
147 }
148 }
149
150 pub const fn primary_key(mut self) -> Self {
151 self.primary_key = true;
152 self
153 }
154
155 pub const fn nullable(mut self) -> Self {
156 self.nullable = true;
157 self
158 }
159
160 pub const fn unique(mut self) -> Self {
161 self.unique = true;
162 self
163 }
164
165 pub const fn index(mut self) -> Self {
166 self.index = true;
167 self
168 }
169
170 pub const fn default(mut self, value: DefaultValue) -> Self {
171 self.default = Some(value);
172 self
173 }
174
175 pub const fn references(
176 mut self,
177 table: &'static str,
178 column: &'static str,
179 on_delete: OnDelete,
180 ) -> Self {
181 self.references = Some(Reference {
182 table,
183 column,
184 on_delete,
185 });
186 self
187 }
188
189 pub const fn input(mut self) -> Self {
190 self.input = true;
191 self
192 }
193
194 pub const fn hidden(mut self) -> Self {
195 self.returned = false;
196 self
197 }
198}
199
200#[derive(Clone, Debug, PartialEq, Eq)]
203pub struct UniqueDef {
204 pub columns: Vec<&'static str>,
205 pub owner: &'static str,
207}
208
209#[derive(Clone, Debug, PartialEq, Eq)]
210pub struct TableDef {
211 pub name: &'static str,
212 pub owner: &'static str,
213 pub columns: Vec<ColumnDef>,
214 pub uniques: Vec<UniqueDef>,
216 positions: HashMap<&'static str, usize>,
217 id_storage: IdStorage,
218 stored: Vec<String>,
220 bytes_text: Vec<Option<BytesText>>,
222 referenced: Vec<Option<String>>,
224}
225
226impl TableDef {
227 fn new(name: &'static str, owner: &'static str) -> Self {
228 Self {
229 name,
230 owner,
231 columns: Vec::new(),
232 uniques: Vec::new(),
233 positions: HashMap::new(),
234 id_storage: IdStorage::default(),
235 stored: Vec::new(),
236 bytes_text: Vec::new(),
237 referenced: Vec::new(),
238 }
239 }
240
241 pub fn stored_reference(&self, position: usize) -> Option<&str> {
243 match self.referenced.get(position) {
244 Some(stored) => stored.as_deref(),
245 None => self.columns[position].references.map(|r| r.column),
246 }
247 }
248
249 pub fn stored_name(&self, position: usize) -> &str {
252 self.stored
253 .get(position)
254 .map_or(self.columns[position].name, String::as_str)
255 }
256
257 pub fn stored_column(&self, column: &str) -> Option<&str> {
259 self.position(column).map(|i| self.stored_name(i))
260 }
261
262 pub fn column_stored_as(&self, stored: &str) -> Option<&ColumnDef> {
264 (0..self.columns.len())
265 .find(|&i| self.stored_name(i) == stored)
266 .map(|i| &self.columns[i])
267 }
268
269 pub fn is_hex_text(&self, position: usize) -> bool {
273 self.bytes_text(position) == Some(BytesText::Hex)
274 }
275
276 pub fn bytes_text(&self, position: usize) -> Option<BytesText> {
279 self.bytes_text.get(position).copied().flatten()
280 }
281
282 pub fn id_storage(&self) -> IdStorage {
285 self.id_storage
286 }
287
288 pub fn position(&self, column: &str) -> Option<usize> {
289 self.positions.get(column).copied()
290 }
291
292 pub fn column(&self, column: &str) -> Option<&ColumnDef> {
293 self.position(column).map(|i| &self.columns[i])
294 }
295
296 pub fn primary_key(&self) -> Option<&ColumnDef> {
297 self.columns.iter().find(|c| c.primary_key)
298 }
299
300 pub fn unique_sets(&self) -> impl Iterator<Item = Vec<&'static str>> + '_ {
303 self.columns
304 .iter()
305 .filter(|c| c.unique && !c.primary_key)
306 .map(|c| vec![c.name])
307 .chain(self.uniques.iter().map(|u| u.columns.clone()))
308 }
309}
310
311#[derive(Clone, Debug, Default)]
314pub struct Schema {
315 tables: Vec<Arc<TableDef>>,
316 by_name: HashMap<&'static str, usize>,
317 id_storage: IdStorage,
318}
319
320impl Schema {
321 pub fn id_storage(&self) -> IdStorage {
323 self.id_storage
324 }
325
326 pub fn tables(&self) -> &[Arc<TableDef>] {
327 &self.tables
328 }
329
330 pub fn table(&self, name: &str) -> Option<&Arc<TableDef>> {
331 self.by_name.get(name).map(|&i| &self.tables[i])
332 }
333
334 pub fn expect(&self, name: &str) -> &Arc<TableDef> {
337 self.table(name)
338 .unwrap_or_else(|| panic!("fastauth: table `{name}` is not in the schema"))
339 }
340}
341
342#[derive(Debug, Default)]
344pub struct SchemaBuilder {
345 tables: Vec<TableDef>,
346 pub(crate) owner: &'static str,
347 pub(crate) errors: Vec<String>,
348}
349
350impl SchemaBuilder {
351 pub(crate) fn new() -> Self {
352 Self {
353 owner: "core",
354 ..Self::default()
355 }
356 }
357
358 pub fn table(&mut self, name: &'static str, columns: &[ColumnDef]) -> &mut Self {
360 if let Some(existing) = self.tables.iter().find(|t| t.name == name) {
361 self.errors.push(format!(
362 "table `{name}` is defined by both `{}` and `{}`",
363 existing.owner, self.owner
364 ));
365 return self;
366 }
367 self.tables.push(TableDef::new(name, self.owner));
368 self.extend(name, columns)
369 }
370
371 pub fn extend(&mut self, table: &'static str, columns: &[ColumnDef]) -> &mut Self {
373 let owner = self.owner;
374 let Some(def) = self.tables.iter_mut().find(|t| t.name == table) else {
375 self.errors
376 .push(format!("`{owner}` adds columns to unknown table `{table}`"));
377 return self;
378 };
379 for column in columns {
380 if let Some(clash) = def.column(column.name) {
381 self.errors.push(format!(
382 "column `{table}.{}` is defined by both `{}` and `{owner}`",
383 column.name, clash.owner
384 ));
385 continue;
386 }
387 let mut column = *column;
388 column.owner = owner;
389 def.positions.insert(column.name, def.columns.len());
390 def.columns.push(column);
391 }
392 self
393 }
394
395 pub fn unique(&mut self, table: &'static str, columns: &[&'static str]) -> &mut Self {
398 let owner = self.owner;
399 let Some(def) = self.tables.iter_mut().find(|t| t.name == table) else {
400 self.errors.push(format!(
401 "`{owner}` adds a unique constraint to unknown table `{table}`"
402 ));
403 return self;
404 };
405 if columns.len() < 2 {
406 self.errors.push(format!(
407 "`{owner}`: a unique constraint on `{table}` needs two or more columns; \
408 use `ColumnDef::unique` for one"
409 ));
410 return self;
411 }
412 if let Some(missing) = columns.iter().find(|c| def.column(c).is_none()) {
413 self.errors.push(format!(
414 "`{owner}` adds a unique constraint on missing column `{table}.{missing}`"
415 ));
416 return self;
417 }
418 if !def.uniques.iter().any(|u| u.columns == columns) {
419 def.uniques.push(UniqueDef {
420 columns: columns.to_vec(),
421 owner,
422 });
423 }
424 self
425 }
426
427 pub fn model<M: crate::model::Model>(&mut self) -> &mut Self {
429 self.table(M::TABLE, M::columns())
430 }
431
432 pub(crate) fn finish(
433 mut self,
434 id_storage: IdStorage,
435 storage: &Storage,
436 ) -> Result<Schema, Vec<String>> {
437 let mut errors = std::mem::take(&mut self.errors);
438 for table in &mut self.tables {
439 table.stored = table
440 .columns
441 .iter()
442 .map(|c| storage.naming.apply(c.name))
443 .collect();
444 table.bytes_text = vec![None; table.columns.len()];
445 }
446 fn find<'t>(
447 tables: &'t mut [TableDef],
448 (table, column): (&str, &str),
449 what: &str,
450 errors: &mut Vec<String>,
451 ) -> Option<(&'t mut TableDef, usize)> {
452 let found = tables
453 .iter_mut()
454 .find(|t| t.name == table)
455 .and_then(|t| t.position(column).map(|i| (t, i)));
456 if found.is_none() {
457 errors.push(format!(
458 "{what} names `{table}.{column}`, which is not in the schema"
459 ));
460 }
461 found
462 }
463 for (table, column, to) in &storage.renames {
464 let target = (table.as_str(), column.as_str());
465 if let Some((def, i)) = find(&mut self.tables, target, "rename_column", &mut errors) {
466 def.stored[i] = to.clone();
467 }
468 }
469 let text_columns = (storage.hex_text.iter().map(|c| (c, BytesText::Hex)))
470 .chain(storage.utf8_text.iter().map(|c| (c, BytesText::Utf8)));
471 for ((table, column), encoding) in text_columns {
472 let target = (table.as_str(), column.as_str());
473 if let Some((def, i)) = find(&mut self.tables, target, "bytes_as_hex_text", &mut errors)
474 {
475 if def.columns[i].ty == ColumnType::Bytes {
476 def.bytes_text[i] = Some(encoding);
477 } else {
478 errors.push(format!(
479 "bytes_as_hex_text names `{table}.{column}`, which is {:?}, not Bytes",
480 def.columns[i].ty
481 ));
482 }
483 }
484 }
485 let stored: HashMap<(&str, &str), String> = self
486 .tables
487 .iter()
488 .flat_map(|t| {
489 t.columns
490 .iter()
491 .zip(&t.stored)
492 .map(|(c, s)| ((t.name, c.name), s.clone()))
493 })
494 .collect();
495 let referenced: Vec<Vec<Option<String>>> = self
496 .tables
497 .iter()
498 .map(|t| {
499 t.columns
500 .iter()
501 .map(|c| {
502 let r = c.references?;
503 Some(
504 stored
505 .get(&(r.table, r.column))
506 .cloned()
507 .unwrap_or(r.column.to_owned()),
508 )
509 })
510 .collect()
511 })
512 .collect();
513 for (table, referenced) in self.tables.iter_mut().zip(referenced) {
514 table.referenced = referenced;
515 }
516 for table in &self.tables {
517 let mut seen = std::collections::HashSet::new();
518 for (i, stored) in table.stored.iter().enumerate() {
519 if !seen.insert(stored.as_str()) {
520 errors.push(format!(
521 "two columns of `{}` are stored as `{stored}` (one is `{}`)",
522 table.name, table.columns[i].name
523 ));
524 }
525 }
526 }
527 for table in &self.tables {
528 for column in &table.columns {
529 if let Some(r) = column.references {
530 let target = self.tables.iter().find(|t| t.name == r.table);
531 if target.and_then(|t| t.column(r.column)).is_none() {
532 errors.push(format!(
533 "column `{}.{}` references missing `{}.{}`",
534 table.name, column.name, r.table, r.column
535 ));
536 }
537 }
538 }
539 }
540 if !errors.is_empty() {
541 return Err(errors);
542 }
543 let by_name = self
544 .tables
545 .iter()
546 .enumerate()
547 .map(|(i, t)| (t.name, i))
548 .collect();
549 Ok(Schema {
550 tables: self
551 .tables
552 .into_iter()
553 .map(|mut table| {
554 table.id_storage = id_storage;
555 Arc::new(table)
556 })
557 .collect(),
558 by_name,
559 id_storage,
560 })
561 }
562}