Skip to main content

pandrs/distributed/expr/
core.rs

1//! # Core Expression System
2//!
3//! This module provides the core expression system for distributed processing.
4
5use serde::{Deserialize, Serialize};
6use std::fmt;
7
8use super::ExprDataType;
9
10/// Represents an expression that can be used in a distributed computation
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub enum Expr {
13    /// Column reference
14    Column(String),
15    /// Literal value
16    Literal(Literal),
17    /// Binary operation
18    BinaryOp {
19        /// Left operand
20        left: Box<Expr>,
21        /// Operator
22        op: BinaryOperator,
23        /// Right operand
24        right: Box<Expr>,
25    },
26    /// Unary operation
27    UnaryOp {
28        /// Operator
29        op: UnaryOperator,
30        /// Operand
31        expr: Box<Expr>,
32    },
33    /// Function call
34    Function {
35        /// Function name
36        name: String,
37        /// Arguments
38        args: Vec<Expr>,
39    },
40    /// Case statement
41    Case {
42        /// When conditions and results
43        when_then: Vec<(Expr, Expr)>,
44        /// Default result
45        else_expr: Option<Box<Expr>>,
46    },
47    /// CAST expression
48    Cast {
49        /// Input expression
50        expr: Box<Expr>,
51        /// Target data type
52        data_type: ExprDataType,
53    },
54    /// COALESCE expression
55    Coalesce {
56        /// Expressions to check
57        exprs: Vec<Expr>,
58    },
59}
60
61/// Represents a literal value in an expression
62#[derive(Debug, Clone, Serialize, Deserialize)]
63pub enum Literal {
64    /// Null value
65    Null,
66    /// Boolean value
67    Boolean(bool),
68    /// Integer value
69    Integer(i64),
70    /// Float value
71    Float(f64),
72    /// String value
73    String(String),
74}
75
76/// Types of binary operators
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
78pub enum BinaryOperator {
79    /// Addition (+)
80    Add,
81    /// Subtraction (-)
82    Subtract,
83    /// Multiplication (*)
84    Multiply,
85    /// Division (/)
86    Divide,
87    /// Modulo (%)
88    Modulo,
89    /// Equality (=)
90    Equal,
91    /// Inequality (<>)
92    NotEqual,
93    /// Less than (<)
94    LessThan,
95    /// Less than or equal to (<=)
96    LessThanOrEqual,
97    /// Greater than (>)
98    GreaterThan,
99    /// Greater than or equal to (>=)
100    GreaterThanOrEqual,
101    /// Logical AND
102    And,
103    /// Logical OR
104    Or,
105    /// Bitwise AND (&)
106    BitwiseAnd,
107    /// Bitwise OR (|)
108    BitwiseOr,
109    /// Bitwise XOR (^)
110    BitwiseXor,
111    /// Like pattern matching
112    Like,
113    /// String concatenation (||)
114    Concat,
115}
116
117/// Types of unary operators
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
119pub enum UnaryOperator {
120    /// Negation (-)
121    Negate,
122    /// Logical NOT
123    Not,
124    /// Is NULL
125    IsNull,
126    /// Is NOT NULL
127    IsNotNull,
128}
129
130// Display implementations
131impl 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('\'', "''")), // Escape single quotes
139        }
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
233// Factory methods for Expr
234impl Expr {
235    /// Creates a column reference
236    pub fn col(name: impl Into<String>) -> Self {
237        Self::Column(name.into())
238    }
239
240    /// Creates a literal value
241    pub fn lit<T: Into<Literal>>(value: T) -> Self {
242        Self::Literal(value.into())
243    }
244
245    /// Creates a literal NULL value
246    pub fn null() -> Self {
247        Self::Literal(Literal::Null)
248    }
249
250    /// Creates a function call
251    pub fn call(name: impl Into<String>, args: Vec<Expr>) -> Self {
252        Self::Function {
253            name: name.into(),
254            args,
255        }
256    }
257
258    /// Creates a binary operation
259    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    /// Creates a unary operation
268    pub fn unary(op: UnaryOperator, expr: Expr) -> Self {
269        Self::UnaryOp {
270            op,
271            expr: Box::new(expr),
272        }
273    }
274
275    /// Creates a CASE expression
276    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    /// Creates a CAST expression
284    pub fn cast(expr: Expr, data_type: ExprDataType) -> Self {
285        Self::Cast {
286            expr: Box::new(expr),
287            data_type,
288        }
289    }
290
291    /// Creates a COALESCE expression
292    pub fn coalesce(exprs: Vec<Expr>) -> Self {
293        Self::Coalesce { exprs }
294    }
295
296    /// Adds two expressions
297    pub fn add(self, other: Expr) -> Self {
298        Self::binary(self, BinaryOperator::Add, other)
299    }
300
301    /// Subtracts an expression from this one
302    pub fn sub(self, other: Expr) -> Self {
303        Self::binary(self, BinaryOperator::Subtract, other)
304    }
305
306    /// Multiplies this expression by another
307    pub fn mul(self, other: Expr) -> Self {
308        Self::binary(self, BinaryOperator::Multiply, other)
309    }
310
311    /// Divides this expression by another
312    pub fn div(self, other: Expr) -> Self {
313        Self::binary(self, BinaryOperator::Divide, other)
314    }
315
316    /// Applies modulo operation
317    pub fn modulo(self, other: Expr) -> Self {
318        Self::binary(self, BinaryOperator::Modulo, other)
319    }
320
321    /// Checks if this expression equals another
322    pub fn eq(self, other: Expr) -> Self {
323        Self::binary(self, BinaryOperator::Equal, other)
324    }
325
326    /// Checks if this expression does not equal another
327    pub fn neq(self, other: Expr) -> Self {
328        Self::binary(self, BinaryOperator::NotEqual, other)
329    }
330
331    /// Checks if this expression is less than another
332    pub fn lt(self, other: Expr) -> Self {
333        Self::binary(self, BinaryOperator::LessThan, other)
334    }
335
336    /// Checks if this expression is less than or equal to another
337    pub fn lte(self, other: Expr) -> Self {
338        Self::binary(self, BinaryOperator::LessThanOrEqual, other)
339    }
340
341    /// Checks if this expression is greater than another
342    pub fn gt(self, other: Expr) -> Self {
343        Self::binary(self, BinaryOperator::GreaterThan, other)
344    }
345
346    /// Checks if this expression is greater than or equal to another
347    pub fn gte(self, other: Expr) -> Self {
348        Self::binary(self, BinaryOperator::GreaterThanOrEqual, other)
349    }
350
351    /// Applies logical AND
352    pub fn and(self, other: Expr) -> Self {
353        Self::binary(self, BinaryOperator::And, other)
354    }
355
356    /// Applies logical OR
357    pub fn or(self, other: Expr) -> Self {
358        Self::binary(self, BinaryOperator::Or, other)
359    }
360
361    /// Applies LIKE pattern matching
362    pub fn like(self, pattern: impl Into<String>) -> Self {
363        Self::binary(self, BinaryOperator::Like, Self::lit(pattern.into()))
364    }
365
366    /// Concatenates with another string expression
367    pub fn concat(self, other: Expr) -> Self {
368        Self::binary(self, BinaryOperator::Concat, other)
369    }
370
371    /// Negates this expression
372    pub fn negate(self) -> Self {
373        Self::unary(UnaryOperator::Negate, self)
374    }
375
376    /// Applies logical NOT
377    pub fn not(self) -> Self {
378        Self::unary(UnaryOperator::Not, self)
379    }
380
381    /// Checks if this expression is NULL
382    pub fn is_null(self) -> Self {
383        Self::unary(UnaryOperator::IsNull, self)
384    }
385
386    /// Checks if this expression is NOT NULL
387    pub fn is_not_null(self) -> Self {
388        Self::unary(UnaryOperator::IsNotNull, self)
389    }
390
391    /// Casts this expression to boolean
392    pub fn to_boolean(self) -> Self {
393        Self::cast(self, ExprDataType::Boolean)
394    }
395
396    /// Casts this expression to integer
397    pub fn to_integer(self) -> Self {
398        Self::cast(self, ExprDataType::Integer)
399    }
400
401    /// Casts this expression to float
402    pub fn to_float(self) -> Self {
403        Self::cast(self, ExprDataType::Float)
404    }
405
406    /// Casts this expression to string
407    pub fn to_string(self) -> Self {
408        Self::cast(self, ExprDataType::String)
409    }
410
411    /// Casts this expression to date
412    pub fn to_date(self) -> Self {
413        Self::cast(self, ExprDataType::Date)
414    }
415
416    /// Casts this expression to timestamp
417    pub fn to_timestamp(self) -> Self {
418        Self::cast(self, ExprDataType::Timestamp)
419    }
420}
421
422// Conversions to Literal
423impl 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}