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
// Copyright 2018 sqlparser-rs contributors. All rights reserved.
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// This file is derived from the sqlparser-rs project, available at
// https://github.com/andygrove/sqlparser-rs. It was incorporated
// directly into Materialize on December 21, 2019.
//
// 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 in the LICENSE file at the
// root of this repository, or online 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::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

use crate::ast::display::{self, AstDisplay, AstFormatter};
use crate::ast::Ident;

#[derive(Debug)]
pub struct ValueError(pub(crate) String);

impl std::error::Error for ValueError {}

impl fmt::Display for ValueError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Primitive SQL values.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Value {
    /// Numeric value.
    Number(String),
    /// String value.
    String(String),
    /// Hex string value.
    HexString(String),
    /// Boolean value.
    Boolean(bool),
    /// INTERVAL literals, roughly in the following format:
    ///
    /// ```text
    /// INTERVAL '<value>' <leading_field> [ TO <last_field>
    ///     [ (<fractional_seconds_precision>) ] ]
    /// ```
    /// e.g. `INTERVAL '123:45.678' MINUTE TO SECOND(2)`.
    Interval(IntervalValue),
    /// `NULL` value.
    Null,
}

impl AstDisplay for Value {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        if f.redacted() {
            // When adding branches to this match statement, think about whether it is OK for us to collect
            // the value as part of our telemetry. Check the data management policy to be sure!
            match self {
                Value::Number(_) | Value::String(_) | Value::HexString(_) => {
                    f.write_str("'<REDACTED>'");
                    return;
                }
                Value::Interval(_) => {
                    f.write_str("INTERVAL '<REDACTED>'");
                    return;
                }
                Value::Boolean(_) | Value::Null => {
                    // These are fine to log, so just fall through.
                }
            }
        }
        match self {
            Value::Number(v) => f.write_str(v),
            Value::String(v) => {
                f.write_str("'");
                f.write_node(&display::escape_single_quote_string(v));
                f.write_str("'");
            }
            Value::HexString(v) => {
                f.write_str("X'");
                f.write_str(v);
                f.write_str("'");
            }
            Value::Boolean(v) => f.write_str(v),
            Value::Interval(interval_value) => {
                f.write_str("INTERVAL '");
                f.write_node(interval_value);
            }
            Value::Null => f.write_str("NULL"),
        }
    }
}
impl_display!(Value);

impl AstDisplay for IntervalValue {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        if f.redacted() {
            f.write_str("<REDACTED>'");
        } else {
            let IntervalValue {
                value,
                precision_high,
                precision_low,
                fsec_max_precision,
            } = self;
            f.write_node(&display::escape_single_quote_string(value));
            f.write_str("'");
            match (precision_high, precision_low, fsec_max_precision) {
                (DateTimeField::Year, DateTimeField::Second, None) => {}
                (DateTimeField::Year, DateTimeField::Second, Some(ns)) => {
                    f.write_str(" SECOND(");
                    f.write_str(ns);
                    f.write_str(")");
                }
                (DateTimeField::Year, low, None) => {
                    f.write_str(" ");
                    f.write_str(low);
                }
                (high, low, None) => {
                    f.write_str(" ");
                    f.write_str(high);
                    f.write_str(" TO ");
                    f.write_str(low);
                }
                (high, low, Some(ns)) => {
                    f.write_str(" ");
                    f.write_str(high);
                    f.write_str(" TO ");
                    f.write_str(low);
                    f.write_str("(");
                    f.write_str(ns);
                    f.write_str(")");
                }
            }
        }
    }
}

impl From<Ident> for Value {
    fn from(ident: Ident) -> Self {
        Self::String(ident.0)
    }
}

#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DateTimeField {
    Millennium,
    Century,
    Decade,
    Year,
    Month,
    Day,
    Hour,
    Minute,
    Second,
    Milliseconds,
    Microseconds,
}

impl fmt::Display for DateTimeField {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match self {
            DateTimeField::Millennium => "MILLENNIUM",
            DateTimeField::Century => "CENTURY",
            DateTimeField::Decade => "DECADE",
            DateTimeField::Year => "YEAR",
            DateTimeField::Month => "MONTH",
            DateTimeField::Day => "DAY",
            DateTimeField::Hour => "HOUR",
            DateTimeField::Minute => "MINUTE",
            DateTimeField::Second => "SECOND",
            DateTimeField::Milliseconds => "MILLISECONDS",
            DateTimeField::Microseconds => "MICROSECONDS",
        })
    }
}

impl FromStr for DateTimeField {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_uppercase().as_ref() {
            "MILLENNIUM" | "MILLENNIA" | "MIL" | "MILS" => Ok(Self::Millennium),
            "CENTURY" | "CENTURIES" | "CENT" | "C" => Ok(Self::Century),
            "DECADE" | "DECADES" | "DEC" | "DECS" => Ok(Self::Decade),
            "YEAR" | "YEARS" | "YR" | "YRS" | "Y" => Ok(Self::Year),
            "MONTH" | "MONTHS" | "MON" | "MONS" => Ok(Self::Month),
            "DAY" | "DAYS" | "D" => Ok(Self::Day),
            "HOUR" | "HOURS" | "HR" | "HRS" | "H" => Ok(Self::Hour),
            "MINUTE" | "MINUTES" | "MIN" | "MINS" | "M" => Ok(Self::Minute),
            "SECOND" | "SECONDS" | "SEC" | "SECS" | "S" => Ok(Self::Second),
            "MILLISECOND" | "MILLISECONDS" | "MILLISECON" | "MILLISECONS" | "MSECOND"
            | "MSECONDS" | "MSEC" | "MSECS" | "MS" => Ok(Self::Milliseconds),
            "MICROSECOND" | "MICROSECONDS" | "MICROSECON" | "MICROSECONS" | "USECOND"
            | "USECONDS" | "USEC" | "USECS" | "US" => Ok(Self::Microseconds),
            _ => Err(format!("invalid DateTimeField: {}", s)),
        }
    }
}

/// An intermediate value for Intervals, which tracks all data from
/// the user, as well as the computed ParsedDateTime.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct IntervalValue {
    /// The raw `[value]` that was present in `INTERVAL '[value]'`
    pub value: String,
    /// The most significant DateTimeField to propagate to Interval in
    /// compute_interval.
    pub precision_high: DateTimeField,
    /// The least significant DateTimeField to propagate to Interval in
    /// compute_interval.
    /// precision_low is also used to provide a TimeUnit if the final
    /// part of `value` is ambiguous, e.g. INTERVAL '1-2 3' DAY uses
    /// 'day' as the TimeUnit for 3.
    pub precision_low: DateTimeField,
    /// Maximum nanosecond precision can be specified in SQL source as
    /// `INTERVAL '__' SECOND(_)`.
    pub fsec_max_precision: Option<u64>,
}

impl Default for IntervalValue {
    fn default() -> Self {
        Self {
            value: String::default(),
            precision_high: DateTimeField::Year,
            precision_low: DateTimeField::Second,
            fsec_max_precision: None,
        }
    }
}