sql/statements/transform/
expand_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
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::HashMap;
use std::ops::ControlFlow;
use std::time::Duration as StdDuration;

use itertools::Itertools;
use lazy_static::lazy_static;
use regex::Regex;
use sqlparser::ast::{DataType, Expr, Interval, Value};

use crate::statements::transform::TransformRule;

lazy_static! {
    /// Matches either one or more digits `(\d+)` or one or more ASCII characters `[a-zA-Z]` or plus/minus signs
    static ref INTERVAL_ABBREVIATION_PATTERN: Regex = Regex::new(r"([+-]?\d+|[a-zA-Z]+|\+|-)").unwrap();

    /// Checks if the provided string starts as ISO_8601 format string (case/sign independent)
    static ref IS_VALID_ISO_8601_PREFIX_PATTERN: Regex = Regex::new(r"^[-]?[Pp]").unwrap();

    static ref INTERVAL_ABBREVIATION_MAPPING: HashMap<&'static str, &'static str> = HashMap::from([
        ("y","years"),
        ("mon","months"),
        ("w","weeks"),
        ("d","days"),
        ("h","hours"),
        ("m","minutes"),
        ("s","seconds"),
        ("millis","milliseconds"),
        ("ms","milliseconds"),
        ("us","microseconds"),
        ("ns","nanoseconds"),
    ]);
}

/// 'INTERVAL' abbreviation transformer
/// - `y` for `years`
/// - `mon` for `months`
/// - `w` for `weeks`
/// - `d` for `days`
/// - `h` for `hours`
/// - `m` for `minutes`
/// - `s` for `seconds`
/// - `millis` for `milliseconds`
/// - `ms` for `milliseconds`
/// - `us` for `microseconds`
/// - `ns` for `nanoseconds`
///
/// Required for scenarios that use the shortened version of `INTERVAL`,
///   f.e `SELECT INTERVAL '1h'` or `SELECT INTERVAL '3w2d'`
pub(crate) struct ExpandIntervalTransformRule;

