use crate::{column::ColumnDef, error::Result, value::{Row, Value}};
pub trait Model: Sized + Send + Sync + 'static {
fn table_name() -> &'static str;
fn columns() -> Vec<ColumnDef>;
fn primary_key() -> &'static str {
"id"
}
fn to_row(&self) -> Result<Row>;
fn from_row(row: Row) -> Result<Self>;
fn pk_value(&self) -> Result<Value>;
}
#[derive(Debug, Clone)]
pub struct TableSchema {
pub table: String,
pub columns: Vec<ColumnDef>,
pub indexes: Vec<IndexDef>,
}
#[derive(Debug, Clone)]
pub struct IndexDef {
pub name: String,
pub columns: Vec<String>,
pub unique: bool,
}
impl TableSchema {
pub fn from_model<M: Model>() -> Self {
Self {
table: M::table_name().to_owned(),
columns: M::columns(),
indexes: vec![],
}
}
pub fn with_index(mut self, name: impl Into<String>, cols: Vec<impl Into<String>>, unique: bool) -> Self {
self.indexes.push(IndexDef {
name: name.into(),
columns: cols.into_iter().map(|c| c.into()).collect(),
unique,
});
self
}
}