proof_of_sql_parser/
intermediate_ast.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! This module contains the AST nodes for the intermediate representation of a Proof of SQL query.
/***
* These AST nodes are closely following vervolg:
* https://docs.rs/vervolg/latest/vervolg/ast/enum.Statement.html
***/

use crate::{intermediate_decimal::IntermediateDecimal, posql_time::PoSQLTimestamp, Identifier};
use alloc::{boxed::Box, string::String, vec::Vec};
use core::{
    fmt,
    fmt::{Display, Formatter},
    hash::Hash,
};
use serde::{Deserialize, Serialize};

/// Representation of a SetExpression, a collection of rows, each having one or more columns.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub enum SetExpression {
    /// Query result as `SetExpression`
    Query {
        /// Result expressions e.g. `a` and `b` in `SELECT a, b FROM table`
        result_exprs: Vec<SelectResultExpr>,
        /// Table expression e.g. `table` in `SELECT a, b FROM table`
        from: Vec<Box<TableExpression>>,
        /// Filter expression e.g. `a > 5` in `SELECT a, b FROM table WHERE a > 5`
        /// If None, no filter is applied
        where_expr: Option<Box<Expression>>,
        /// Group by expressions e.g. `a` in `SELECT a, COUNT(*) FROM table GROUP BY a`
        group_by: Vec<Identifier>,
    },
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
/// What to select in a query
pub enum SelectResultExpr {
    /// All columns in a table e.g. `SELECT * FROM table`
    ALL,
    /// A single expression e.g. `SELECT a FROM table`
    AliasedResultExpr(AliasedResultExpr),
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
/// An expression with an alias e.g. `a + 1 AS b`
pub struct AliasedResultExpr {
    /// The expression e.g. `a + 1`, `COUNT(*)`, etc.
    pub expr: Box<Expression>,
    /// The alias e.g. `count` in `COUNT(*) AS count`
    pub alias: Identifier,
}

impl AliasedResultExpr {
    /// Create a new `AliasedResultExpr`
    pub fn new(expr: Expression, alias: Identifier) -> Self {
        Self {
            expr: Box::new(expr),
            alias,
        }
    }

    /// Try to get the identifier of the expression if it is a column
    /// Otherwise return None
    pub fn try_as_identifier(&self) -> Option<&Identifier> {
        match self.expr.as_ref() {
            Expression::Column(column) => Some(column),
            _ => None,
        }
    }
}

/// Representations of base queries
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub enum TableExpression {
    /// The row set of a given table; possibly providing an alias
    Named {
        /// The qualified table Identifier
        table: Identifier,
        /// Namespace / schema for the table
        schema: Option<Identifier>,
    },
}

/// Binary operators for simple expressions
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum BinaryOperator {
    /// Numeric addition
    Add,

    /// Numeric subtraction
    Subtract,

    /// Numeric multiplication
    Multiply,

    /// Numeric division
    Division,

    /// Logical And
    And,

    /// Logical Or
    Or,

    /// Comparison =
    Equal,

    /// Comparison <=
    LessThanOrEqual,

    /// Comparison >=
    GreaterThanOrEqual,
}

/// Possible unary operators for simple expressions
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum UnaryOperator {
    /// Logical inversion
    Not,
}

// Aggregation operators
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone, Copy)]
/// Aggregation operators
pub enum AggregationOperator {
    /// Maximum
    Max,
    /// Minimum
    Min,
    /// Sum
    Sum,
    /// Count
    Count,
    /// Return the first value
    First,
}

impl Display for AggregationOperator {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            AggregationOperator::Max => write!(f, "max"),
            AggregationOperator::Min => write!(f, "min"),
            AggregationOperator::Sum => write!(f, "sum"),
            AggregationOperator::Count => write!(f, "count"),
            AggregationOperator::First => write!(f, "first"),
        }
    }
}

/// Boolean Expressions
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Hash)]
pub enum Expression {
    /// Literal
    Literal(Literal),

    /// Column
    Column(Identifier),

    /// Unary operation
    Unary {
        /// The unary operator
        op: UnaryOperator,
        /// The expression to apply the operator to
        expr: Box<Expression>,
    },

    /// Binary operation
    Binary {
        /// The binary operator
        op: BinaryOperator,
        /// The left hand side of the operation
        left: Box<Expression>,
        /// The right hand side of the operation
        right: Box<Expression>,
    },

    /// * expression
    Wildcard,

    /// Aggregation operation
    Aggregation {
        /// The aggregation operator
        op: AggregationOperator,
        /// The expression to aggregate
        expr: Box<Expression>,
    },
}

impl Expression {
    /// Create a new SUM()
    pub fn sum(self) -> Box<Self> {
        Box::new(Expression::Aggregation {
            op: AggregationOperator::Sum,
            expr: Box::new(self),
        })
    }

    /// Create a new MAX()
    pub fn max(self) -> Box<Self> {
        Box::new(Expression::Aggregation {
            op: AggregationOperator::Max,
            expr: Box::new(self),
        })
    }

