Skip to main content

vibesql/ast/
expr.rs

1//! Expression AST definitions.
2//!
3//! This module defines the expression types for the SQL AST.
4
5use super::{DataTypeSpec, Ident, ObjectName, Query, WindowSpec};
6use crate::error::Span;
7
8/// An SQL expression.
9#[derive(Debug, Clone, PartialEq)]
10pub struct Expr {
11    pub kind: ExprKind,
12    pub span: Span,
13}
14
15impl Expr {
16    pub fn new(kind: ExprKind, span: Span) -> Self {
17        Self { kind, span }
18    }
19
20    /// Create a boxed expression.
21    pub fn boxed(kind: ExprKind, span: Span) -> Box<Self> {
22        Box::new(Self::new(kind, span))
23    }
24}
25
26/// Expression kind.
27#[derive(Debug, Clone, PartialEq)]
28pub enum ExprKind {
29    // Literals
30    /// NULL literal
31    Null,
32    /// Boolean literal (TRUE/FALSE)
33    Boolean(bool),
34    /// Integer literal
35    Integer(i64),
36    /// Floating-point literal
37    Float(f64),
38    /// String literal
39    String(String),
40    /// Bytes literal
41    Bytes(Vec<u8>),
42    /// Array literal: [1, 2, 3] or ARRAY[1, 2, 3]
43    Array {
44        element_type: Option<Box<DataTypeSpec>>,
45        elements: Vec<Box<Expr>>,
46    },
47    /// Struct literal: STRUCT(1, 'a') or (1, 'a')
48    Struct { fields: Vec<StructField> },
49
50    // Identifiers and references
51    /// Simple identifier (column name)
52    Identifier(Ident),
53    /// Compound identifier (table.column or schema.table.column)
54    CompoundIdentifier(Vec<Ident>),
55    /// Parameter reference (@param or ?)
56    Parameter(Parameter),
57
58    // Operators
59    /// Unary operator
60    UnaryOp { op: UnaryOp, expr: Box<Expr> },
61    /// Binary operator
62    BinaryOp {
63        op: BinaryOp,
64        left: Box<Expr>,
65        right: Box<Expr>,
66    },
67
68    // Comparisons
69    /// BETWEEN expression
70    Between {
71        expr: Box<Expr>,
72        low: Box<Expr>,
73        high: Box<Expr>,
74        negated: bool,
75    },
76    /// IN expression (expr IN (values) or expr IN (subquery))
77    In {
78        expr: Box<Expr>,
79        list: InList,
80        negated: bool,
81    },
82    /// LIKE expression
83    Like {
84        expr: Box<Expr>,
85        pattern: Box<Expr>,
86        escape: Option<Box<Expr>>,
87        negated: bool,
88    },
89    /// IS NULL / IS NOT NULL / IS TRUE / IS FALSE / IS UNKNOWN
90    IsExpr {
91        expr: Box<Expr>,
92        test: IsTest,
93        negated: bool,
94    },
95    /// IS DISTINCT FROM
96    IsDistinct {
97        left: Box<Expr>,
98        right: Box<Expr>,
99        negated: bool,
100    },
101
102    // Functions
103    /// Function call
104    Function(FunctionCall),
105    /// Aggregate function call
106    Aggregate(AggregateCall),
107    /// Window function call
108    WindowFunction(WindowFunctionCall),
109
110    // Type operations
111    /// CAST(expr AS type)
112    Cast {
113        expr: Box<Expr>,
114        data_type: DataTypeSpec,
115        safe: bool, // SAFE_CAST
116    },
117    /// EXTRACT(part FROM expr)
118    Extract {
119        field: DateTimePart,
120        from: Box<Expr>,
121    },
122
123    // Conditional expressions
124    /// CASE expression
125    Case {
126        operand: Option<Box<Expr>>,
127        conditions: Vec<(Box<Expr>, Box<Expr>)>,
128        else_result: Option<Box<Expr>>,
129    },
130    /// IF(condition, then_expr, else_expr)
131    If {
132        condition: Box<Expr>,
133        then_expr: Box<Expr>,
134        else_expr: Box<Expr>,
135    },
136    /// COALESCE(expr1, expr2, ...)
137    Coalesce(Vec<Box<Expr>>),
138    /// NULLIF(expr1, expr2)
139    Nullif { left: Box<Expr>, right: Box<Expr> },
140    /// IFNULL(expr1, expr2)
141    IfNull {
142        expr: Box<Expr>,
143        null_replacement: Box<Expr>,
144    },
145
146    // Subqueries
147    /// Scalar subquery
148    Subquery(Box<Query>),
149    /// EXISTS subquery
150    Exists { subquery: Box<Query>, negated: bool },
151    /// ANY/SOME/ALL subquery
152    SubqueryOp {
153        left: Box<Expr>,
154        op: BinaryOp,
155        modifier: SubqueryModifier,
156        subquery: Box<Query>,
157    },
158    /// IN subquery
159    InSubquery {
160        expr: Box<Expr>,
161        subquery: Box<Query>,
162        negated: bool,
163    },
164
165    // Array operations
166    /// Array subscript: `array[index]`
167    ArraySubscript {
168        array: Box<Expr>,
169        index: ArraySubscriptKind,
170    },
171    /// Array element access with SAFE: `array[SAFE_OFFSET(index)]`
172    SafeArraySubscript {
173        array: Box<Expr>,
174        index: Box<Expr>,
175        offset_type: ArrayOffsetType,
176    },
177
178    // Struct/JSON operations
179    /// Field access: expr.field
180    FieldAccess { expr: Box<Expr>, field: Ident },
181    /// JSON subscript: `json['field']` or `json[index]`
182    JsonSubscript { expr: Box<Expr>, key: JsonKey },
183
184    // Special expressions
185    /// Interval literal: INTERVAL expr UNIT
186    Interval {
187        value: Box<Expr>,
188        unit: IntervalUnit,
189    },
190    /// Date/Time/Timestamp/Datetime literal with type prefix
191    TypedLiteral {
192        data_type: TypedLiteralType,
193        value: String,
194    },
195    /// Parenthesized expression
196    Parenthesized(Box<Expr>),
197    /// Row constructor: ROW(expr1, expr2, ...)
198    Row(Vec<Box<Expr>>),
199}
200
201/// Struct field in struct literal.
202#[derive(Debug, Clone, PartialEq)]
203pub struct StructField {
204    pub name: Option<Ident>,
205    pub value: Box<Expr>,
206}
207
208/// Query parameter.
209#[derive(Debug, Clone, PartialEq)]
210pub enum Parameter {
211    Named(String),
212    Positional(u32),
213}
214
215/// Unary operator.
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub enum UnaryOp {
218    Plus,
219    Minus,
220    Not,
221    BitwiseNot,
222}
223
224impl std::fmt::Display for UnaryOp {
225    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226        match self {
227            UnaryOp::Plus => write!(f, "+"),
228            UnaryOp::Minus => write!(f, "-"),
229            UnaryOp::Not => write!(f, "NOT"),
230            UnaryOp::BitwiseNot => write!(f, "~"),
231        }
232    }
233}
234
235/// Binary operator.
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
237pub enum BinaryOp {
238    // Arithmetic
239    Plus,
240    Minus,
241    Multiply,
242    Divide,
243    Modulo,
244
245    // Comparison
246    Eq,
247    NotEq,
248    Lt,
249    LtEq,
250    Gt,
251    GtEq,
252
253    // Logical
254    And,
255    Or,
256
257    // Bitwise
258    BitwiseAnd,
259    BitwiseOr,
260    BitwiseXor,
261    LeftShift,
262    RightShift,
263
264    // String/Array
265    Concat,
266}
267
268impl BinaryOp {
269    /// Get the precedence of this operator (higher = binds tighter).
270    pub fn precedence(&self) -> u8 {
271        match self {
272            BinaryOp::Or => 1,
273            BinaryOp::And => 2,
274            BinaryOp::BitwiseOr => 3,
275            BinaryOp::BitwiseXor => 4,
276            BinaryOp::BitwiseAnd => 5,
277            BinaryOp::LeftShift | BinaryOp::RightShift => 6,
278            BinaryOp::Plus | BinaryOp::Minus => 7,
279            BinaryOp::Multiply | BinaryOp::Divide | BinaryOp::Modulo | BinaryOp::Concat => 8,
280            BinaryOp::Eq
281            | BinaryOp::NotEq
282            | BinaryOp::Lt
283            | BinaryOp::LtEq
284            | BinaryOp::Gt
285            | BinaryOp::GtEq => 9,
286        }
287    }
288
289    /// Check if this operator is left-associative.
290    pub fn is_left_associative(&self) -> bool {
291        true // All binary operators in SQL are left-associative
292    }
293}
294
295impl std::fmt::Display for BinaryOp {
296    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297        match self {
298            BinaryOp::Plus => write!(f, "+"),
299            BinaryOp::Minus => write!(f, "-"),
300            BinaryOp::Multiply => write!(f, "*"),
301            BinaryOp::Divide => write!(f, "/"),
302            BinaryOp::Modulo => write!(f, "%"),
303            BinaryOp::Eq => write!(f, "="),
304            BinaryOp::NotEq => write!(f, "!="),
305            BinaryOp::Lt => write!(f, "<"),
306            BinaryOp::LtEq => write!(f, "<="),
307            BinaryOp::Gt => write!(f, ">"),
308            BinaryOp::GtEq => write!(f, ">="),
309            BinaryOp::And => write!(f, "AND"),
310            BinaryOp::Or => write!(f, "OR"),
311            BinaryOp::BitwiseAnd => write!(f, "&"),
312            BinaryOp::BitwiseOr => write!(f, "|"),
313            BinaryOp::BitwiseXor => write!(f, "^"),
314            BinaryOp::LeftShift => write!(f, "<<"),
315            BinaryOp::RightShift => write!(f, ">>"),
316            BinaryOp::Concat => write!(f, "||"),
317        }
318    }
319}
320
321/// IN list variants.
322#[derive(Debug, Clone, PartialEq)]
323pub enum InList {
324    Values(Vec<Box<Expr>>),
325    Subquery(Box<Query>),
326}
327
328/// IS test type.
329#[derive(Debug, Clone, Copy, PartialEq, Eq)]
330pub enum IsTest {
331    Null,
332    True,
333    False,
334    Unknown,
335}
336
337/// Subquery modifier for ANY/SOME/ALL.
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339pub enum SubqueryModifier {
340    Any,
341    Some,
342    All,
343}
344
345/// Array subscript kind.
346#[derive(Debug, Clone, PartialEq)]
347pub enum ArraySubscriptKind {
348    /// Simple index: `array[0]`
349    Index(Box<Expr>),
350    /// OFFSET: `array[OFFSET(0)]`
351    Offset(Box<Expr>),
352    /// ORDINAL: `array[ORDINAL(1)]`
353    Ordinal(Box<Expr>),
354    /// SAFE_OFFSET: `array[SAFE_OFFSET(0)]`
355    SafeOffset(Box<Expr>),
356    /// SAFE_ORDINAL: `array[SAFE_ORDINAL(1)]`
357    SafeOrdinal(Box<Expr>),
358}
359
360/// Array offset type for safe access.
361#[derive(Debug, Clone, Copy, PartialEq, Eq)]
362pub enum ArrayOffsetType {
363    Offset,
364    Ordinal,
365}
366
367/// JSON key type.
368#[derive(Debug, Clone, PartialEq)]
369pub enum JsonKey {
370    String(String),
371    Index(Box<Expr>),
372}
373
374/// Function call.
375#[derive(Debug, Clone, PartialEq)]
376pub struct FunctionCall {
377    pub name: ObjectName,
378    pub args: Vec<FunctionArg>,
379    pub distinct: bool,
380    pub null_treatment: Option<NullTreatment>,
381    pub order_by: Vec<super::OrderByExpr>,
382    pub limit: Option<Box<Expr>>,
383}
384
385/// Function argument.
386#[derive(Debug, Clone, PartialEq)]
387pub enum FunctionArg {
388    /// Unnamed argument
389    Unnamed(Box<Expr>),
390    /// Named argument: name => value
391    Named { name: Ident, value: Box<Expr> },
392    /// Star argument: COUNT(*)
393    Star,
394}
395
396/// Null treatment in window/aggregate functions.
397#[derive(Debug, Clone, Copy, PartialEq, Eq)]
398pub enum NullTreatment {
399    RespectNulls,
400    IgnoreNulls,
401}
402
403/// Aggregate function call.
404#[derive(Debug, Clone, PartialEq)]
405pub struct AggregateCall {
406    pub function: FunctionCall,
407    pub filter: Option<Box<Expr>>,
408}
409
410/// Window function call.
411#[derive(Debug, Clone, PartialEq)]
412pub struct WindowFunctionCall {
413    pub function: FunctionCall,
414    pub window: WindowSpecOrRef,
415}
416
417/// Window specification or reference.
418#[derive(Debug, Clone, PartialEq)]
419pub enum WindowSpecOrRef {
420    Spec(WindowSpec),
421    Ref(Ident),
422}
423
424/// Date/time part for EXTRACT.
425#[derive(Debug, Clone, Copy, PartialEq, Eq)]
426pub enum DateTimePart {
427    Year,
428    Month,
429    Day,
430    Hour,
431    Minute,
432    Second,
433    Millisecond,
434    Microsecond,
435    Nanosecond,
436    Dayofweek,
437    Dayofyear,
438    Week,
439    Quarter,
440    Date,
441    Time,
442    Datetime,
443    Isoweek,
444    Isoyear,
445}
446
447impl DateTimePart {
448    /// Parse a datetime part from a string.
449    pub fn parse(s: &str) -> Option<Self> {
450        match s.to_uppercase().as_str() {
451            "YEAR" => Some(DateTimePart::Year),
452            "MONTH" => Some(DateTimePart::Month),
453            "DAY" => Some(DateTimePart::Day),
454            "HOUR" => Some(DateTimePart::Hour),
455            "MINUTE" => Some(DateTimePart::Minute),
456            "SECOND" => Some(DateTimePart::Second),
457            "MILLISECOND" => Some(DateTimePart::Millisecond),
458            "MICROSECOND" => Some(DateTimePart::Microsecond),
459            "NANOSECOND" => Some(DateTimePart::Nanosecond),
460            "DAYOFWEEK" => Some(DateTimePart::Dayofweek),
461            "DAYOFYEAR" => Some(DateTimePart::Dayofyear),
462            "WEEK" => Some(DateTimePart::Week),
463            "QUARTER" => Some(DateTimePart::Quarter),
464            "DATE" => Some(DateTimePart::Date),
465            "TIME" => Some(DateTimePart::Time),
466            "DATETIME" => Some(DateTimePart::Datetime),
467            "ISOWEEK" => Some(DateTimePart::Isoweek),
468            "ISOYEAR" => Some(DateTimePart::Isoyear),
469            _ => None,
470        }
471    }
472}
473
474/// Interval unit.
475#[derive(Debug, Clone, Copy, PartialEq, Eq)]
476pub enum IntervalUnit {
477    Year,
478    Month,
479    Day,
480    Hour,
481    Minute,
482    Second,
483    Millisecond,
484    Microsecond,
485    Nanosecond,
486    Week,
487    Quarter,
488}
489
490impl IntervalUnit {
491    /// Parse an interval unit from a string.
492    pub fn parse(s: &str) -> Option<Self> {
493        match s.to_uppercase().as_str() {
494            "YEAR" | "YEARS" => Some(IntervalUnit::Year),
495            "MONTH" | "MONTHS" => Some(IntervalUnit::Month),
496            "DAY" | "DAYS" => Some(IntervalUnit::Day),
497            "HOUR" | "HOURS" => Some(IntervalUnit::Hour),
498            "MINUTE" | "MINUTES" => Some(IntervalUnit::Minute),
499            "SECOND" | "SECONDS" => Some(IntervalUnit::Second),
500            "MILLISECOND" | "MILLISECONDS" => Some(IntervalUnit::Millisecond),
501            "MICROSECOND" | "MICROSECONDS" => Some(IntervalUnit::Microsecond),
502            "NANOSECOND" | "NANOSECONDS" => Some(IntervalUnit::Nanosecond),
503            "WEEK" | "WEEKS" => Some(IntervalUnit::Week),
504            "QUARTER" | "QUARTERS" => Some(IntervalUnit::Quarter),
505            _ => None,
506        }
507    }
508}
509
510/// Typed literal type (DATE, TIME, TIMESTAMP, DATETIME, JSON, etc.).
511#[derive(Debug, Clone, Copy, PartialEq, Eq)]
512pub enum TypedLiteralType {
513    Date,
514    Time,
515    Timestamp,
516    Datetime,
517    Json,
518    Numeric,
519    Bignumeric,
520    Range,
521}
522
523impl TypedLiteralType {
524    /// Parse a typed literal type from a string.
525    pub fn parse(s: &str) -> Option<Self> {
526        match s.to_uppercase().as_str() {
527            "DATE" => Some(TypedLiteralType::Date),
528            "TIME" => Some(TypedLiteralType::Time),
529            "TIMESTAMP" => Some(TypedLiteralType::Timestamp),
530            "DATETIME" => Some(TypedLiteralType::Datetime),
531            "JSON" => Some(TypedLiteralType::Json),
532            "NUMERIC" | "DECIMAL" => Some(TypedLiteralType::Numeric),
533            "BIGNUMERIC" | "BIGDECIMAL" => Some(TypedLiteralType::Bignumeric),
534            "RANGE" => Some(TypedLiteralType::Range),
535            _ => None,
536        }
537    }
538}
539
540#[cfg(test)]
541mod tests {
542    use super::*;
543
544    #[test]
545    fn test_binary_op_precedence() {
546        assert!(BinaryOp::Multiply.precedence() > BinaryOp::Plus.precedence());
547        assert!(BinaryOp::And.precedence() > BinaryOp::Or.precedence());
548        assert!(BinaryOp::Eq.precedence() > BinaryOp::And.precedence());
549    }
550
551    #[test]
552    fn test_datetime_part_from_str() {
553        assert_eq!(DateTimePart::parse("YEAR"), Some(DateTimePart::Year));
554        assert_eq!(DateTimePart::parse("year"), Some(DateTimePart::Year));
555        assert_eq!(DateTimePart::parse("invalid"), None);
556    }
557
558    #[test]
559    fn test_interval_unit_from_str() {
560        assert_eq!(IntervalUnit::parse("DAY"), Some(IntervalUnit::Day));
561        assert_eq!(IntervalUnit::parse("DAYS"), Some(IntervalUnit::Day));
562        assert_eq!(IntervalUnit::parse("invalid"), None);
563    }
564}