risingwave_sqlparser/parser_v2/
expr.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
// 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 winnow::combinator::{alt, cut_err, opt, preceded, repeat, seq, trace};
use winnow::error::ContextError;
use winnow::{PResult, Parser};

use super::{data_type, token, ParserExt, TokenStream};
use crate::ast::Expr;
use crate::keywords::Keyword;
use crate::parser::Precedence;
use crate::tokenizer::Token;

fn expr_parse<S>(input: &mut S) -> PResult<Expr>
where
    S: TokenStream,
{
    // TODO: implement this function using combinator style.
    trace("expr", |input: &mut S| {
        input.parse_v1(|parser| parser.parse_expr())
    })
    .parse_next(input)
}

fn subexpr<S>(precedence: Precedence) -> impl Parser<S, Expr, ContextError>
where
    S: TokenStream,
{
    // TODO: implement this function using combinator style.
    trace("subexpr", move |input: &mut S| {
        input.parse_v1(|parser| parser.parse_subexpr(precedence))
    })
}

pub fn expr_case<S>(input: &mut S) -> PResult<Expr>
where
    S: TokenStream,
{
    let parse = (
        opt(expr_parse),
        repeat(
            1..,
            (
                Keyword::WHEN,
                cut_err(expr_parse),
                cut_err(Keyword::THEN),
                cut_err(expr_parse),
            ),
        ),
        opt(preceded(Keyword::ELSE, cut_err(expr_parse))),
        cut_err(Keyword::END),
    )
        .map(|(operand, branches, else_result, _)| {
            let branches: Vec<_> = branches;
            let (conditions, results) = branches.into_iter().map(|(_, c, _, t)| (c, t)).unzip();
            Expr::Case {
                operand: operand.map(Box::new),
                conditions,
                results,
                else_result: else_result.map(Box::new),
            }
        });

    trace("expr_case", parse).parse_next(input)
}

/// Consume a SQL CAST function e.g. `CAST(expr AS FLOAT)`
pub fn expr_cast<S>(input: &mut S) -> PResult<Expr>
where
    S: TokenStream,
{
    let parse = cut_err(seq! {Expr::Cast {
        _: Token::LParen,
        expr: expr_parse.map(Box::new),
        _: Keyword::AS,
        data_type: data_type,
        _: Token::RParen,
    }});

    trace("expr_cast", parse).parse_next(input)
}

/// Consume a SQL TRY_CAST function e.g. `TRY_CAST(expr AS FLOAT)`
pub fn expr_try_cast<S>(input: &mut S) -> PResult<Expr>
where
    S: TokenStream,
{
    let parse = cut_err(seq! {Expr::TryCast {
        _: Token::LParen,
        expr: expr_parse.map(Box::new),
        _: Keyword::AS,
        data_type: data_type,
        _: Token::RParen,
    }});

    trace("expr_try_cast", parse).parse_next(input)
}

/// Consume a SQL EXTRACT function e.g. `EXTRACT(YEAR FROM expr)`
pub fn expr_extract<S>(input: &mut S) -> PResult<Expr>
where
    S: TokenStream,
{
    let mut date_time_field = token
        .verify_map(|token| match token.token {
            Token::Word(w) => Some(w.value.to_uppercase()),
            Token::SingleQuotedString(s) => Some(s.to_uppercase()),
            _ => None,
        })
        .expect("date/time field");

    let parse = cut_err(seq! {Expr::Extract {
        _: Token::LParen,
        field: date_time_field,
        _: Keyword::FROM,
        expr: expr_parse.map(Box::new),
        _: Token::RParen,
    }});

    trace("expr_extract", parse).parse_next(input)
}

/// Consume `SUBSTRING (EXPR [FROM 1] [FOR 3])`
pub fn expr_substring<S>(input: &mut S) -> PResult<Expr>
where
    S: TokenStream,
{
    let mut substring_from = opt(preceded(
        alt((Token::Comma.void(), Keyword::FROM.void())),
        cut_err(expr_parse).map(Box::new),
    ));
    let mut substring_for = opt(preceded(
        alt((Token::Comma.void(), Keyword::FOR.void())),
        cut_err(expr_parse).map(Box::new),
    ));
    let parse = cut_err(seq! {Expr::Substring {
        _: Token::LParen,
        expr: expr_parse.map(Box::new),
        substring_from: substring_from,
        substring_for: substring_for,
        _: Token::RParen,
    }});

    trace("expr_substring", parse).parse_next(input)
}

/// `POSITION(<expr> IN <expr>)`
pub fn expr_position<S>(input: &mut S) -> PResult<Expr>
where
    S: TokenStream,
{
    let parse = cut_err(seq! {Expr::Position {
        _: Token::LParen,
        // Logically `parse_expr`, but limited to those with precedence higher than `BETWEEN`/`IN`,
        // to avoid conflict with general IN operator, for example `position(a IN (b) IN (c))`.
        // https://github.com/postgres/postgres/blob/REL_15_2/src/backend/parser/gram.y#L16012
        substring: subexpr(Precedence::Between).map(Box::new),
        _: Keyword::IN,
        string: subexpr(Precedence::Between).map(Box::new),
        _: Token::RParen,
    }});

    trace("expr_position", parse).parse_next(input)
}

/// `OVERLAY(<expr> PLACING <expr> FROM <expr> [ FOR <expr> ])`
pub fn expr_overlay<S>(input: &mut S) -> PResult<Expr>
where
    S: TokenStream,
{
    let mut count_parse = opt(preceded(
        Keyword::FOR.void(),
        cut_err(expr_parse).map(Box::new),
    ));

    let parse = cut_err(seq! {Expr::Overlay {
        _: Token::LParen,
        expr: expr_parse.map(Box::new),
        _: Keyword::PLACING,
        new_substring: expr_parse.map(Box::new),
        _: Keyword::FROM,
        start: expr_parse.map(Box::new),
        count: count_parse,
        _: Token::RParen,
    }});

    trace("expr_overlay", parse).parse_next(input)
}