Skip to main content

ngb_sqlbuilder/
delete.rs

1use crate::{
2    Clause, Condition, SqlClause, __condition, wrap,
3    LOGIC_CONN_AND, LOGIC_CONN_OR,
4};
5
6pub struct Delete;
7pub struct DeleteWhere;
8
9pub fn delete_from<'q>(table: &str) -> Clause<'q, Delete> {
10    let mut sql = String::from("DELETE FROM ");
11    sql.push_str(&wrap(table));
12    Clause::new(sql, vec![])
13}
14impl<'q> Clause<'q, Delete> {
15    pub fn where_col(self, column: &str, value: Clause<'q, Condition>) -> Clause<'q, DeleteWhere> {
16        let (mut sql, mut params) = self.unwrap();
17        sql.push_str(" WHERE ");
18        sql.push_str(&wrap(column));
19        let (cond_sql, cond_params) = value.unwrap();
20        sql.push_str(&cond_sql);
21        params.extend_from_slice(&cond_params);
22        Clause::new(sql, params)
23    }
24
25    pub fn where_cond(self, cond: Clause<'q, Condition>) -> Clause<'q, DeleteWhere> {
26        let (mut sql, mut params) = self.unwrap();
27        let (cond_sql, cond_params) = cond.unwrap();
28        sql.push_str(" WHERE ");
29        sql.push_str(&cond_sql);
30        params.extend_from_slice(&cond_params);
31        Clause::new(sql, params)
32    }
33}
34impl<'q> Clause<'q, DeleteWhere> {
35    pub fn and(self, condition: Clause<'q, Condition>) -> Clause<'q, DeleteWhere> {
36        // __and_cond(self, condition)
37        __condition(LOGIC_CONN_AND, self, condition)
38    }
39    pub fn or(self, condition: Clause<'q, Condition>) -> Clause<'q, DeleteWhere> {
40        // __or_cond(self, condition)
41        __condition(LOGIC_CONN_OR, self, condition)
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use crate::delete::delete_from;
48    use crate::{col, eq, Build};
49
50    #[test]
51    fn delete_test() {
52        let post_id = 123;
53        let time_limit = "2020-01-02 00:00:00";
54        let (sql, params) = delete_from("Post")
55            .where_col("PostId", eq(&post_id))
56            .and(col("Timestamp").lt(&time_limit))
57            .build();
58        println!("{}", sql);
59        println!("params: {:?}", params);
60    }
61}