use crate::{DropTable, Sql};
pub struct CreateTable<'a> {
pub table: &'a str,
pub columns: Vec<String>,
}
impl<'a> Sql for CreateTable<'a> {
fn sql(&self) -> String {
let mut result = format!("CREATE TABLE {} (", self.table);
let mut first = true;
for c in &self.columns {
if !first {
result.push_str(", ");
}
first = false;
result.push_str(&c.to_string());
}
result.push(')');
result
}
}
pub struct TableBuilder<'a> {
pub table: &'a str,
pub columns: Vec<Vec<String>>,
}
#[allow(non_snake_case)]
pub fn T<'a>(s: &'a str) -> TableBuilder<'a> {
TableBuilder {
table: s,
columns: Vec::new(),
}
}
impl<'a> TableBuilder<'a> {
pub fn build_create_table(&self) -> CreateTable<'a> {
let mut table_cols = Vec::new();
for c in &self.columns {
table_cols.push(c.join(" "));
}
CreateTable {
table: self.table,
columns: table_cols,
}
}
pub fn build_drop_table(&self) -> DropTable<'a> {
DropTable { table: self.table }
}
pub fn table(&mut self, table: &'a str) -> &mut TableBuilder<'a> {
self.table = table;
self
}
pub fn column(
&mut self,
column: &str,
datatype: &str,
other: Vec<&str>,
) -> &mut TableBuilder<'a> {
let mut col = vec![column, datatype];
col.extend(other);
let str_cols = col.iter().map(|s| s.to_string()).collect();
self.columns.push(str_cols);
self
}
}