-
Notifications
You must be signed in to change notification settings - Fork 220
/
Copy pathmod.rs
393 lines (365 loc) · 14.4 KB
/
mod.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
// Copyright 2022 RisingLight Project Authors. Licensed under Apache-2.0.
use bitvec::prelude::BitVec;
use serde::Serialize;
use super::*;
use crate::catalog::ColumnRefId;
use crate::parser::{BinaryOperator, DateTimeField, Expr, Function, UnaryOperator, Value};
use crate::types::{DataType, DataTypeKind, DataValue, Interval, F64};
mod agg_call;
mod binary_op;
mod column_ref;
mod expr_with_alias;
mod input_ref;
mod isnull;
mod type_cast;
mod unary_op;
pub use self::agg_call::*;
pub use self::binary_op::*;
pub use self::column_ref::*;
pub use self::expr_with_alias::*;
pub use self::input_ref::*;
pub use self::isnull::*;
pub use self::type_cast::*;
pub use self::unary_op::*;
/// A bound expression.
#[derive(PartialEq, Clone, Serialize)]
pub enum BoundExpr {
Constant(DataValue),
ColumnRef(BoundColumnRef),
/// Only used after column ref is resolved into input ref
InputRef(BoundInputRef),
BinaryOp(BoundBinaryOp),
UnaryOp(BoundUnaryOp),
TypeCast(BoundTypeCast),
AggCall(BoundAggCall),
IsNull(BoundIsNull),
ExprWithAlias(BoundExprWithAlias),
Alias(BoundAlias),
}
impl BoundExpr {
pub fn return_type(&self) -> Option<DataType> {
match self {
Self::Constant(v) => v.data_type(),
Self::ColumnRef(expr) => Some(*expr.desc.datatype()),
Self::BinaryOp(expr) => expr.return_type,
Self::UnaryOp(expr) => expr.return_type,
Self::TypeCast(expr) => Some(expr.ty.nullable()),
Self::AggCall(expr) => Some(expr.return_type),
Self::InputRef(expr) => Some(expr.return_type),
Self::IsNull(_) => Some(DataTypeKind::Bool.not_null()),
Self::ExprWithAlias(expr) => expr.expr.return_type(),
Self::Alias(expr) => expr.expr.return_type(),
}
}
fn get_filter_column_inner(&self, filter_column: &mut BitVec) {
struct Visitor<'a>(&'a mut BitVec);
impl<'a> ExprVisitor for Visitor<'a> {
fn visit_input_ref(&mut self, expr: &BoundInputRef) {
self.0.set(expr.index, true)
}
}
Visitor(filter_column).visit_expr(self);
}
pub fn get_filter_column(&self, len: usize) -> BitVec {
let mut filter_column = BitVec::repeat(false, len);
self.get_filter_column_inner(&mut filter_column);
filter_column
}
pub fn contains_column_ref(&self) -> bool {
struct Visitor(bool);
impl ExprVisitor for Visitor {
fn visit_column_ref(&mut self, _: &BoundColumnRef) {
self.0 = true;
}
fn visit_alias(&mut self, _: &BoundAlias) {
self.0 = true;
}
}
let mut visitor = Visitor(false);
visitor.visit_expr(self);
visitor.0
}
pub fn contains_row_count(&self) -> bool {
struct Visitor(bool);
impl ExprVisitor for Visitor {
fn visit_agg_call(&mut self, expr: &BoundAggCall) {
self.0 = expr.kind == AggKind::RowCount;
}
}
let mut visitor = Visitor(false);
visitor.visit_expr(self);
visitor.0
}
pub fn resolve_column_ref_id(&self, column_ref_ids: &mut Vec<ColumnRefId>) {
struct Visitor<'a>(&'a mut Vec<ColumnRefId>);
impl<'a> ExprVisitor for Visitor<'a> {
fn visit_column_ref(&mut self, expr: &BoundColumnRef) {
self.0.push(expr.column_ref_id);
}
}
Visitor(column_ref_ids).visit_expr(self);
}
pub fn resolve_input_ref(&self, input_refs: &mut Vec<BoundInputRef>) {
struct Visitor<'a>(&'a mut Vec<BoundInputRef>);
impl<'a> ExprVisitor for Visitor<'a> {
fn visit_input_ref(&mut self, expr: &BoundInputRef) {
self.0.push(expr.clone());
}
}
Visitor(input_refs).visit_expr(self);
}
pub fn contains_agg_call(&self) -> bool {
struct Visitor(bool);
impl ExprVisitor for Visitor {
fn visit_agg_call(&mut self, _: &BoundAggCall) {
self.0 = true;
}
}
let mut visitor = Visitor(false);
visitor.visit_expr(self);
visitor.0
}
pub fn format_name(&self, child_schema: &Vec<ColumnDesc>) -> String {
match self {
Self::Constant(DataValue::Int64(num)) => format!("{}", num),
Self::Constant(DataValue::Int32(num)) => format!("{}", num),
Self::Constant(DataValue::Float64(num)) => format!("{:.3}", num),
Self::BinaryOp(expr) => {
let left_expr_name = expr.left_expr.format_name(child_schema);
let right_expr_name = expr.right_expr.format_name(child_schema);
format!("{}{}{}", left_expr_name, expr.op, right_expr_name)
}
Self::UnaryOp(expr) => {
let expr_name = expr.expr.format_name(child_schema);
format!("{}{}", expr.op, expr_name)
}
Self::InputRef(expr) => child_schema[expr.index].name().to_string(),
_ => "".to_string(),
}
}
}
impl std::fmt::Debug for BoundExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Constant(expr) => write!(f, "{:?} (const)", expr)?,
Self::ColumnRef(expr) => write!(f, "Column #{:?}", expr)?,
Self::BinaryOp(expr) => write!(f, "{:?}", expr)?,
Self::UnaryOp(expr) => write!(f, "{:?}", expr)?,
Self::TypeCast(expr) => write!(f, "{:?}", expr)?,
Self::AggCall(expr) => write!(f, "{:?} (agg)", expr)?,
Self::InputRef(expr) => write!(f, "InputRef #{:?}", expr)?,
Self::IsNull(expr) => write!(f, "{:?} (isnull)", expr)?,
Self::ExprWithAlias(expr) => write!(f, "{:?}", expr)?,
Self::Alias(expr) => write!(f, "{:?}", expr)?,
}
Ok(())
}
}
impl std::fmt::Display for BoundExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Constant(expr) => write!(f, "{}", expr)?,
Self::ColumnRef(expr) => write!(f, "Column #{:?}", expr)?,
Self::BinaryOp(expr) => write!(f, "{}", expr)?,
Self::UnaryOp(expr) => write!(f, "{:?}", expr)?,
Self::TypeCast(expr) => write!(f, "{}", expr)?,
Self::AggCall(expr) => write!(f, "{:?} (agg)", expr)?,
Self::InputRef(expr) => write!(f, "InputRef #{:?}", expr)?,
Self::IsNull(expr) => write!(f, "{:?} (isnull)", expr)?,
Self::ExprWithAlias(expr) => write!(f, "{}", expr)?,
Self::Alias(expr) => write!(f, "{:?}", expr)?,
}
Ok(())
}
}
impl Binder {
/// Bind an expression.
pub fn bind_expr(&mut self, expr: &Expr) -> Result<BoundExpr, BindError> {
match expr {
Expr::Value(v) => Ok(BoundExpr::Constant(v.into())),
Expr::Identifier(ident) => self.bind_column_ref(std::slice::from_ref(ident)),
Expr::CompoundIdentifier(idents) => self.bind_column_ref(idents),
Expr::BinaryOp { left, op, right } => self.bind_binary_op(left, op, right),
Expr::UnaryOp { op, expr } => self.bind_unary_op(op, expr),
Expr::Nested(expr) => self.bind_expr(expr),
Expr::Cast { expr, data_type } => self.bind_type_cast(expr, data_type.clone()),
Expr::Function(func) => self.bind_function(func),
Expr::IsNull(expr) => self.bind_isnull(expr),
Expr::IsNotNull(expr) => {
let expr = self.bind_isnull(expr)?;
Ok(BoundExpr::UnaryOp(BoundUnaryOp {
op: UnaryOperator::Not,
expr: Box::new(expr),
return_type: Some(DataTypeKind::Bool.not_null()),
}))
}
Expr::TypedString { data_type, value } => self.bind_typed_string(data_type, value),
Expr::Between {
expr,
negated,
low,
high,
} => self.bind_between(expr, negated, low, high),
_ => todo!("bind expression: {:?}", expr),
}
}
fn bind_typed_string(
&mut self,
data_type: &crate::parser::DataType,
value: &str,
) -> Result<BoundExpr, BindError> {
match data_type {
crate::parser::DataType::Date => {
let date = value.parse().map_err(|_| {
BindError::CastError(DataValue::String(value.into()), DataTypeKind::Date)
})?;
Ok(BoundExpr::Constant(DataValue::Date(date)))
}
t => todo!("support typed string: {:?}", t),
}
}
fn bind_between(
&mut self,
expr: &Expr,
negated: &bool,
low: &Expr,
high: &Expr,
) -> Result<BoundExpr, BindError> {
use BinaryOperator::{And, Gt, GtEq, Lt, LtEq, Or};
let (left_op, right_op, final_op) = match negated {
false => (GtEq, LtEq, And),
true => (Lt, Gt, Or),
};
let left_expr = self.bind_binary_op(expr, &left_op, low)?;
let right_expr = self.bind_binary_op(expr, &right_op, high)?;
Ok(BoundExpr::BinaryOp(BoundBinaryOp {
op: final_op,
left_expr: Box::new(left_expr),
right_expr: Box::new(right_expr),
return_type: Some(DataType::new(DataTypeKind::Bool, false)),
}))
}
}
impl From<&Value> for DataValue {
fn from(v: &Value) -> Self {
match v {
Value::Number(n, _) => {
if let Ok(int) = n.parse::<i32>() {
Self::Int32(int)
} else if let Ok(bigint) = n.parse::<i64>() {
Self::Int64(bigint)
} else if let Ok(float) = n.parse::<F64>() {
Self::Float64(float)
} else {
panic!("invalid digit: {}", n);
}
}
Value::SingleQuotedString(s) => Self::String(s.clone()),
Value::DoubleQuotedString(s) => Self::String(s.clone()),
Value::Boolean(b) => Self::Bool(*b),
Value::Null => Self::Null,
Value::Interval {
value,
leading_field,
..
} => {
if let Expr::Value(Value::SingleQuotedString(value)) = &**value {
match leading_field {
Some(DateTimeField::Day) => {
// TODO: don't directly call to_string here, sqlparser may already
// parsed that.
Self::Interval(Interval::from_days(value.to_string().parse().unwrap()))
}
Some(DateTimeField::Month) => Self::Interval(Interval::from_months(
value.to_string().parse().unwrap(),
)),
Some(DateTimeField::Year) => {
Self::Interval(Interval::from_years(value.to_string().parse().unwrap()))
}
_ => todo!("Support interval with leading field: {:?}", leading_field),
}
} else {
todo!("unsupported value: {}", value)
}
}
_ => todo!("parse value: {:?}", v),
}
}
}
#[cfg(test)]
mod tests {
use sqlparser::ast::{BinaryOperator, UnaryOperator};
use crate::binder::{BoundBinaryOp, BoundExpr, BoundInputRef, BoundUnaryOp};
use crate::catalog::ColumnDesc;
use crate::types::{DataType, DataTypeKind, DataValue};
// test when BoundExpr is Constant
#[test]
fn test_format_name_constant() {
let expr = BoundExpr::Constant(DataValue::Int32(1));
assert_eq!("1", expr.format_name(&vec![]));
let expr = BoundExpr::Constant(DataValue::Int64(1));
assert_eq!("1", expr.format_name(&vec![]));
let expr = BoundExpr::Constant(DataValue::Float64(32.0.into()));
assert_eq!("32.000", expr.format_name(&vec![]));
}
// test when BoundExpr is UnaryOp(form like -a)
#[test]
fn test_format_name_unary_op() {
let data_type = DataType::new(DataTypeKind::Int32, true);
let expr = BoundExpr::InputRef(BoundInputRef {
index: 0,
return_type: data_type,
});
let child_schema = vec![ColumnDesc::new(data_type, "a".to_string(), false)];
let expr = BoundExpr::UnaryOp(BoundUnaryOp {
op: UnaryOperator::Minus,
expr: Box::new(expr),
return_type: Some(data_type),
});
assert_eq!("-a", expr.format_name(&child_schema));
}
// test when BoundExpr is BinaryOp
#[test]
fn test_format_name_binary_op() {
// forms like a + 1
{
let left_data_type = DataType::new(DataTypeKind::Int32, true);
let left_expr = BoundExpr::InputRef(BoundInputRef {
index: 0,
return_type: left_data_type,
});
let right_expr = BoundExpr::Constant(DataValue::Int64(1));
let child_schema = vec![ColumnDesc::new(left_data_type, "a".to_string(), false)];
let expr = BoundExpr::BinaryOp(BoundBinaryOp {
op: BinaryOperator::Plus,
left_expr: Box::new(left_expr),
right_expr: Box::new(right_expr),
return_type: Some(DataType::new(DataTypeKind::Int32, true)),
});
assert_eq!("a+1", expr.format_name(&child_schema));
}
// forms like a + b
{
let data_type = DataType::new(DataTypeKind::Int32, true);
let left_expr = BoundExpr::InputRef(BoundInputRef {
index: 0,
return_type: data_type,
});
let right_expr = BoundExpr::InputRef(BoundInputRef {
index: 1,
return_type: data_type,
});
let child_schema = vec![
ColumnDesc::new(data_type, "a".to_string(), false),
ColumnDesc::new(data_type, "b".to_string(), false),
];
let expr = BoundExpr::BinaryOp(BoundBinaryOp {
op: BinaryOperator::Plus,
left_expr: Box::new(left_expr),
right_expr: Box::new(right_expr),
return_type: Some(data_type),
});
assert_eq!("a+b", expr.format_name(&child_schema));
}
}
}