use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
pub struct Schema {
pub tables: Vec<Table>,
}
#[derive(Debug, Clone, Serialize)]
pub struct Table {
pub name: String,
pub rust_name: String,
pub strict: bool,
pub without_rowid: bool,
pub columns: Vec<Column>,
pub primary_key: Option<TablePrimaryKey>,
pub indexes: Vec<Index>,
pub foreign_keys: Vec<TableForeignKey>,
pub checks: Vec<TableCheck>,
}
#[derive(Debug, Clone, Serialize)]
pub struct Column {
pub name: String,
pub ty: ColumnType,
pub nullable: bool,
pub primary_key: bool,
pub auto_increment: bool,
pub unique: bool,
pub default: Option<String>,
pub check: Option<String>,
pub references: Option<ColumnFk>,
pub generated: Option<Generated>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "kind", content = "inner", rename_all = "snake_case")]
pub enum ColumnType {
Integer,
Text,
Real,
Blob,
Json(String),
Jsonb(String),
}
impl ColumnType {
pub fn sql(&self) -> &'static str {
match self {
ColumnType::Integer => "INTEGER",
ColumnType::Text | ColumnType::Json(_) => "TEXT",
ColumnType::Real => "REAL",
ColumnType::Blob | ColumnType::Jsonb(_) => "BLOB",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ColumnFk {
pub table: String,
pub column: String,
pub on_delete: Option<FkAction>,
pub on_update: Option<FkAction>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FkAction {
Cascade,
Restrict,
SetNull,
SetDefault,
NoAction,
}
impl FkAction {
pub fn parse(s: &str) -> Option<Self> {
Some(match s {
"cascade" => Self::Cascade,
"restrict" => Self::Restrict,
"set_null" => Self::SetNull,
"set_default" => Self::SetDefault,
"no_action" => Self::NoAction,
_ => return None,
})
}
pub fn sql(self) -> &'static str {
match self {
Self::Cascade => "CASCADE",
Self::Restrict => "RESTRICT",
Self::SetNull => "SET NULL",
Self::SetDefault => "SET DEFAULT",
Self::NoAction => "NO ACTION",
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct Generated {
pub expr: String,
pub kind: GeneratedKind,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GeneratedKind {
Stored,
Virtual,
}
#[derive(Debug, Clone, Serialize)]
pub struct TablePrimaryKey {
pub columns: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct Index {
pub name: Option<String>,
pub columns: Vec<String>,
pub unique: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct TableForeignKey {
pub columns: Vec<String>,
pub references_table: String,
pub references_columns: Vec<String>,
pub on_delete: Option<FkAction>,
pub on_update: Option<FkAction>,
}
#[derive(Debug, Clone, Serialize)]
pub struct TableCheck {
pub name: String,
pub expr: String,
}