Skip to main content

sql_builder/query/condition/
holder.rs

1use super::*;
2
3impl ConditionHolder {
4    pub fn new() -> Self {
5        Self::default()
6    }
7
8    pub fn new_with_condition(condition: Condition) -> Self {
9        let contents = ConditionHolderContents::Condition(condition);
10        Self { contents }
11    }
12
13    pub fn is_empty(&self) -> bool {
14        match &self.contents {
15            ConditionHolderContents::Empty => true,
16            ConditionHolderContents::Chain(c) => c.is_empty(),
17            ConditionHolderContents::Condition(c) => c.conditions.is_empty(),
18        }
19    }
20
21    pub fn is_one(&self) -> bool {
22        match &self.contents {
23            ConditionHolderContents::Empty => true,
24            ConditionHolderContents::Chain(c) => c.len() == 1,
25            ConditionHolderContents::Condition(c) => c.conditions.len() == 1,
26        }
27    }
28
29    pub fn add_and_or(&mut self, condition: LogicalChainOper) {
30        match &mut self.contents {
31            ConditionHolderContents::Empty => {
32                self.contents = ConditionHolderContents::Chain(vec![condition])
33            }
34            ConditionHolderContents::Chain(c) => c.push(condition),
35            ConditionHolderContents::Condition(_) => {
36                panic!("Cannot mix `and_where`/`or_where` and `cond_where` in statements")
37            }
38        }
39    }
40
41    pub fn add_condition(&mut self, mut addition: Condition) {
42        match std::mem::take(&mut self.contents) {
43            ConditionHolderContents::Empty => {
44                self.contents = ConditionHolderContents::Condition(addition);
45            }
46            ConditionHolderContents::Condition(mut current) => {
47                if current.condition_type == ConditionType::All && !current.negate {
48                    if addition.condition_type == ConditionType::All && !addition.negate {
49                        current.conditions.append(&mut addition.conditions);
50                        self.contents = ConditionHolderContents::Condition(current);
51                    } else {
52                        self.contents = ConditionHolderContents::Condition(current.add(addition));
53                    }
54                } else {
55                    self.contents = ConditionHolderContents::Condition(
56                        Condition::all().add(current).add(addition),
57                    );
58                }
59            }
60            ConditionHolderContents::Chain(_) => {
61                panic!("Cannot mix `and_where`/`or_where` and `cond_where` in statements")
62            }
63        }
64    }
65}
66
67#[cfg(test)]
68#[path = "../../../tests/unit/condition_tests.rs"]
69mod tests;