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    #[must_use]
24    pub fn filter<T: Into<ExprNode<'a>>>(mut self, expr: T) -> Self {
25        self.filter_expr = Some(expr.into());
26
27        self
28    }
29}
30
31impl Build for DeleteNode<'_> {
32    fn build(self) -> Result<Statement> {
33        let table_name = self.table_name;
34        let selection = self.filter_expr.map(Expr::try_from).transpose()?;
35
36        Ok(Statement::Delete {
37            table_name,
38            selection,
39        })
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use crate::{
46        ast::Expr,
47        ast_builder::{Build, col, table, test},
48    };
49
50    #[test]
51    fn delete() {
52        let actual = table("Foo").delete().build();
53        let expected = "DELETE FROM Foo";
54        test(&actual, expected);
55
56        let actual = table("Bar").delete().filter("id < (1 + 3 + rate)").build();
57        let expected = "DELETE FROM Bar WHERE id < (1 + 3 + rate)";
58        test(&actual, expected);
59
60        let actual = table("Person")
61            .delete()
62            .filter(Expr::IsNull(Box::new(Expr::Identifier("name".to_owned()))))
63            .build();
64        let expected = "DELETE FROM Person WHERE name IS NULL";
65        test(&actual, expected);
66
67        let actual = table("Person")
68            .delete()
69            .filter(col("name").is_null())
70            .build();
71        let expected = "DELETE FROM Person WHERE name IS NULL";
72        test(&actual, expected);
73    }
74}