gluesql_core/ast_builder/
delete.rs

1use {
2    super::{Build, ExprNode},
3    crate::{
4        ast::{Expr, Statement},
5        result::Result,
6    },
7};
8
9#[derive(Clone, Debug)]
10pub struct DeleteNode<'a> {
11    table_name: String,
12    filter_expr: Option<ExprNode<'a>>,
13}
14
15impl<'a> DeleteNode<'a> {
16    pub fn new(table_name: String) -> Self {
17        Self {
18            table_name,
19            filter_expr: None,
20        }
21    }
22
23    pub fn filter<T: Into<ExprNode<'a>>>(mut self, expr: T) -> Self {
24        self.filter_expr = Some(expr.into());
25
26        self
27    }
28}
29
30impl<'a> Build for DeleteNode<'a> {
31    fn build(self) -> Result<Statement> {
32        let table_name = self.table_name;
33        let selection = self.filter_expr.map(Expr::try_from).transpose()?;
34
35        Ok(Statement::Delete {
36            table_name,
37            selection,
38        })
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use crate::{
45        ast::Expr,
46        ast_builder::{Build, col, table, test},
47    };
48
49    #[test]
50    fn delete() {
51        let actual = table("Foo").delete().build();
52        let expected = "DELETE FROM Foo";
53        test(actual, expected);
54
55        let actual = table("Bar").delete().filter("id < (1 + 3 + rate)").build();
56        let expected = "DELETE FROM Bar WHERE id < (1 + 3 + rate)";
57        test(actual, expected);
58
59        let actual = table("Person")
60            .delete()
61            .filter(Expr::IsNull(Box::new(Expr::Identifier("name".to_owned()))))
62            .build();
63        let expected = "DELETE FROM Person WHERE name IS NULL";
64        test(actual, expected);
65
66        let actual = table("Person")
67            .delete()
68            .filter(col("name").is_null())
69            .build();
70        let expected = "DELETE FROM Person WHERE name IS NULL";
71        test(actual, expected);
72    }
73}