utopia_query/builder/case.rs
1//! [`CaseExpression`]: `CASE WHEN ... THEN ... ELSE ... END`, built
2//! clause by clause and compiled with bindings by a builder.
3
4use crate::error::{Error, Result};
5use crate::method::backed_enum;
6use crate::value::{IntoValue, IntoValues, Value};
7
8backed_enum! {
9 /// What a `WHEN` clause tests.
10 ///
11 /// PHP: `Utopia\Query\Builder\Case\Kind`.
12 pub enum Kind: "Utopia\\Query\\Builder\\Case\\Kind" {
13 /// `column operator ?`.
14 Comparison = "comparison",
15 /// `column IS NULL`.
16 Null = "null",
17 /// `column IS NOT NULL`.
18 NotNull = "notNull",
19 /// `column IN (?, ...)`.
20 In = "in",
21 /// Raw SQL with bindings.
22 Raw = "raw",
23 }
24}
25
26backed_enum! {
27 /// A comparison of a `WHEN` clause.
28 ///
29 /// PHP: `Utopia\Query\Builder\Case\Operator`.
30 pub enum Operator: "Utopia\\Query\\Builder\\Case\\Operator" {
31 /// `=`.
32 Equal = "equal",
33 /// `!=`.
34 NotEqual = "notEqual",
35 /// `<`.
36 LessThan = "lessThan",
37 /// `<=`.
38 LessThanEqual = "lessThanEqual",
39 /// `>`.
40 GreaterThan = "greaterThan",
41 /// `>=`.
42 GreaterThanEqual = "greaterThanEqual",
43 }
44}
45
46impl Operator {
47 /// The SQL operator.
48 ///
49 /// PHP: `sqlOperator()`.
50 pub fn sql_operator(self) -> &'static str {
51 match self {
52 Operator::Equal => "=",
53 Operator::NotEqual => "!=",
54 Operator::LessThan => "<",
55 Operator::LessThanEqual => "<=",
56 Operator::GreaterThan => ">",
57 Operator::GreaterThanEqual => ">=",
58 }
59 }
60}
61
62/// One `WHEN ... THEN ...` clause.
63///
64/// PHP: `Utopia\Query\Builder\Case\WhenClause`.
65#[derive(Debug, Clone, PartialEq)]
66pub struct WhenClause {
67 /// What the clause tests.
68 pub kind: Kind,
69 /// The column tested (not for raw clauses).
70 pub column: Option<String>,
71 /// The comparison (comparison clauses).
72 pub operator: Option<Operator>,
73 /// The value compared to (comparison clauses).
74 pub value: Value,
75 /// The result when the clause matches.
76 pub then: Value,
77 /// The values of an `IN` clause.
78 pub values: Vec<Value>,
79 /// The SQL of a raw clause.
80 pub raw_condition: Option<String>,
81 /// The bindings of a raw clause.
82 pub raw_bindings: Vec<Value>,
83}
84
85impl WhenClause {
86 /// A clause from its parts.
87 ///
88 /// PHP: `new WhenClause(...)`.
89 #[allow(clippy::too_many_arguments)]
90 pub fn new(
91 kind: Kind,
92 column: Option<String>,
93 operator: Option<Operator>,
94 value: Value,
95 then: Value,
96 values: Vec<Value>,
97 raw_condition: Option<String>,
98 raw_bindings: Vec<Value>,
99 ) -> Self {
100 WhenClause { kind, column, operator, value, then, values, raw_condition, raw_bindings }
101 }
102}
103
104/// A `CASE` expression: `WHEN` clauses in order, an optional `ELSE` and an alias.
105///
106/// PHP: `Utopia\Query\Builder\Case\Expression`.
107///
108/// ```
109/// use utopia_query::builder::{CaseExpression, MySql, Operator};
110///
111/// let mut case = CaseExpression::new();
112/// case.when("status", Operator::Equal, "active", 1).else_(0).alias("is_active");
113/// let statement = MySql::new().from("users", "").select_case(case).build()?;
114/// assert_eq!(statement.query, "SELECT CASE WHEN `status` = ? THEN ? ELSE ? END AS `is_active` FROM `users`");
115/// # Ok::<(), utopia_query::Error>(())
116/// ```
117///
118/// ```php
119/// use Utopia\Query\Builder\Case\Expression;
120/// use Utopia\Query\Builder\Case\Operator;
121/// use Utopia\Query\Builder\MySQL;
122///
123/// $case = (new Expression())->when('status', Operator::Equal, 'active', 1)->else(0)->alias('is_active');
124/// echo (new MySQL())->from('users')->selectCase($case)->build()->query, "\n";
125/// ```
126#[derive(Debug, Clone, PartialEq, Default)]
127pub struct CaseExpression {
128 whens: Vec<WhenClause>,
129 has_else: bool,
130 else_value: Value,
131 alias: String,
132}
133
134impl CaseExpression {
135 /// An empty `CASE`.
136 pub fn new() -> Self {
137 CaseExpression::default()
138 }
139
140 /// `WHEN column operator value THEN then`.
141 ///
142 /// PHP: `when()`.
143 pub fn when(
144 &mut self,
145 column: impl Into<String>,
146 operator: Operator,
147 value: impl IntoValue,
148 then: impl IntoValue,
149 ) -> &mut Self {
150 self.whens.push(WhenClause::new(
151 Kind::Comparison,
152 Some(column.into()),
153 Some(operator),
154 value.into_value(),
155 then.into_value(),
156 Vec::new(),
157 None,
158 Vec::new(),
159 ));
160 self
161 }
162
163 /// `WHEN column IS NULL THEN then`.
164 ///
165 /// PHP: `whenNull()`.
166 pub fn when_null(&mut self, column: impl Into<String>, then: impl IntoValue) -> &mut Self {
167 self.whens.push(WhenClause::new(
168 Kind::Null,
169 Some(column.into()),
170 None,
171 Value::Null,
172 then.into_value(),
173 Vec::new(),
174 None,
175 Vec::new(),
176 ));
177 self
178 }
179
180 /// `WHEN column IS NOT NULL THEN then`.
181 ///
182 /// PHP: `whenNotNull()`.
183 pub fn when_not_null(&mut self, column: impl Into<String>, then: impl IntoValue) -> &mut Self {
184 self.whens.push(WhenClause::new(
185 Kind::NotNull,
186 Some(column.into()),
187 None,
188 Value::Null,
189 then.into_value(),
190 Vec::new(),
191 None,
192 Vec::new(),
193 ));
194 self
195 }
196
197 /// `WHEN column IN (values) THEN then`; `values` must not be empty.
198 ///
199 /// PHP: `whenIn()`.
200 pub fn when_in(
201 &mut self,
202 column: impl Into<String>,
203 values: impl IntoValues,
204 then: impl IntoValue,
205 ) -> Result<&mut Self> {
206 let values: Vec<Value> = values.into_values().values().cloned().collect();
207 if values.is_empty() {
208 return Err(Error::Validation("whenIn() requires at least one value.".into()));
209 }
210 self.whens.push(WhenClause::new(
211 Kind::In,
212 Some(column.into()),
213 None,
214 Value::Null,
215 then.into_value(),
216 values,
217 None,
218 Vec::new(),
219 ));
220 Ok(self)
221 }
222
223 /// `WHEN condition THEN then` with raw SQL and its bindings.
224 ///
225 /// PHP: `whenRaw()`.
226 pub fn when_raw(
227 &mut self,
228 condition: impl Into<String>,
229 then: impl IntoValue,
230 bindings: impl IntoValues,
231 ) -> &mut Self {
232 self.whens.push(WhenClause::new(
233 Kind::Raw,
234 None,
235 None,
236 Value::Null,
237 then.into_value(),
238 Vec::new(),
239 Some(condition.into()),
240 bindings.into_values().values().cloned().collect(),
241 ));
242 self
243 }
244
245 /// `ELSE value`.
246 ///
247 /// PHP: `else()`.
248 pub fn else_(&mut self, value: impl IntoValue) -> &mut Self {
249 self.has_else = true;
250 self.else_value = value.into_value();
251 self
252 }
253
254 /// The alias (`AS alias`).
255 ///
256 /// PHP: `alias()`.
257 pub fn alias(&mut self, alias: impl Into<String>) -> &mut Self {
258 self.alias = alias.into();
259 self
260 }
261
262 /// The `WHEN` clauses.
263 ///
264 /// PHP: `getWhens()`.
265 pub fn whens(&self) -> &[WhenClause] {
266 &self.whens
267 }
268
269 /// Whether an `ELSE` was set.
270 ///
271 /// PHP: `hasElse()`.
272 pub fn has_else(&self) -> bool {
273 self.has_else
274 }
275
276 /// The `ELSE` value (`null` when none).
277 ///
278 /// PHP: `getElse()`.
279 pub fn else_value(&self) -> &Value {
280 &self.else_value
281 }
282
283 /// The alias, or `""`.
284 ///
285 /// PHP: `getAlias()`.
286 pub fn get_alias(&self) -> &str {
287 &self.alias
288 }
289}