lumus_sql_builder/sqlite/
delete.rs

1use super::BuildableStatement;
2use crate::errors::SqlBuilderError;
3
4/// Represents a ´DELETE´ clause builder for SQL queries
5#[derive(Debug)]
6pub struct Delete {
7    table: String,
8    condition: Option<String>,
9}
10
11impl Delete {
12    /// Creates a new `Delete` instance with the given table name.
13    /// # Example
14    /// ```
15    /// use lumus_sql_builder::sqlite::Delete;
16    ///
17    /// let delete = Delete::new("users_tb").build();
18    ///
19    /// assert_eq!("DELETE FROM users_tb;", delete.unwrap());
20    /// ```
21    pub fn new(table: &str) -> Self {
22        Self {
23            table: table.to_string(),
24            condition: None,
25        }
26    }
27
28    /// Specifies where for `Delete`.
29    pub fn condition(&mut self, condition: String) -> &mut Self {
30        self.condition = Some(condition);
31        self
32    }
33
34    pub fn build(&self) -> Result<String, SqlBuilderError> {
35        if self.table.is_empty() {
36            return Err(SqlBuilderError::EmptyTableName);
37        }
38
39        if let Some(condition) = &self.condition {
40            if condition.is_empty() {
41                return Err(SqlBuilderError::EmptyCondition);
42            }
43            return Ok(format!("DELETE FROM {} WHERE {};", self.table, condition));
44        }
45
46        Ok(format!("DELETE FROM {};", self.table))
47    }
48}
49
50/// Implementation of the `BuildableStatement` trait for `Delete`, allowing it to be printed.
51impl BuildableStatement for Delete {
52    fn build(&self) -> String {
53        self.build().unwrap()
54    }
55}