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
use std::fmt;
use std::fmt::{Display, Formatter};
use std::str::FromStr;

use nom::branch::alt;
use nom::bytes::complete::{is_not, tag, tag_no_case, take};
use nom::character::complete::{digit1, multispace0};
use nom::combinator::{map, opt};
use nom::multi::{fold_many0, many0};
use nom::sequence::{delimited, pair, preceded, tuple};
use nom::IResult;

use base::error::ParseSQLError;
use base::{CommonParser, ItemPlaceholder};

#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub enum Literal {
    Bool(bool),
    Null,
    Integer(i64),
    UnsignedInteger(u64),
    FixedPoint(Real),
    String(String),
    Blob(Vec<u8>),
    CurrentTime,
    CurrentDate,
    CurrentTimestamp,
    Placeholder(ItemPlaceholder),
}

impl Literal {
    // Integer literal value
    pub fn integer_literal(i: &str) -> IResult<&str, Literal, ParseSQLError<&str>> {
        map(pair(opt(tag("-")), digit1), |tup| {
            let mut intval = i64::from_str(tup.1).unwrap();
            if (tup.0).is_some() {
                intval *= -1;
            }
            Literal::Integer(intval)
        })(i)
    }

    fn unpack(v: &str) -> i32 {
        i32::from_str(v).unwrap()
    }

    // Floating point literal value
    pub fn float_literal(i: &str) -> IResult<&str, Literal, ParseSQLError<&str>> {
        map(tuple((opt(tag("-")), digit1, tag("."), digit1)), |tup| {
            Literal::FixedPoint(Real {
                integral: if (tup.0).is_some() {
                    -Self::unpack(tup.1)
                } else {
                    Self::unpack(tup.1)
                },
                fractional: Self::unpack(tup.3),
            })
        })(i)
    }

    /// String literal value
    fn raw_string_quoted(
        input: &str,
        is_single_quote: bool,
    ) -> IResult<&str, String, ParseSQLError<&str>> {
        // Adjusted to work with &str
        let quote_char = if is_single_quote { '\'' } else { '"' };
        let quote_str = if is_single_quote { "\'" } else { "\"" };
        let double_quote_str = if is_single_quote { "\'\'" } else { "\"\"" };
        let backslash_quote = if is_single_quote { "\\\'" } else { "\\\"" };

        delimited(
            tag(quote_str),
            fold_many0(
                alt((
                    is_not(backslash_quote),
                    map(tag(double_quote_str), |_| {
                        if is_single_quote {
                            "\'"
                        } else {
                            "\""
                        }
                    }),
                    map(tag("\\\\"), |_| "\\"),
                    map(tag("\\b"), |_| "\x7F"), // 注意:\x7f 是 DEL,\x08 是退格
                    map(tag("\\r"), |_| "\r"),
                    map(tag("\\n"), |_| "\n"),
                    map(tag("\\t"), |_| "\t"),
                    map(tag("\\0"), |_| "\0"),
                    map(tag("\\Z"), |_| "\x1A"),
                    preceded(tag("\\"), take(1usize)),
                )),
                String::new,
                |mut acc: String, bytes: &str| {
                    acc.push_str(bytes);
                    acc
                },
            ),
            tag(quote_str),
        )(input)
    }

    fn raw_string_single_quoted(i: &str) -> IResult<&str, String, ParseSQLError<&str>> {
        Self::raw_string_quoted(i, true)
    }

    fn raw_string_double_quoted(i: &str) -> IResult<&str, String, ParseSQLError<&str>> {
        Self::raw_string_quoted(i, false)
    }

    pub fn string_literal(i: &str) -> IResult<&str, Literal, ParseSQLError<&str>> {
        map(
            alt((
                Self::raw_string_single_quoted,
                Self::raw_string_double_quoted,
            )),
            Literal::String,
        )(i)
    }

    // Any literal value.
    pub fn parse(i: &str) -> IResult<&str, Literal, ParseSQLError<&str>> {
        alt((
            Self::float_literal,
            Self::integer_literal,
            Self::string_literal,
            map(tag_no_case("NULL"), |_| Literal::Null),
            map(tag_no_case("CURRENT_TIMESTAMP"), |_| {
                Literal::CurrentTimestamp
            }),
            map(tag_no_case("CURRENT_DATE"), |_| Literal::CurrentDate),
            map(tag_no_case("CURRENT_TIME"), |_| Literal::CurrentTime),
            map(tag("?"), |_| {
                Literal::Placeholder(ItemPlaceholder::QuestionMark)
            }),
            map(preceded(tag(":"), digit1), |num| {
                let value = i32::from_str(num).unwrap();
                Literal::Placeholder(ItemPlaceholder::ColonNumber(value))
            }),
            map(preceded(tag("$"), digit1), |num| {
                let value = i32::from_str(num).unwrap();
                Literal::Placeholder(ItemPlaceholder::DollarNumber(value))
            }),
        ))(i)
    }