    /// Create a new MIN()
    pub fn min(self) -> Box<Self> {
        Box::new(Expression::Aggregation {
            op: AggregationOperator::Min,
            expr: Box::new(self),
        })
    }

    /// Create a new COUNT()
    pub fn count(self) -> Box<Self> {
        Box::new(Expression::Aggregation {
            op: AggregationOperator::Count,
            expr: Box::new(self),
        })
    }

    /// Create a new FIRST()
    pub fn first(self) -> Box<Self> {
        Box::new(Expression::Aggregation {
            op: AggregationOperator::First,
            expr: Box::new(self),
        })
    }
    /// Create an `AliasedResultExpr` from an `Expression` using the provided alias.
    pub fn alias(self, alias: &str) -> AliasedResultExpr {
        AliasedResultExpr {
            expr: Box::new(self),
            alias: alias.parse().unwrap(),
        }
    }
}
impl core::ops::Add<Box<Expression>> for Box<Expression> {
    type Output = Box<Expression>;

    fn add(self, rhs: Box<Expression>) -> Box<Expression> {
        Box::new(Expression::Binary {
            op: BinaryOperator::Add,
            left: self,
            right: rhs,
        })
    }
}
impl core::ops::Mul<Box<Expression>> for Box<Expression> {
    type Output = Box<Expression>;

    fn mul(self, rhs: Box<Expression>) -> Box<Expression> {
        Box::new(Expression::Binary {
            op: BinaryOperator::Multiply,
            left: self,
            right: rhs,
        })
    }
}
impl core::ops::Div<Box<Expression>> for Box<Expression> {
    type Output = Box<Expression>;

    fn div(self, rhs: Box<Expression>) -> Box<Expression> {
        Box::new(Expression::Binary {
            op: BinaryOperator::Division,
            left: self,
            right: rhs,
        })
    }
}
impl core::ops::Sub<Box<Expression>> for Box<Expression> {
    type Output = Box<Expression>;

    fn sub(self, rhs: Box<Expression>) -> Box<Expression> {
        Box::new(Expression::Binary {
            op: BinaryOperator::Subtract,
            left: self,
            right: rhs,
        })
    }
}

/// OrderBy
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct OrderBy {
    /// which column to order by
    pub expr: Identifier,
    /// in which direction to order
    pub direction: OrderByDirection,
}

/// OrderByDirection values
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Copy)]
pub enum OrderByDirection {
    /// Ascending
    Asc,
    /// Descending
    Desc,
}

impl Display for OrderByDirection {
    // This trait requires `fmt` with this exact signature.
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            OrderByDirection::Asc => write!(f, "asc"),
            OrderByDirection::Desc => write!(f, "desc"),
        }
    }
}

/// Limits for a limit clause
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct Slice {
    /// number of rows to return
    ///
    /// if u64::MAX, specify all rows
    pub number_rows: u64,

    /// number of rows to skip
    ///
    /// if 0, specify the first row as starting point
    /// if negative, specify the offset from the end
    /// (e.g. -1 is the last row, -2 is the second to last row, etc.)
    pub offset_value: i64,
}

/// Literal values
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Hash)]
pub enum Literal {
    /// Boolean Literal
    Boolean(bool),
    /// i64 Literal
    BigInt(i64),
    /// i128 Literal
    Int128(i128),
    /// String Literal
    VarChar(String),
    /// Decimal Literal
    Decimal(IntermediateDecimal),
    /// Timestamp Literal
    Timestamp(PoSQLTimestamp),
}

impl From<bool> for Literal {
    fn from(val: bool) -> Self {
        Literal::Boolean(val)
    }
}

/// TODO: add docs
macro_rules! impl_int_to_literal {
    ($tt:ty) => {
        impl From<$tt> for Literal {
            fn from(val: $tt) -> Self {
                Literal::BigInt(val as i64)
            }
        }
    };
}

impl_int_to_literal!(i8);
impl_int_to_literal!(u8);
impl_int_to_literal!(i16);
impl_int_to_literal!(u16);
impl_int_to_literal!(i32);
impl_int_to_literal!(u32);
impl_int_to_literal!(i64);

impl From<i128> for Literal {
    fn from(val: i128) -> Self {
        Literal::Int128(val)
    }
}

/// TODO: add docs
macro_rules! impl_string_to_literal {
    ($tt:ty) => {
        impl From<$tt> for Literal {
            fn from(val: $tt) -> Self {
                Literal::VarChar(val.into())
            }
        }
    };
}

impl_string_to_literal!(&str);
impl_string_to_literal!(String);

impl From<IntermediateDecimal> for Literal {
    fn from(val: IntermediateDecimal) -> Self {
        Literal::Decimal(val)
    }
}

impl From<PoSQLTimestamp> for Literal {
    fn from(time: PoSQLTimestamp) -> Self {
        Literal::Timestamp(time)
    }
}

/// Helper function to append an item to a vector
pub(crate) fn append<T>(list: Vec<T>, item: T) -> Vec<T> {
    let mut result = list;
    result.push(item);
    result
}