impl TransformRule for ExpandIntervalTransformRule {
    /// Applies transform rule for `Interval` type by extending the shortened version (e.g. '1h', '2d') or
    /// converting ISO 8601 format strings (e.g., "P1Y2M3D")
    /// In case when `Interval` has `BinaryOp` value (e.g. query like `SELECT INTERVAL '2h' - INTERVAL '1h'`)
    /// it's AST has `left` part of type `Value::SingleQuotedString` which needs to be handled specifically.
    /// To handle the `right` part which is `Interval` no extra steps are needed.
    fn visit_expr(&self, expr: &mut Expr) -> ControlFlow<()> {
        match expr {
            Expr::Interval(interval) => match &*interval.value {
                Expr::Value(Value::SingleQuotedString(value))
                | Expr::Value(Value::DoubleQuotedString(value)) => {
                    if let Some(normalized_name) = normalize_interval_name(value) {
                        *expr = update_existing_interval_with_value(
                            interval,
                            single_quoted_string_expr(normalized_name),
                        );
                    }
                }
                Expr::BinaryOp { left, op, right } => match &**left {
                    Expr::Value(Value::SingleQuotedString(value))
                    | Expr::Value(Value::DoubleQuotedString(value)) => {
                        if let Some(normalized_name) = normalize_interval_name(value) {
                            let new_expr_value = Box::new(Expr::BinaryOp {
                                left: single_quoted_string_expr(normalized_name),
                                op: op.clone(),
                                right: right.clone(),
                            });
                            *expr = update_existing_interval_with_value(interval, new_expr_value);
                        }
                    }
                    _ => {}
                },
                _ => {}
            },
            Expr::Cast {
                expr: cast_exp,
                data_type,
                ..
            } => {
                if DataType::Interval == *data_type {
                    match &**cast_exp {
                        Expr::Value(Value::SingleQuotedString(value))
                        | Expr::Value(Value::DoubleQuotedString(value)) => {
                            let interval_name =
                                normalize_interval_name(value).unwrap_or_else(|| value.to_string());
                            *expr = create_interval(single_quoted_string_expr(interval_name));
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
        ControlFlow::<()>::Continue(())
    }
}

fn single_quoted_string_expr(string: String) -> Box<Expr> {
    Box::new(Expr::Value(Value::SingleQuotedString(string)))
}

fn create_interval(value: Box<Expr>) -> Expr {
    Expr::Interval(Interval {
        value,
        leading_field: None,
        leading_precision: None,
        last_field: None,
        fractional_seconds_precision: None,
    })
}

fn update_existing_interval_with_value(interval: &Interval, value: Box<Expr>) -> Expr {
    Expr::Interval(Interval {
        value,
        leading_field: interval.leading_field.clone(),
        leading_precision: interval.leading_precision,
        last_field: interval.last_field.clone(),
        fractional_seconds_precision: interval.fractional_seconds_precision,
    })
}

/// Normalizes an interval expression string into the sql-compatible format.
/// This function handles 2 types of input:
/// 1. Abbreviated interval strings (e.g., "1y2mo3d")
///    Returns an interval's full name (e.g., "years", "hours", "minutes") according to the `INTERVAL_ABBREVIATION_MAPPING`
///    If the `interval_str` contains whitespaces, the interval name is considered to be in a full form.
/// 2. ISO 8601 format strings (e.g., "P1Y2M3D"), case/sign independent
///    Returns a number of milliseconds corresponding to ISO 8601 (e.g., "36525000 milliseconds")
///
/// Note: Hybrid format "1y 2 days 3h" is not supported.
fn normalize_interval_name(interval_str: &str) -> Option<String> {
    if interval_str.contains(char::is_whitespace) {
        return None;
    }

    if IS_VALID_ISO_8601_PREFIX_PATTERN.is_match(interval_str) {
        return parse_iso8601_interval(interval_str);
    }

    expand_interval_abbreviation(interval_str)
}

fn parse_iso8601_interval(signed_iso: &str) -> Option<String> {
    let (is_negative, unsigned_iso) = if let Some(stripped) = signed_iso.strip_prefix('-') {
        (true, stripped)
    } else {
        (false, signed_iso)
    };

    match iso8601::duration(&unsigned_iso.to_uppercase()) {
        Ok(duration) => {
            let millis = StdDuration::from(duration).as_millis();
            let sign = if is_negative { "-" } else { "" };
            Some(format!("{}{} milliseconds", sign, millis))
        }
        Err(_) => None,
    }
}

fn expand_interval_abbreviation(interval_str: &str) -> Option<String> {
    Some(
        INTERVAL_ABBREVIATION_PATTERN
            .find_iter(interval_str)
            .map(|mat| {
                let mat_str = mat.as_str();
                *INTERVAL_ABBREVIATION_MAPPING
                    .get(mat_str)
                    .unwrap_or(&mat_str)
            })
            .join(" "),
    )
}

#[cfg(test)]
mod tests {
    use std::ops::ControlFlow;

    use sqlparser::ast::{BinaryOperator, DataType, Expr, Interval, Value};

    use crate::statements::transform::expand_interval::{
        create_interval, normalize_interval_name, single_quoted_string_expr,
        ExpandIntervalTransformRule,
    };
    use crate::statements::transform::TransformRule;

    #[test]
    fn test_transform_interval_basic_conversions() {
        let test_cases = vec![
            ("1y", "1 years"),
            ("4mon", "4 months"),
            ("-3w", "-3 weeks"),
            ("55h", "55 hours"),
            ("3d", "3 days"),
            ("5s", "5 seconds"),
            ("2m", "2 minutes"),
            ("100millis", "100 milliseconds"),
            ("200ms", "200 milliseconds"),
            ("350us", "350 microseconds"),
            ("400ns", "400 nanoseconds"),
        ];
        for (input, expected) in test_cases {
            let result = normalize_interval_name(input).unwrap();
            assert_eq!(result, expected);
        }

        let test_cases = vec!["1 year 2 months 3 days 4 hours", "-2 months"];
        for input in test_cases {
            assert_eq!(normalize_interval_name(input), None);
        }
    }

    #[test]
    fn test_transform_interval_compound_conversions() {
        let test_cases = vec![
            ("2y4mon6w", "2 years 4 months 6 weeks"),
            ("5d3h1m", "5 days 3 hours 1 minutes"),
            (
                "10s312ms789ns",
                "10 seconds 312 milliseconds 789 nanoseconds",
            ),
            (
                "23millis987us754ns",
                "23 milliseconds 987 microseconds 754 nanoseconds",
            ),
            ("-1d-5h", "-1 days -5 hours"),
            ("-2y-4mon-6w", "-2 years -4 months -6 weeks"),
            ("-5d-3h-1m", "-5 days -3 hours -1 minutes"),
            (
                "-10s-312ms-789ns",
                "-10 seconds -312 milliseconds -789 nanoseconds",
            ),
            (
                "-23millis-987us-754ns",
                "-23 milliseconds -987 microseconds -754 nanoseconds",
            ),
        ];
        for (input, expected) in test_cases {
            let result = normalize_interval_name(input).unwrap();
            assert_eq!(result, expected);
        }
    }

    #[test]
    fn test_iso8601_format() {
        assert_eq!(
            normalize_interval_name("P1Y2M3DT4H5M6S"),
            Some("36993906000 milliseconds".to_string())
        );
        assert_eq!(
            normalize_interval_name("p3y3m700dt133h17m36.789s"),
            Some("163343856789 milliseconds".to_string())
        );
        assert_eq!(
            normalize_interval_name("-P1Y2M3DT4H5M6S"),
            Some("-36993906000 milliseconds".to_string())
        );
        assert_eq!(normalize_interval_name("P1_INVALID_ISO8601"), None);
    }

    #[test]
    fn test_visit_expr_when_interval_is_single_quoted_string_abbr_expr() {
        let interval_transformation_rule = ExpandIntervalTransformRule {};

        let mut string_expr = create_interval(single_quoted_string_expr("5y".to_string()));

        let control_flow = interval_transformation_rule.visit_expr(&mut string_expr);

        assert_eq!(control_flow, ControlFlow::Continue(()));
        assert_eq!(
            string_expr,
            Expr::Interval(Interval {
                value: Box::new(Expr::Value(Value::SingleQuotedString(
                    "5 years".to_string()
                ))),
                leading_field: None,
                leading_precision: None,
                last_field: None,
                fractional_seconds_precision: None,
            })
        );
    }

    #[test]
    fn test_visit_expr_when_interval_is_single_quoted_string_iso8601_expr() {
        let interval_transformation_rule = ExpandIntervalTransformRule {};

        let mut string_expr =
            create_interval(single_quoted_string_expr("P1Y2M3DT4H5M6S".to_string()));

        let control_flow = interval_transformation_rule.visit_expr(&mut string_expr);

        assert_eq!(control_flow, ControlFlow::Continue(()));
        assert_eq!(
            string_expr,
            Expr::Interval(Interval {
                value: Box::new(Expr::Value(Value::SingleQuotedString(
                    "36993906000 milliseconds".to_string()
                ))),
                leading_field: None,
                leading_precision: None,
                last_field: None,
                fractional_seconds_precision: None,
            })
        );
    }

    #[test]
    fn test_visit_expr_when_interval_is_binary_op() {
        let interval_transformation_rule = ExpandIntervalTransformRule {};

        let binary_op = Box::new(Expr::BinaryOp {
            left: single_quoted_string_expr("2d".to_string()),
            op: BinaryOperator::Minus,
            right: Box::new(create_interval(single_quoted_string_expr("1d".to_string()))),
        });
        let mut binary_op_expr = create_interval(binary_op);
        let control_flow = interval_transformation_rule.visit_expr(&mut binary_op_expr);

        assert_eq!(control_flow, ControlFlow::Continue(()));
        assert_eq!(
            binary_op_expr,
            Expr::Interval(Interval {
                value: Box::new(Expr::BinaryOp {
                    left: single_quoted_string_expr("2 days".to_string()),
                    op: BinaryOperator::Minus,
                    right: Box::new(Expr::Interval(Interval {
                        value: single_quoted_string_expr("1d".to_string()),
                        leading_field: None,
                        leading_precision: None,
                        last_field: None,
                        fractional_seconds_precision: None,
                    })),
                }),
                leading_field: None,
                leading_precision: None,
                last_field: None,
                fractional_seconds_precision: None,
            })
        );
    }

    #[test]
    fn test_visit_expr_when_cast_expr() {
        let interval_transformation_rule = ExpandIntervalTransformRule {};

        let mut cast_to_interval_expr = Expr::Cast {
            expr: single_quoted_string_expr("3y2mon".to_string()),
            data_type: DataType::Interval,
            format: None,
        };

        let control_flow = interval_transformation_rule.visit_expr(&mut cast_to_interval_expr);

        assert_eq!(control_flow, ControlFlow::Continue(()));
        assert_eq!(
            cast_to_interval_expr,
            Expr::Interval(Interval {
                value: Box::new(Expr::Value(Value::SingleQuotedString(
                    "3 years 2 months".to_string()
                ))),
                leading_field: None,
                leading_precision: None,
                last_field: None,
                fractional_seconds_precision: None,
            })
        );

        let mut cast_to_i64_expr = Expr::Cast {
            expr: single_quoted_string_expr("5".to_string()),
            data_type: DataType::Int64,
            format: None,
        };
        let control_flow = interval_transformation_rule.visit_expr(&mut cast_to_i64_expr);
        assert_eq!(control_flow, ControlFlow::Continue(()));
        assert_eq!(
            cast_to_i64_expr,
            Expr::Cast {
                expr: single_quoted_string_expr("5".to_string()),
                data_type: DataType::Int64,
                format: None,
            }
        );
    }
}