use super::{BuildableStatement, Column};
use crate::errors::SqlBuilderError;
#[derive(Debug)]
pub struct CreateTable {
table: String,
columns: Vec<Column>,
if_not_exists: bool,
}
impl CreateTable {
pub fn new(table: &str, columns: Vec<Column>) -> Self {
Self {
table: table.to_string(),
columns,
if_not_exists: false,
}
}
pub fn if_not_exists(mut self) -> Self {
self.if_not_exists = true;
self
}
pub fn build(&self) -> Result<String, SqlBuilderError> {
if self.table.is_empty() {
return Err(SqlBuilderError::EmptyTableName);
}
if self.columns.is_empty() {
return Err(SqlBuilderError::NoColumnsSpecified);
}
let mut statement = if self.if_not_exists {
format!("CREATE TABLE IF NOT EXISTS {} (", self.table)
} else {
format!("CREATE TABLE {} (", self.table)
};
let columns_sql: Result<Vec<String>, SqlBuilderError> =
self.columns.iter().map(|col| col.build()).collect();
statement.push_str(&columns_sql?.join(", "));
statement.push_str(");");
Ok(statement)
}
}
impl BuildableStatement for CreateTable {
fn build(&self) -> String {
self.build().unwrap()
}
}