use super::BuildableStatement;
use crate::errors::SqlBuilderError;
#[derive(Debug)]
pub struct Insert {
pub table: String,
pub values: Vec<(String, String)>,
}
impl Insert {
pub fn new(table: &str) -> Self {
Self {
table: table.to_string(),
values: Vec::new(),
}
}
pub fn values(mut self, values: Vec<(&str, &str)>) -> Self {
self.values = values
.into_iter()
.map(|(col, val)| (col.to_string(), val.to_string()))
.collect();
self
}
pub fn build(&self) -> Result<String, SqlBuilderError> {
if self.table.is_empty() {
return Err(SqlBuilderError::EmptyTableName);
}
if self.values.is_empty() {
return Err(SqlBuilderError::EmptyColumnAndValue);
}
let mut columns: Vec<String> = vec![];
let mut values: Vec<String> = vec![];
for (col, val) in &self.values {
if col.is_empty() {
return Err(SqlBuilderError::EmptyColumnName);
}
if val.is_empty() {
return Err(SqlBuilderError::EmptyValue);
}
columns.push(col.clone());
values.push(format!("'{}'", val.clone()));
}
Ok(format!(
"INSERT INTO {} ({}) VALUES ({});",
self.table,
columns.join(", "),
values.join(", ")
))
}
}
impl BuildableStatement for Insert {
fn build(&self) -> String {
self.build().unwrap()
}
}