use std::collections::HashMap;
use crate::{
condition::Condition,
sqlite::util::{
generate_limit_str, generate_offset_str, generate_order_by_str,
generate_where_condition_str, remove_quotes_and_backslashes,
},
};
use rusqlite::{Connection, Result};
use log::info;
use crate::table::Table;
pub fn delete<T: Table + Default>(conn: Connection) -> DeleteQueryBuilder<T> {
DeleteQueryBuilder::new(conn)
}
pub struct DeleteQueryBuilder<T: Table + Default> {
conn: Connection,
table: Option<T>,
where_condition: Option<Condition>,
order_by: Option<HashMap<Vec<String>, String>>,
limit: Option<usize>,
offset: Option<usize>,
}
impl<T: Table + Default> DeleteQueryBuilder<T> {
pub fn new(conn: Connection) -> Self {
DeleteQueryBuilder {
conn,
table: None,
where_condition: None,
order_by: None,
limit: None,
offset: None,
}
}
pub fn from(mut self, table: T) -> Self {
self.table = Some(table);
self
}
pub fn where_clause(mut self, condition: Condition) -> Self {
self.where_condition = Some(condition);
self
}
pub fn order_by(mut self, col_and_order: HashMap<Vec<String>, String>) -> Self {
self.order_by = Some(col_and_order);
self
}
pub fn limit(mut self, count: usize) -> Self {
self.limit = Some(count);
self
}
pub fn offset(mut self, offset: usize) -> Self {
self.offset = Some(offset);
self
}
pub fn build(mut self) -> 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 order_by_str = generate_order_by_str(&self.order_by);
let limit_str = generate_limit_str(self.limit);
let offset_str = generate_offset_str(self.offset);
let query = format!(
"DELETE FROM {} {} {} {}",
table_name_str,
where_condition_str,
order_by_str,
format!("{} {}", limit_str, offset_str),
);
info!("{}", query);
println!("{}", query);
let _ = match self.conn.transaction() {
Ok(tx) => tx.execute(&query.to_string(), []),
Err(_) => todo!(),
};
Ok(())
}
}