    // Parse a list of values (e.g., for INSERT syntax).
    pub fn value_list(i: &str) -> IResult<&str, Vec<Literal>, ParseSQLError<&str>> {
        many0(delimited(
            multispace0,
            Literal::parse,
            opt(CommonParser::ws_sep_comma),
        ))(i)
    }
}

impl From<i64> for Literal {
    fn from(i: i64) -> Self {
        Literal::Integer(i)
    }
}

impl From<u64> for Literal {
    fn from(i: u64) -> Self {
        Literal::UnsignedInteger(i)
    }
}

impl From<i32> for Literal {
    fn from(i: i32) -> Self {
        Literal::Integer(i.into())
    }
}

impl From<u32> for Literal {
    fn from(i: u32) -> Self {
        Literal::UnsignedInteger(i.into())
    }
}

impl From<String> for Literal {
    fn from(s: String) -> Self {
        Literal::String(s)
    }
}

impl<'a> From<&'a str> for Literal {
    fn from(s: &'a str) -> Self {
        Literal::String(String::from(s))
    }
}

impl Display for Literal {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match *self {
            Literal::Null => write!(f, "NULL"),
            Literal::Bool(ref value) => {
                if *value {
                    write!(f, "TRUE")
                } else {
                    write!(f, "FALSE")
                }
            }
            Literal::Integer(ref i) => write!(f, "{}", i),
            Literal::UnsignedInteger(ref i) => write!(f, "{}", i),
            Literal::FixedPoint(ref fp) => write!(f, "{}.{}", fp.integral, fp.fractional),
            Literal::String(ref s) => write!(f, "'{}'", s.replace('\'', "''")),
            Literal::Blob(ref bv) => {
                let val = bv
                    .iter()
                    .map(|v| format!("{:x}", v))
                    .collect::<Vec<String>>()
                    .join(" ")
                    .to_string();
                write!(f, "{}", val)
            }
            Literal::CurrentTime => write!(f, "CURRENT_TIME"),
            Literal::CurrentDate => write!(f, "CURRENT_DATE"),
            Literal::CurrentTimestamp => write!(f, "CURRENT_TIMESTAMP"),
            Literal::Placeholder(ref item) => write!(f, "{}", item),
        }
    }
}

#[derive(Debug, Clone, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct LiteralExpression {
    pub value: Literal,
    pub alias: Option<String>,
}

impl LiteralExpression {
    pub fn parse(i: &str) -> IResult<&str, LiteralExpression, ParseSQLError<&str>> {
        map(
            pair(
                CommonParser::opt_delimited(tag("("), Literal::parse, tag(")")),
                opt(CommonParser::as_alias),
            ),
            |p| LiteralExpression {
                value: p.0,
                alias: (p.1).map(|a| a.to_string()),
            },
        )(i)
    }
}

impl From<Literal> for LiteralExpression {
    fn from(l: Literal) -> Self {
        LiteralExpression {
            value: l,
            alias: None,
        }
    }
}

impl fmt::Display for LiteralExpression {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.alias {
            Some(ref alias) => write!(f, "{} AS {}", self.value, alias),
            None => write!(f, "{}", self.value),
        }
    }
}

#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct Real {
    pub integral: i32,
    pub fractional: i32,
}

impl Display for Real {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}", self.integral, self.fractional)
    }
}

#[cfg(test)]
mod tests {
    use base::Literal;

    #[test]
    #[allow(clippy::redundant_slicing)]
    fn literal_string_single_backslash_escape() {
        let all_escaped = r#"\0\'\"\b\n\r\t\Z\\\%\_"#;
        for quote in ["'", "\""].iter() {
            let quoted = &[quote, &all_escaped[..], quote].concat();
            let res = Literal::string_literal(quoted);
            let expected = Literal::String("\0\'\"\x7F\n\r\t\x1a\\%_".to_string());

            assert!(res.is_ok());
            assert_eq!(res.unwrap().1, expected);
        }
    }

    #[test]
    fn literal_string_single_quote() {
        let res = Literal::string_literal("'a''b'");
        let expected = Literal::String("a'b".to_string());

        assert!(res.is_ok());
        assert_eq!(res.unwrap().1, expected);
    }

    #[test]
    fn literal_string_double_quote() {
        let res = Literal::string_literal(r#""a""b""#);
        let expected = Literal::String(r#"a"b"#.to_string());

        assert!(res.is_ok());
        assert_eq!(res.unwrap().1, expected);
    }
}