risingwave_frontend/expr/
session_timezone.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
// Copyright 2024 RisingWave Labs
//
// 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 risingwave_common::types::DataType;
pub use risingwave_pb::expr::expr_node::Type as ExprType;

pub use crate::expr::expr_rewriter::ExprRewriter;
pub use crate::expr::function_call::FunctionCall;
use crate::expr::{Expr, ExprImpl, ExprVisitor};
use crate::session::current;

/// `SessionTimezone` will be used to resolve session
/// timezone-dependent casts, comparisons or arithmetic.
pub struct SessionTimezone {
    timezone: String,
    /// Whether or not the session timezone was used
    used: bool,
}

impl ExprRewriter for SessionTimezone {
    fn rewrite_function_call(&mut self, func_call: FunctionCall) -> ExprImpl {
        let (func_type, inputs, ret) = func_call.decompose();
        let inputs: Vec<ExprImpl> = inputs
            .into_iter()
            .map(|expr| self.rewrite_expr(expr))
            .collect();
        if let Some(expr) = self.with_timezone(func_type, &inputs, ret.clone()) {
            self.mark_used();
            expr
        } else {
            FunctionCall::new_unchecked(func_type, inputs, ret).into()
        }
    }
}

impl SessionTimezone {
    pub fn new(timezone: String) -> Self {
        Self {
            timezone,
            used: false,
        }
    }

    pub fn timezone(&self) -> String {
        self.timezone.clone()
    }

    pub fn used(&self) -> bool {
        self.used
    }

    fn mark_used(&mut self) {
        if !self.used {
            self.used = true;
            current::notice_to_user(format!(
                "Your session timezone is {}. It was used in the interpretation of timestamps and dates in your query. If this is unintended, \
                change your timezone to match that of your data's with `set timezone = [timezone]` or \
                rewrite your query with an explicit timezone conversion, e.g. with `AT TIME ZONE`.\n",
                self.timezone
            ));
        }
    }

