use std::collections::BTreeMap;
use crate::error::{Error, Result};
use crate::protocol::{ColumnDef, TableSchema};
pub mod col {
use crate::protocol::ColumnDef;
pub fn string() -> ColumnDef {
ColumnDef::new("string")
}
pub fn number() -> ColumnDef {
ColumnDef::new("number")
}
pub fn boolean() -> ColumnDef {
ColumnDef::new("boolean")
}
pub fn datetime() -> ColumnDef {
ColumnDef::new("datetime")
}
pub fn json() -> ColumnDef {
ColumnDef::new("json")
}
pub fn file_ref() -> ColumnDef {
ColumnDef::new("file_ref")
}
pub fn reference(table: &str) -> ColumnDef {
let mut c = ColumnDef::new("ref");
c.ref_table = Some(table.to_string());
c
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Tables(pub BTreeMap<String, TableSchema>);
impl Tables {
pub fn new() -> Tables {
Tables::default()
}
pub fn table<I, S>(mut self, name: &str, columns: I) -> Tables
where
I: IntoIterator<Item = (S, ColumnDef)>,
S: Into<String>,
{
let mut t = TableSchema::default();
let mut order = Vec::new();
for (n, c) in columns {
let n = n.into();
order.push(n.clone());
t.columns.insert(n, c);
}
t.order = Some(order);
self.0.insert(name.to_string(), t);
self
}
pub fn from_json(json: &str) -> Result<Tables> {
let m: BTreeMap<String, TableSchema> = serde_json::from_str(json)?;
Ok(Tables(m))
}
pub fn validate(&self) -> Result<()> {
for (name, t) in &self.0 {
t.validate(name)?;
if t.columns.contains_key("id") {
return Err(Error::config(format!(
"{name}: a column can't be named id; the row id lives in the record's id"
)));
}
}
Ok(())
}
}