-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathsqlite_interval.rs
469 lines (411 loc) · 15.8 KB
/
sqlite_interval.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use datafusion::error::DataFusionError;
use datafusion::sql::sqlparser::ast::{
self, BinaryOperator, Expr, FunctionArg, FunctionArgExpr, FunctionArgumentList, Ident,
VisitorMut,
};
use std::fmt::Display;
use std::ops::ControlFlow;
use std::str::FromStr;
#[derive(Default)]
pub struct SQLiteIntervalVisitor {}
#[derive(Default, Debug)]
struct IntervalParts {
years: i64,
months: i64,
days: i64,
hours: i64,
minutes: i64,
seconds: i64,
nanos: u32,
}
enum SQLiteIntervalType {
Date,
Datetime,
}
impl Display for SQLiteIntervalType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SQLiteIntervalType::Date => write!(f, "date"),
SQLiteIntervalType::Datetime => write!(f, "datetime"),
}
}
}
type IntervalSetter = fn(IntervalParts, i64) -> IntervalParts;
impl IntervalParts {
fn new() -> Self {
Self::default()
}
fn intraday(&self) -> bool {
self.hours > 0 || self.minutes > 0 || self.seconds > 0 || self.nanos > 0
}
fn negate(mut self) -> Self {
self.years = -self.years;
self.months = -self.months;
self.days = -self.days;
self.hours = -self.hours;
self.minutes = -self.minutes;
self.seconds = -self.seconds;
self
}
fn with_years(mut self, years: i64) -> Self {
self.years = years;
self
}
fn with_months(mut self, months: i64) -> Self {
self.months = months;
self
}
fn with_days(mut self, days: i64) -> Self {
self.days = days;
self
}
fn with_hours(mut self, hours: i64) -> Self {
self.hours = hours;
self
}
fn with_minutes(mut self, minutes: i64) -> Self {
self.minutes = minutes;
self
}
fn with_seconds(mut self, seconds: i64) -> Self {
self.seconds = seconds;
self
}
fn with_nanos(mut self, nanos: u32) -> Self {
self.nanos = nanos;
self
}
}
impl VisitorMut for SQLiteIntervalVisitor {
type Break = ();
fn pre_visit_expr(&mut self, expr: &mut Expr) -> ControlFlow<Self::Break> {
// for each INTERVAL, find the previous (or next, if the INTERVAL is first) expression or column name that is associated with it
// e.g. `column_name + INTERVAL '1' DAY``, we should find the `column_name`
// then replace the `INTERVAL` with e.g. `datetime(column_name, '+1 day')`
// this should also apply to expressions though, like `CAST(column_name AS TEXT) + INTERVAL '1' DAY`
// in this example, it would be replaced with `datetime(CAST(column_name AS TEXT), '+1 day')`
// TODO: figure out nested BinaryOp, e.g. `column_name + INTERVAL '1' DAY + INTERVAL '1' DAY`
if let Expr::BinaryOp { op, left, right } = expr {
if *op != BinaryOperator::Plus && *op != BinaryOperator::Minus {
return ControlFlow::Continue(());
}
let (target, interval) = SQLiteIntervalVisitor::normalize_interval_expr(left, right);
if let Expr::Interval(_) = interval.as_ref() {
// parse the INTERVAL and get the bits out of it
// e.g. INTERVAL 0 YEARS 0 MONS 1 DAYS 0 HOURS 0 MINUTES 0.000000000 SECS -> IntervalParts { days: 1 }
if let Ok(interval_parts) = SQLiteIntervalVisitor::parse_interval(interval) {
// negate the interval parts if the operator is minus
let interval_parts = if *op == BinaryOperator::Minus {
interval_parts.negate()
} else {
interval_parts
};
*expr =
SQLiteIntervalVisitor::create_datetime_function(target, &interval_parts);
}
}
}
ControlFlow::Continue(())
}
}
impl SQLiteIntervalVisitor {
// normalize the sides of the operation to make sure the INTERVAL is always on the right
fn normalize_interval_expr<'a>(
left: &'a mut Box<Expr>,
right: &'a mut Box<Expr>,
) -> (&'a mut Box<Expr>, &'a mut Box<Expr>) {
if let Expr::Interval { .. } = left.as_ref() {
(right, left)
} else {
(left, right)
}
}
fn parse_interval(interval: &Expr) -> Result<IntervalParts, DataFusionError> {
if let Expr::Interval(interval_expr) = interval {
if let Expr::Value(ast::Value::SingleQuotedString(value)) = interval_expr.value.as_ref()
{
return SQLiteIntervalVisitor::parse_interval_string(value);
}
}
Err(DataFusionError::Plan(
"Invalid interval expression".to_string(),
))
}
fn parse_interval_string(value: &str) -> Result<IntervalParts, DataFusionError> {
let mut parts = IntervalParts::new();
let mut remaining = value;
let components: [(_, IntervalSetter); 5] = [
("YEARS", IntervalParts::with_years),
("MONS", IntervalParts::with_months),
("DAYS", IntervalParts::with_days),
("HOURS", IntervalParts::with_hours),
("MINS", IntervalParts::with_minutes),
];
for (unit, setter) in &components {
if let Some((value, rest)) = remaining.split_once(unit) {
let parsed_value: i64 = SQLiteIntervalVisitor::parse_value(value.trim())?;
parts = setter(parts, parsed_value);
remaining = rest;
}
}
// Parse seconds and nanoseconds separately
if let Some((secs, _)) = remaining.split_once("SECS") {
let (seconds, nanos) = SQLiteIntervalVisitor::parse_seconds_and_nanos(secs.trim())?;
parts = parts.with_seconds(seconds).with_nanos(nanos);
}
Ok(parts)
}
fn parse_seconds_and_nanos(value: &str) -> Result<(i64, u32), DataFusionError> {
let parts: Vec<&str> = value.split('.').collect();
let seconds = SQLiteIntervalVisitor::parse_value(parts[0])?;
let nanos = if parts.len() > 1 {
let nanos_str = format!("{:0<9}", parts[1]);
nanos_str[..9].parse().map_err(|_| {
DataFusionError::Plan(format!("Failed to parse nanoseconds: {}", parts[1]))
})?
} else {
0
};
Ok((seconds, nanos))
}
fn parse_value<T: FromStr>(value: &str) -> Result<T, DataFusionError> {
value
.parse()
.map_err(|_| DataFusionError::Plan(format!("Failed to parse interval value: {value}")))
}
fn create_datetime_function(target: &Expr, interval: &IntervalParts) -> Expr {
let interval_date_type = if interval.intraday() {
SQLiteIntervalType::Datetime
} else {
SQLiteIntervalType::Date
};
let function_args = vec![
Some(FunctionArg::Unnamed(FunctionArgExpr::Expr(target.clone()))),
SQLiteIntervalVisitor::create_interval_arg("years", interval.years),
SQLiteIntervalVisitor::create_interval_arg("months", interval.months),
SQLiteIntervalVisitor::create_interval_arg("days", interval.days),
SQLiteIntervalVisitor::create_interval_arg("hours", interval.hours),
SQLiteIntervalVisitor::create_interval_arg("minutes", interval.minutes),
SQLiteIntervalVisitor::create_interval_arg_with_fraction(
"seconds",
interval.seconds,
interval.nanos,
),
]
.into_iter()
.flatten() // flatten the list of arguments to exclude 0 values
.collect();
let datetime_function = Expr::Function(ast::Function {
name: ast::ObjectName(vec![Ident::new(interval_date_type.to_string())]),
args: ast::FunctionArguments::List(FunctionArgumentList {
duplicate_treatment: None,
args: function_args,
clauses: Vec::new(),
}),
filter: None,
null_treatment: None,
over: None,
within_group: Vec::new(),
parameters: ast::FunctionArguments::None,
});
Expr::Cast {
expr: Box::new(datetime_function),
data_type: ast::DataType::Text,
format: None,
kind: ast::CastKind::Cast,
}
}
fn create_interval_arg(unit: &str, value: i64) -> Option<FunctionArg> {
if value == 0 {
None
} else {
Some(FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(
ast::Value::SingleQuotedString(format!("{value:+} {unit}")),
))))
}
}
fn create_interval_arg_with_fraction(
unit: &str,
value: i64,
fraction: u32,
) -> Option<FunctionArg> {
if value == 0 && fraction == 0 {
None
} else {
let fraction_str = if fraction > 0 {
format!(".{fraction:09}")
} else {
String::new()
};
Some(FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(
ast::Value::SingleQuotedString(format!("{value:+}{fraction_str} {unit}")),
))))
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_interval_parts_parse() {
let parts = SQLiteIntervalVisitor::parse_interval_string(
"0 YEARS 0 MONS 1 DAYS 0 HOURS 0 MINS 0.000000000 SECS",
)
.expect("interval parts should be parsed");
assert_eq!(parts.years, 0);
assert_eq!(parts.months, 0);
assert_eq!(parts.days, 1);
assert_eq!(parts.hours, 0);
assert_eq!(parts.minutes, 0);
assert_eq!(parts.seconds, 0);
assert_eq!(parts.nanos, 0);
}
#[test]
fn test_interval_parts_parse_with_nanos() {
let parts = SQLiteIntervalVisitor::parse_interval_string(
"0 YEARS 0 MONS 0 DAYS 0 HOURS 0 MINS 0.000000001 SECS",
)
.expect("interval parts should be parsed");
assert_eq!(parts.years, 0);
assert_eq!(parts.months, 0);
assert_eq!(parts.days, 0);
assert_eq!(parts.hours, 0);
assert_eq!(parts.minutes, 0);
assert_eq!(parts.seconds, 0);
assert_eq!(parts.nanos, 1);
}
#[test]
fn test_interval_parts_parse_negative() {
let parts = SQLiteIntervalVisitor::parse_interval_string(
"0 YEARS 0 MONS -1 DAYS 0 HOURS 0 MINS 0.000000000 SECS",
)
.expect("interval parts should be parsed");
assert_eq!(parts.years, 0);
assert_eq!(parts.months, 0);
assert_eq!(parts.days, -1);
assert_eq!(parts.hours, 0);
assert_eq!(parts.minutes, 0);
assert_eq!(parts.seconds, 0);
assert_eq!(parts.nanos, 0);
}
#[test]
fn test_interval_parts_parse_intraday() {
let parts = SQLiteIntervalVisitor::parse_interval_string(
"0 YEARS 0 MONS 0 DAYS 1 HOURS 1 MINS 1.000000001 SECS",
)
.expect("interval parts should be parsed");
assert_eq!(parts.years, 0);
assert_eq!(parts.months, 0);
assert_eq!(parts.days, 0);
assert_eq!(parts.hours, 1);
assert_eq!(parts.minutes, 1);
assert_eq!(parts.seconds, 1);
assert_eq!(parts.nanos, 1);
assert!(parts.intraday());
}
#[test]
fn test_interval_parts_parse_interday() {
let parts = SQLiteIntervalVisitor::parse_interval_string(
"0 YEARS 0 MONS 1 DAYS 0 HOURS 0 MINS 0.000000000 SECS",
)
.expect("interval parts should be parsed");
assert_eq!(parts.years, 0);
assert_eq!(parts.months, 0);
assert_eq!(parts.days, 1);
assert_eq!(parts.hours, 0);
assert_eq!(parts.minutes, 0);
assert_eq!(parts.seconds, 0);
assert_eq!(parts.nanos, 0);
assert!(!parts.intraday());
}
#[test]
fn test_create_date_function() {
let target = Expr::Value(ast::Value::SingleQuotedString("1995-01-01".to_string()));
let interval = IntervalParts::new()
.with_years(1)
.with_months(2)
.with_days(3)
.with_hours(0)
.with_minutes(0)
.with_seconds(0)
.with_nanos(0);
let datetime_function = SQLiteIntervalVisitor::create_datetime_function(&target, &interval);
let expected = Expr::Cast {
expr: Box::new(Expr::Function(ast::Function {
name: ast::ObjectName(vec![Ident::new("date")]),
args: ast::FunctionArguments::List(FunctionArgumentList {
duplicate_treatment: None,
args: vec![
FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(
ast::Value::SingleQuotedString("1995-01-01".to_string()),
))),
FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(
ast::Value::SingleQuotedString("+1 years".to_string()),
))),
FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(
ast::Value::SingleQuotedString("+2 months".to_string()),
))),
FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(
ast::Value::SingleQuotedString("+3 days".to_string()),
))),
],
clauses: Vec::new(),
}),
filter: None,
null_treatment: None,
over: None,
within_group: Vec::new(),
parameters: ast::FunctionArguments::None,
})),
data_type: ast::DataType::Text,
format: None,
kind: ast::CastKind::Cast,
};
assert_eq!(datetime_function, expected);
}
#[test]
fn test_create_datetime_function() {
let target = Expr::Value(ast::Value::SingleQuotedString("1995-01-01".to_string()));
let interval = IntervalParts::new()
.with_years(0)
.with_months(0)
.with_days(0)
.with_hours(1)
.with_minutes(2)
.with_seconds(3)
.with_nanos(0);
let datetime_function = SQLiteIntervalVisitor::create_datetime_function(&target, &interval);
let expected = Expr::Cast {
expr: Box::new(Expr::Function(ast::Function {
name: ast::ObjectName(vec![Ident::new("datetime")]),
args: ast::FunctionArguments::List(FunctionArgumentList {
duplicate_treatment: None,
args: vec![
FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(
ast::Value::SingleQuotedString("1995-01-01".to_string()),
))),
FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(
ast::Value::SingleQuotedString("+1 hours".to_string()),
))),
FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(
ast::Value::SingleQuotedString("+2 minutes".to_string()),
))),
FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(
ast::Value::SingleQuotedString("+3 seconds".to_string()),
))),
],
clauses: Vec::new(),
}),
filter: None,
null_treatment: None,
over: None,
within_group: Vec::new(),
parameters: ast::FunctionArguments::None,
})),
data_type: ast::DataType::Text,
format: None,
kind: ast::CastKind::Cast,
};
assert_eq!(datetime_function, expected);
}
}