use super::BuildableStatement;
use crate::errors::SqlBuilderError;
#[derive(Debug)]
pub struct Update {
table: String,
pub set: Vec<(String, String)>,
condition: Option<String>,
}
impl Update {
pub fn new(table: &str) -> Self {
Self {
table: table.to_string(),
set: Vec::new(),
condition: None,
}
}
pub fn set<T: ToString>(mut self, set: Vec<(&str, T)>) -> Self {
self.set = set
.into_iter()
.map(|(col, val)| (col.to_string(), val.to_string()))
.collect();
self
}
pub fn condition(&mut self, condition: String) -> &mut Self {
self.condition = Some(condition);
self
}
pub fn build(&self) -> Result<String, SqlBuilderError> {
if self.table.is_empty() {
return Err(SqlBuilderError::EmptyTableName);
}
if self.set.is_empty() {
return Err(SqlBuilderError::EmptyColumnAndValue);
}
let mut sets: Vec<String> = vec![];
for (col, val) in &self.set {
if col.is_empty() {
return Err(SqlBuilderError::EmptyColumnName);
}
if val.is_empty() {
return Err(SqlBuilderError::EmptyValue);
}
sets.push(format!("{} = '{}'", col.clone(), val.clone()));
}
if let Some(condition) = &self.condition {
return Ok(format!(
"UPDATE {} SET {} WHERE {};",
self.table,
sets.join(", "),
condition
));
}
Ok(format!("UPDATE {} SET {};", self.table, sets.join(", "),))
}
}
impl BuildableStatement for Update {
fn build(&self) -> String {
self.build().unwrap()
}
}