use crate::{
condition::Condition,
mssql::util::{generate_where_condition_str, remove_quotes_and_backslashes},
};
use log::{debug, info};
use crate::table::Table;
use super::Connection;
pub fn delete<T: Table + Default>() -> DeleteQueryBuilder<'static, T> {
DeleteQueryBuilder::new()
}
pub struct DeleteQueryBuilder<'a, T: Table + Default> {
table: Option<T>,
where_condition: Option<Condition<'a>>,
}
impl<'a, T: Table + Default> DeleteQueryBuilder<'a, T> {
pub fn new() -> Self {
DeleteQueryBuilder {
table: None,
where_condition: None,
}
}
pub fn from(mut self, table: T) -> Self {
self.table = Some(table);
self
}
pub fn where_clause(mut self, condition: Condition<'a>) -> Self {
self.where_condition = Some(condition);
self
}
pub async fn build(self, conn: &mut Connection) -> Result<(), String> {
let table_name = self
.table
.as_ref()
.map(|t| t.get_name().to_string())
.unwrap_or("".to_string());
let table_name_str = remove_quotes_and_backslashes(&table_name);
let where_condition_str = generate_where_condition_str(self.where_condition);
let query = format!("DELETE FROM {} {}", table_name_str, where_condition_str,);
debug!("{}", query);
match conn.client.execute(&query, &[]).await {
Ok(_) => Ok(()),
Err(err) => Err(err.to_string()),
}
}
}