1use serde::{Deserialize, Serialize};
6use std::fmt;
7
8use super::ExprDataType;
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
12pub enum Expr {
13 Column(String),
15 Literal(Literal),
17 BinaryOp {
19 left: Box<Expr>,
21 op: BinaryOperator,
23 right: Box<Expr>,
25 },
26 UnaryOp {
28 op: UnaryOperator,
30 expr: Box<Expr>,
32 },
33 Function {
35 name: String,
37 args: Vec<Expr>,
39 },
40 Case {
42 when_then: Vec<(Expr, Expr)>,
44 else_expr: Option<Box<Expr>>,
46 },
47 Cast {
49 expr: Box<Expr>,
51 data_type: ExprDataType,
53 },
54 Coalesce {
56 exprs: Vec<Expr>,
58 },
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize)]
63pub enum Literal {
64 Null,
66 Boolean(bool),
68 Integer(i64),
70 Float(f64),
72 String(String),
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
78pub enum BinaryOperator {
79 Add,
81 Subtract,
83 Multiply,
85 Divide,
87 Modulo,
89 Equal,
91 NotEqual,
93 LessThan,
95 LessThanOrEqual,
97 GreaterThan,
99 GreaterThanOrEqual,
101 And,
103 Or,
105 BitwiseAnd,
107 BitwiseOr,
109 BitwiseXor,
111 Like,
113 Concat,
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
119pub enum UnaryOperator {
120 Negate,
122 Not,
124 IsNull,
126 IsNotNull,
128}
129
130impl fmt::Display for Literal {
132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133 match self {
134 Self::Null => write!(f, "NULL"),
135 Self::Boolean(b) => write!(f, "{}", if *b { "TRUE" } else { "FALSE" }),
136 Self::Integer(i) => write!(f, "{}", i),
137 Self::Float(fl) => write!(f, "{}", fl),
138 Self::String(s) => write!(f, "'{}'", s.replace('\'', "''")), }
140 }
141}
142
143impl fmt::Display for BinaryOperator {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 match self {
146 Self::Add => write!(f, "+"),
147 Self::Subtract => write!(f, "-"),
148 Self::Multiply => write!(f, "*"),
149 Self::Divide => write!(f, "/"),
150 Self::Modulo => write!(f, "%"),
151 Self::Equal => write!(f, "="),
152 Self::NotEqual => write!(f, "<>"),
153 Self::LessThan => write!(f, "<"),
154 Self::LessThanOrEqual => write!(f, "<="),
155 Self::GreaterThan => write!(f, ">"),
156 Self::GreaterThanOrEqual => write!(f, ">="),
157 Self::And => write!(f, "AND"),
158 Self::Or => write!(f, "OR"),
159 Self::BitwiseAnd => write!(f, "&"),
160 Self::BitwiseOr => write!(f, "|"),
161 Self::BitwiseXor => write!(f, "^"),
162 Self::Like => write!(f, "LIKE"),
163 Self::Concat => write!(f, "||"),
164 }
165 }
166}
167
168impl fmt::Display for UnaryOperator {
169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 match self {
171 Self::Negate => write!(f, "-"),
172 Self::Not => write!(f, "NOT "),
173 Self::IsNull => write!(f, "IS NULL"),
174 Self::IsNotNull => write!(f, "IS NOT NULL"),
175 }
176 }
177}
178
179impl fmt::Display for Expr {
180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181 match self {
182 Self::Column(name) => write!(f, "{}", name),
183 Self::Literal(value) => write!(f, "{}", value),
184 Self::BinaryOp { left, op, right } => {
185 write!(f, "({} {} {})", left, op, right)
186 }
187 Self::UnaryOp { op, expr } => match op {
188 UnaryOperator::IsNull | UnaryOperator::IsNotNull => {
189 write!(f, "({} {})", expr, op)
190 }
191 _ => write!(f, "{}({})", op, expr),
192 },
193 Self::Function { name, args } => {
194 write!(f, "{}(", name)?;
195 for (i, arg) in args.iter().enumerate() {
196 if i > 0 {
197 write!(f, ", ")?;
198 }
199 write!(f, "{}", arg)?;
200 }
201 write!(f, ")")
202 }
203 Self::Case {
204 when_then,
205 else_expr,
206 } => {
207 write!(f, "CASE")?;
208 for (when, then) in when_then {
209 write!(f, " WHEN {} THEN {}", when, then)?;
210 }
211 if let Some(else_expr) = else_expr {
212 write!(f, " ELSE {}", else_expr)?;
213 }
214 write!(f, " END")
215 }
216 Self::Cast { expr, data_type } => {
217 write!(f, "CAST({} AS {})", expr, data_type)
218 }
219 Self::Coalesce { exprs } => {
220 write!(f, "COALESCE(")?;
221 for (i, expr) in exprs.iter().enumerate() {
222 if i > 0 {
223 write!(f, ", ")?;
224 }
225 write!(f, "{}", expr)?;
226 }
227 write!(f, ")")
228 }
229 }
230 }
231}
232
233impl Expr {
235 pub fn col(name: impl Into<String>) -> Self {
237 Self::Column(name.into())
238 }
239
240 pub fn lit<T: Into<Literal>>(value: T) -> Self {
242 Self::Literal(value.into())
243 }
244
245 pub fn null() -> Self {
247 Self::Literal(Literal::Null)
248 }
249
250 pub fn call(name: impl Into<String>, args: Vec<Expr>) -> Self {
252 Self::Function {
253 name: name.into(),
254 args,
255 }
256 }
257
258 pub fn binary(left: Expr, op: BinaryOperator, right: Expr) -> Self {
260 Self::BinaryOp {
261 left: Box::new(left),
262 op,
263 right: Box::new(right),
264 }
265 }
266
267 pub fn unary(op: UnaryOperator, expr: Expr) -> Self {
269 Self::UnaryOp {
270 op,
271 expr: Box::new(expr),
272 }
273 }
274
275 pub fn case(when_then: Vec<(Expr, Expr)>, else_expr: Option<Expr>) -> Self {
277 Self::Case {
278 when_then,
279 else_expr: else_expr.map(Box::new),
280 }
281 }
282
283 pub fn cast(expr: Expr, data_type: ExprDataType) -> Self {
285 Self::Cast {
286 expr: Box::new(expr),
287 data_type,
288 }
289 }
290
291 pub fn coalesce(exprs: Vec<Expr>) -> Self {
293 Self::Coalesce { exprs }
294 }
295
296 pub fn add(self, other: Expr) -> Self {
298 Self::binary(self, BinaryOperator::Add, other)
299 }
300
301 pub fn sub(self, other: Expr) -> Self {
303 Self::binary(self, BinaryOperator::Subtract, other)
304 }
305
306 pub fn mul(self, other: Expr) -> Self {
308 Self::binary(self, BinaryOperator::Multiply, other)
309 }
310
311 pub fn div(self, other: Expr) -> Self {
313 Self::binary(self, BinaryOperator::Divide, other)
314 }
315
316 pub fn modulo(self, other: Expr) -> Self {
318 Self::binary(self, BinaryOperator::Modulo, other)
319 }
320
321 pub fn eq(self, other: Expr) -> Self {
323 Self::binary(self, BinaryOperator::Equal, other)
324 }
325
326 pub fn neq(self, other: Expr) -> Self {
328 Self::binary(self, BinaryOperator::NotEqual, other)
329 }
330
331 pub fn lt(self, other: Expr) -> Self {
333 Self::binary(self, BinaryOperator::LessThan, other)
334 }
335
336 pub fn lte(self, other: Expr) -> Self {
338 Self::binary(self, BinaryOperator::LessThanOrEqual, other)
339 }
340
341 pub fn gt(self, other: Expr) -> Self {
343 Self::binary(self, BinaryOperator::GreaterThan, other)
344 }
345
346 pub fn gte(self, other: Expr) -> Self {
348 Self::binary(self, BinaryOperator::GreaterThanOrEqual, other)
349 }
350
351 pub fn and(self, other: Expr) -> Self {
353 Self::binary(self, BinaryOperator::And, other)
354 }
355
356 pub fn or(self, other: Expr) -> Self {
358 Self::binary(self, BinaryOperator::Or, other)
359 }
360
361 pub fn like(self, pattern: impl Into<String>) -> Self {
363 Self::binary(self, BinaryOperator::Like, Self::lit(pattern.into()))
364 }
365
366 pub fn concat(self, other: Expr) -> Self {
368 Self::binary(self, BinaryOperator::Concat, other)
369 }
370
371 pub fn negate(self) -> Self {
373 Self::unary(UnaryOperator::Negate, self)
374 }
375
376 pub fn not(self) -> Self {
378 Self::unary(UnaryOperator::Not, self)
379 }
380
381 pub fn is_null(self) -> Self {
383 Self::unary(UnaryOperator::IsNull, self)
384 }
385
386 pub fn is_not_null(self) -> Self {
388 Self::unary(UnaryOperator::IsNotNull, self)
389 }
390
391 pub fn to_boolean(self) -> Self {
393 Self::cast(self, ExprDataType::Boolean)
394 }
395
396 pub fn to_integer(self) -> Self {
398 Self::cast(self, ExprDataType::Integer)
399 }
400
401 pub fn to_float(self) -> Self {
403 Self::cast(self, ExprDataType::Float)
404 }
405
406 pub fn to_string(self) -> Self {
408 Self::cast(self, ExprDataType::String)
409 }
410
411 pub fn to_date(self) -> Self {
413 Self::cast(self, ExprDataType::Date)
414 }
415
416 pub fn to_timestamp(self) -> Self {
418 Self::cast(self, ExprDataType::Timestamp)
419 }
420}
421
422impl From<bool> for Literal {
424 fn from(value: bool) -> Self {
425 Self::Boolean(value)
426 }
427}
428
429impl From<i64> for Literal {
430 fn from(value: i64) -> Self {
431 Self::Integer(value)
432 }
433}
434
435impl From<i32> for Literal {
436 fn from(value: i32) -> Self {
437 Self::Integer(value as i64)
438 }
439}
440
441impl From<f64> for Literal {
442 fn from(value: f64) -> Self {
443 Self::Float(value)
444 }
445}
446
447impl From<f32> for Literal {
448 fn from(value: f32) -> Self {
449 Self::Float(value as f64)
450 }
451}
452
453impl From<String> for Literal {
454 fn from(value: String) -> Self {
455 Self::String(value)
456 }
457}
458
459impl From<&str> for Literal {
460 fn from(value: &str) -> Self {
461 Self::String(value.to_string())
462 }
463}