gluesql_core/ast_builder/expr/
unary_op.rs

1use {super::ExprNode, crate::ast::UnaryOperator};
2
3impl ExprNode<'_> {
4    #[must_use]
5    pub fn plus(self) -> Self {
6        plus(self)
7    }
8    #[must_use]
9    pub fn minus(self) -> Self {
10        minus(self)
11    }
12    #[allow(clippy::should_implement_trait)]
13    #[must_use]
14    pub fn negate(self) -> Self {
15        not(self)
16    }
17    #[must_use]
18    pub fn factorial(self) -> Self {
19        factorial(self)
20    }
21    #[must_use]
22    pub fn bitwise_not(self) -> Self {
23        bitwise_not(self)
24    }
25}
26
27pub fn plus<'a, T: Into<ExprNode<'a>>>(expr: T) -> ExprNode<'a> {
28    ExprNode::UnaryOp {
29        op: UnaryOperator::Plus,
30        expr: Box::new(expr.into()),
31    }
32}
33
34pub fn minus<'a, T: Into<ExprNode<'a>>>(expr: T) -> ExprNode<'a> {
35    ExprNode::UnaryOp {
36        op: UnaryOperator::Minus,
37        expr: Box::new(expr.into()),
38    }
39}
40
41pub fn not<'a, T: Into<ExprNode<'a>>>(expr: T) -> ExprNode<'a> {
42    ExprNode::UnaryOp {
43        op: UnaryOperator::Not,
44        expr: Box::new(expr.into()),
45    }
46}
47
48pub fn factorial<'a, T: Into<ExprNode<'a>>>(expr: T) -> ExprNode<'a> {
49    ExprNode::UnaryOp {
50        op: UnaryOperator::Factorial,
51        expr: Box::new(expr.into()),
52    }
53}
54
55pub fn bitwise_not<'a, T: Into<ExprNode<'a>>>(expr: T) -> ExprNode<'a> {
56    ExprNode::UnaryOp {
57        op: UnaryOperator::BitwiseNot,
58        expr: Box::new(expr.into()),
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use crate::ast_builder::{col, num, test_expr};
65
66    #[test]
67    fn unary_op() {
68        let actual = num(5).plus();
69        let expected = "+5";
70        test_expr(actual, expected);
71
72        let actual = num(10).minus();
73        let expected = "-10";
74        test_expr(actual, expected);
75
76        let actual = (col("count").gt(num(5))).negate();
77        let expected = "NOT count > 5";
78        test_expr(actual, expected);
79
80        let actual = num(10).factorial();
81        let expected = "10!";
82        test_expr(actual, expected);
83
84        let actual = num(10).bitwise_not();
85        let expected = "~10";
86        test_expr(actual, expected);
87    }
88}