use std::collections::HashMap;
use std::sync::Arc;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ColumnType {
Id,
Text,
Bool,
Int,
Timestamp,
Json,
Bytes,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum IdStorage {
Uuid,
#[default]
Text,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ColumnNaming {
#[default]
SnakeCase,
CamelCase,
}
impl ColumnNaming {
pub fn apply(self, name: &str) -> String {
match self {
ColumnNaming::SnakeCase => name.to_owned(),
ColumnNaming::CamelCase => {
let mut out = String::with_capacity(name.len());
let mut upper = false;
for (i, ch) in name.char_indices() {
if ch == '_' && i > 0 && i + 1 < name.len() {
upper = true;
} else if upper {
out.extend(ch.to_uppercase());
upper = false;
} else {
out.push(ch);
}
}
out
}
}
}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct Storage {
pub(crate) naming: ColumnNaming,
pub(crate) renames: Vec<(String, String, String)>,
pub(crate) hex_text: Vec<(String, String)>,
pub(crate) utf8_text: Vec<(String, String)>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BytesText {
Hex,
Utf8,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DefaultValue {
Bool(bool),
Int(i64),
Text(&'static str),
Now,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OnDelete {
Cascade,
SetNull,
Restrict,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Reference {
pub table: &'static str,
pub column: &'static str,
pub on_delete: OnDelete,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ColumnDef {
pub name: &'static str,
pub ty: ColumnType,
pub nullable: bool,
pub primary_key: bool,
pub unique: bool,
pub index: bool,
pub default: Option<DefaultValue>,
pub references: Option<Reference>,
pub input: bool,
pub returned: bool,
pub owner: &'static str,
}
impl ColumnDef {
pub const fn new(name: &'static str, ty: ColumnType) -> Self {
Self {
name,
ty,
nullable: false,
primary_key: false,
unique: false,
index: false,
default: None,
references: None,
input: false,
returned: true,
owner: "",
}
}
pub const fn primary_key(mut self) -> Self {
self.primary_key = true;
self
}
pub const fn nullable(mut self) -> Self {
self.nullable = true;
self
}
pub const fn unique(mut self) -> Self {
self.unique = true;
self
}
pub const fn index(mut self) -> Self {
self.index = true;
self
}
pub const fn default(mut self, value: DefaultValue) -> Self {
self.default = Some(value);
self
}
pub const fn references(
mut self,
table: &'static str,
column: &'static str,
on_delete: OnDelete,
) -> Self {
self.references = Some(Reference {
table,
column,
on_delete,
});
self
}
pub const fn input(mut self) -> Self {
self.input = true;
self
}
pub const fn hidden(mut self) -> Self {
self.returned = false;
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UniqueDef {
pub columns: Vec<&'static str>,
pub owner: &'static str,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TableDef {
pub name: &'static str,
pub owner: &'static str,
pub columns: Vec<ColumnDef>,
pub uniques: Vec<UniqueDef>,
positions: HashMap<&'static str, usize>,
id_storage: IdStorage,
stored: Vec<String>,
bytes_text: Vec<Option<BytesText>>,
referenced: Vec<Option<String>>,
}
impl TableDef {
fn new(name: &'static str, owner: &'static str) -> Self {
Self {
name,
owner,
columns: Vec::new(),
uniques: Vec::new(),
positions: HashMap::new(),
id_storage: IdStorage::default(),
stored: Vec::new(),
bytes_text: Vec::new(),
referenced: Vec::new(),
}
}
pub fn stored_reference(&self, position: usize) -> Option<&str> {
match self.referenced.get(position) {
Some(stored) => stored.as_deref(),
None => self.columns[position].references.map(|r| r.column),
}
}
pub fn stored_name(&self, position: usize) -> &str {
self.stored
.get(position)
.map_or(self.columns[position].name, String::as_str)
}
pub fn stored_column(&self, column: &str) -> Option<&str> {
self.position(column).map(|i| self.stored_name(i))
}
pub fn column_stored_as(&self, stored: &str) -> Option<&ColumnDef> {
(0..self.columns.len())
.find(|&i| self.stored_name(i) == stored)
.map(|i| &self.columns[i])
}
pub fn is_hex_text(&self, position: usize) -> bool {
self.bytes_text(position) == Some(BytesText::Hex)
}
pub fn bytes_text(&self, position: usize) -> Option<BytesText> {
self.bytes_text.get(position).copied().flatten()
}
pub fn id_storage(&self) -> IdStorage {
self.id_storage
}
pub fn position(&self, column: &str) -> Option<usize> {
self.positions.get(column).copied()
}
pub fn column(&self, column: &str) -> Option<&ColumnDef> {
self.position(column).map(|i| &self.columns[i])
}
pub fn primary_key(&self) -> Option<&ColumnDef> {
self.columns.iter().find(|c| c.primary_key)
}
pub fn unique_sets(&self) -> impl Iterator<Item = Vec<&'static str>> + '_ {
self.columns
.iter()
.filter(|c| c.unique && !c.primary_key)
.map(|c| vec![c.name])
.chain(self.uniques.iter().map(|u| u.columns.clone()))
}
}
#[derive(Clone, Debug, Default)]
pub struct Schema {
tables: Vec<Arc<TableDef>>,
by_name: HashMap<&'static str, usize>,
id_storage: IdStorage,
}
impl Schema {
pub fn id_storage(&self) -> IdStorage {
self.id_storage
}
pub fn tables(&self) -> &[Arc<TableDef>] {
&self.tables
}
pub fn table(&self, name: &str) -> Option<&Arc<TableDef>> {
self.by_name.get(name).map(|&i| &self.tables[i])
}
pub fn expect(&self, name: &str) -> &Arc<TableDef> {
self.table(name)
.unwrap_or_else(|| panic!("fastauth: table `{name}` is not in the schema"))
}
}
#[derive(Debug, Default)]
pub struct SchemaBuilder {
tables: Vec<TableDef>,
pub(crate) owner: &'static str,
pub(crate) errors: Vec<String>,
}
impl SchemaBuilder {
pub(crate) fn new() -> Self {
Self {
owner: "core",
..Self::default()
}
}
pub fn table(&mut self, name: &'static str, columns: &[ColumnDef]) -> &mut Self {
if let Some(existing) = self.tables.iter().find(|t| t.name == name) {
self.errors.push(format!(
"table `{name}` is defined by both `{}` and `{}`",
existing.owner, self.owner
));
return self;
}
self.tables.push(TableDef::new(name, self.owner));
self.extend(name, columns)
}
pub fn extend(&mut self, table: &'static str, columns: &[ColumnDef]) -> &mut Self {
let owner = self.owner;
let Some(def) = self.tables.iter_mut().find(|t| t.name == table) else {
self.errors
.push(format!("`{owner}` adds columns to unknown table `{table}`"));
return self;
};
for column in columns {
if let Some(clash) = def.column(column.name) {
self.errors.push(format!(
"column `{table}.{}` is defined by both `{}` and `{owner}`",
column.name, clash.owner
));
continue;
}
let mut column = *column;
column.owner = owner;
def.positions.insert(column.name, def.columns.len());
def.columns.push(column);
}
self
}
pub fn unique(&mut self, table: &'static str, columns: &[&'static str]) -> &mut Self {
let owner = self.owner;
let Some(def) = self.tables.iter_mut().find(|t| t.name == table) else {
self.errors.push(format!(
"`{owner}` adds a unique constraint to unknown table `{table}`"
));
return self;
};
if columns.len() < 2 {
self.errors.push(format!(
"`{owner}`: a unique constraint on `{table}` needs two or more columns; \
use `ColumnDef::unique` for one"
));
return self;
}
if let Some(missing) = columns.iter().find(|c| def.column(c).is_none()) {
self.errors.push(format!(
"`{owner}` adds a unique constraint on missing column `{table}.{missing}`"
));
return self;
}
if !def.uniques.iter().any(|u| u.columns == columns) {
def.uniques.push(UniqueDef {
columns: columns.to_vec(),
owner,
});
}
self
}
pub fn model<M: crate::model::Model>(&mut self) -> &mut Self {
self.table(M::TABLE, M::columns())
}
pub(crate) fn finish(
mut self,
id_storage: IdStorage,
storage: &Storage,
) -> Result<Schema, Vec<String>> {
let mut errors = std::mem::take(&mut self.errors);
for table in &mut self.tables {
table.stored = table
.columns
.iter()
.map(|c| storage.naming.apply(c.name))
.collect();
table.bytes_text = vec![None; table.columns.len()];
}
fn find<'t>(
tables: &'t mut [TableDef],
(table, column): (&str, &str),
what: &str,
errors: &mut Vec<String>,
) -> Option<(&'t mut TableDef, usize)> {
let found = tables
.iter_mut()
.find(|t| t.name == table)
.and_then(|t| t.position(column).map(|i| (t, i)));
if found.is_none() {
errors.push(format!(
"{what} names `{table}.{column}`, which is not in the schema"
));
}
found
}
for (table, column, to) in &storage.renames {
let target = (table.as_str(), column.as_str());
if let Some((def, i)) = find(&mut self.tables, target, "rename_column", &mut errors) {
def.stored[i] = to.clone();
}
}
let text_columns = (storage.hex_text.iter().map(|c| (c, BytesText::Hex)))
.chain(storage.utf8_text.iter().map(|c| (c, BytesText::Utf8)));
for ((table, column), encoding) in text_columns {
let target = (table.as_str(), column.as_str());
if let Some((def, i)) = find(&mut self.tables, target, "bytes_as_hex_text", &mut errors)
{
if def.columns[i].ty == ColumnType::Bytes {
def.bytes_text[i] = Some(encoding);
} else {
errors.push(format!(
"bytes_as_hex_text names `{table}.{column}`, which is {:?}, not Bytes",
def.columns[i].ty
));
}
}
}
let stored: HashMap<(&str, &str), String> = self
.tables
.iter()
.flat_map(|t| {
t.columns
.iter()
.zip(&t.stored)
.map(|(c, s)| ((t.name, c.name), s.clone()))
})
.collect();
let referenced: Vec<Vec<Option<String>>> = self
.tables
.iter()
.map(|t| {
t.columns
.iter()
.map(|c| {
let r = c.references?;
Some(
stored
.get(&(r.table, r.column))
.cloned()
.unwrap_or(r.column.to_owned()),
)
})
.collect()
})
.collect();
for (table, referenced) in self.tables.iter_mut().zip(referenced) {
table.referenced = referenced;
}
for table in &self.tables {
let mut seen = std::collections::HashSet::new();
for (i, stored) in table.stored.iter().enumerate() {
if !seen.insert(stored.as_str()) {
errors.push(format!(
"two columns of `{}` are stored as `{stored}` (one is `{}`)",
table.name, table.columns[i].name
));
}
}
}
for table in &self.tables {
for column in &table.columns {
if let Some(r) = column.references {
let target = self.tables.iter().find(|t| t.name == r.table);
if target.and_then(|t| t.column(r.column)).is_none() {
errors.push(format!(
"column `{}.{}` references missing `{}.{}`",
table.name, column.name, r.table, r.column
));
}
}
}
}
if !errors.is_empty() {
return Err(errors);
}
let by_name = self
.tables
.iter()
.enumerate()
.map(|(i, t)| (t.name, i))
.collect();
Ok(Schema {
tables: self
.tables
.into_iter()
.map(|mut table| {
table.id_storage = id_storage;
Arc::new(table)
})
.collect(),
by_name,
id_storage,
})
}
}