    // Inlines conversions based on session timezone if required by the function
    fn with_timezone(
        &self,
        func_type: ExprType,
        inputs: &[ExprImpl],
        return_type: DataType,
    ) -> Option<ExprImpl> {
        match func_type {
            // `input_timestamptz::varchar`
            // => `cast_with_time_zone(input_timestamptz, zone_string)`
            // `input_varchar::timestamptz`
            // => `cast_with_time_zone(input_varchar, zone_string)`
            // `input_date::timestamptz`
            // => `input_date::timestamp AT TIME ZONE zone_string`
            // `input_timestamp::timestamptz`
            // => `input_timestamp AT TIME ZONE zone_string`
            // `input_timestamptz::date`
            // => `(input_timestamptz AT TIME ZONE zone_string)::date`
            // `input_timestamptz::time`
            // => `(input_timestamptz AT TIME ZONE zone_string)::time`
            // `input_timestamptz::timestamp`
            // => `input_timestamptz AT TIME ZONE zone_string`
            ExprType::Cast => {
                assert_eq!(inputs.len(), 1);
                let mut input = inputs[0].clone();
                let input_type = input.return_type();
                match (input_type, return_type.clone()) {
                    (DataType::Timestamptz, DataType::Varchar)
                    | (DataType::Varchar, DataType::Timestamptz) => {
                        Some(self.cast_with_timezone(input, return_type))
                    }
                    (DataType::Date, DataType::Timestamptz)
                    | (DataType::Timestamp, DataType::Timestamptz) => {
                        input = input.cast_explicit(DataType::Timestamp).unwrap();
                        Some(self.at_timezone(input))
                    }
                    (DataType::Timestamptz, DataType::Date)
                    | (DataType::Timestamptz, DataType::Time)
                    | (DataType::Timestamptz, DataType::Timestamp) => {
                        input = self.at_timezone(input);
                        input = input.cast_explicit(return_type).unwrap();
                        Some(input)
                    }
                    _ => None,
                }
            }
            // `lhs_date CMP rhs_timestamptz`
            // => `(lhs_date::timestamp AT TIME ZONE zone_string) CMP rhs_timestamptz`
            // `lhs_timestamp CMP rhs_timestamptz`
            // => `(lhs_timestamp AT TIME ZONE zone_string) CMP rhs_timestamptz`
            // `lhs_timestamptz CMP rhs_date`
            // => `lhs_timestamptz CMP (rhs_date::timestamp AT TIME ZONE zone_string)`
            // `lhs_timestamptz CMP rhs_timestamp`
            // => `lhs_timestamptz CMP (rhs_timestamp AT TIME ZONE zone_string)`
            ExprType::Equal
            | ExprType::NotEqual
            | ExprType::LessThan
            | ExprType::LessThanOrEqual
            | ExprType::GreaterThan
            | ExprType::GreaterThanOrEqual
            | ExprType::IsDistinctFrom
            | ExprType::IsNotDistinctFrom => {
                assert_eq!(inputs.len(), 2);
                let mut inputs = inputs.to_vec();
                for idx in 0..2 {
                    if matches!(inputs[(idx + 1) % 2].return_type(), DataType::Timestamptz)
                        && matches!(
                            inputs[idx % 2].return_type(),
                            DataType::Date | DataType::Timestamp
                        )
                    {
                        let mut to_cast = inputs[idx % 2].clone();
                        // Cast to `Timestamp` first, then use `AT TIME ZONE` to convert to
                        // `Timestamptz`
                        to_cast = to_cast.cast_explicit(DataType::Timestamp).unwrap();
                        inputs[idx % 2] = self.at_timezone(to_cast);
                        return Some(
                            FunctionCall::new_unchecked(func_type, inputs, return_type).into(),
                        );
                    }
                }
                None
            }
            // `add(lhs_interval, rhs_timestamptz)`
            // => `add_with_time_zone(rhs_timestamptz, lhs_interval, zone_string)`
            // `add(lhs_timestamptz, rhs_interval)`
            // => `add_with_time_zone(lhs_timestamptz, rhs_interval, zone_string)`
            // `subtract(lhs_timestamptz, rhs_interval)`
            // => `subtract_with_time_zone(lhs_timestamptz, rhs_interval, zone_string)`
            ExprType::Subtract | ExprType::Add => {
                assert_eq!(inputs.len(), 2);
                let canonical_match = matches!(inputs[0].return_type(), DataType::Timestamptz)
                    && matches!(inputs[1].return_type(), DataType::Interval);
                let inverse_match = matches!(inputs[1].return_type(), DataType::Timestamptz)
                    && matches!(inputs[0].return_type(), DataType::Interval);
                assert!(!(inverse_match && func_type == ExprType::Subtract)); // This should never have been parsed.
                if canonical_match || inverse_match {
                    let (orig_timestamptz, interval) =
                        if func_type == ExprType::Add && inverse_match {
                            (inputs[1].clone(), inputs[0].clone())
                        } else {
                            (inputs[0].clone(), inputs[1].clone())
                        };
                    let new_type = match func_type {
                        ExprType::Add => ExprType::AddWithTimeZone,
                        ExprType::Subtract => ExprType::SubtractWithTimeZone,
                        _ => unreachable!(),
                    };
                    let rewritten_expr = FunctionCall::new(
                        new_type,
                        vec![
                            orig_timestamptz,
                            interval,
                            ExprImpl::literal_varchar(self.timezone()),
                        ],
                    )
                    .unwrap()
                    .into();
                    return Some(rewritten_expr);
                }
                None
            }
            // `date_trunc(field_string, input_timestamptz)`
            // => `date_trunc(field_string, input_timestamptz, zone_string)`
            ExprType::DateTrunc | ExprType::Extract | ExprType::DatePart => {
                if !(inputs.len() == 2 && inputs[1].return_type() == DataType::Timestamptz) {
                    return None;
                }
                assert_eq!(inputs[0].return_type(), DataType::Varchar);
                if let ExprImpl::Literal(lit) = &inputs[0]
                    && matches!(func_type, ExprType::Extract | ExprType::DatePart)
                    && lit
                        .get_data()
                        .as_ref()
                        .map_or(true, |v| v.as_utf8().eq_ignore_ascii_case("epoch"))
                {
                    // No need to rewrite when field is `null` or `epoch`.
                    // This is optional but avoids false warning in common case.
                    return None;
                }
                let mut new_inputs = inputs.to_vec();
                new_inputs.push(ExprImpl::literal_varchar(self.timezone()));
                Some(FunctionCall::new(func_type, new_inputs).unwrap().into())
            }
            // `char_to_timestamptz(input_string, format_string)`
            // => `char_to_timestamptz(input_string, format_string, zone_string)`
            ExprType::CharToTimestamptz => {
                if !(inputs.len() == 2
                    && inputs[0].return_type() == DataType::Varchar
                    && inputs[1].return_type() == DataType::Varchar)
                {
                    return None;
                }
                let mut new_inputs = inputs.to_vec();
                new_inputs.push(ExprImpl::literal_varchar(self.timezone()));
                Some(FunctionCall::new(func_type, new_inputs).unwrap().into())
            }
            // `to_char(input_timestamptz, format_string)`
            // => `to_char(input_timestamptz, format_string, zone_string)`
            ExprType::ToChar => {
                if !(inputs.len() == 2
                    && inputs[0].return_type() == DataType::Timestamptz
                    && inputs[1].return_type() == DataType::Varchar)
                {
                    return None;
                }
                let mut new_inputs = inputs.to_vec();
                new_inputs.push(ExprImpl::literal_varchar(self.timezone()));
                Some(FunctionCall::new(func_type, new_inputs).unwrap().into())
            }
            _ => None,
        }
    }

    fn at_timezone(&self, input: ExprImpl) -> ExprImpl {
        FunctionCall::new(
            ExprType::AtTimeZone,
            vec![input, ExprImpl::literal_varchar(self.timezone.clone())],
        )
        .unwrap()
        .into()
    }

    fn cast_with_timezone(&self, input: ExprImpl, return_type: DataType) -> ExprImpl {
        FunctionCall::new_unchecked(
            ExprType::CastWithTimeZone,
            vec![input, ExprImpl::literal_varchar(self.timezone.clone())],
            return_type,
        )
        .into()
    }
}

#[derive(Default)]
pub struct TimestamptzExprFinder {
    has: bool,
}

impl TimestamptzExprFinder {
    pub fn has(&self) -> bool {
        self.has
    }
}

impl ExprVisitor for TimestamptzExprFinder {
    fn visit_function_call(&mut self, func_call: &FunctionCall) {
        if func_call.return_type() == DataType::Timestamptz {
            self.has = true;
            return;
        }

        for input in &func_call.inputs {
            if input.return_type() == DataType::Timestamptz {
                self.has = true;
                return;
            }
        }

        func_call
            .inputs()
            .iter()
            .for_each(|expr| self.visit_expr(expr));
    }
}