orql 0.1.0

A toy SQL parser for a subset of the Oracle dialect.
Documentation
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
//! Parsing code related to processing analytical function calls.

use super::{MetaTracker, ParserInner, Result};
use crate::{
    ast::{
        Node, OrderBy, PartitionBy, PartitionByExprs, WindowFrame, WindowFrameBoundDirection,
        WindowFrameBoundType, WindowFrameBounds, WindowFrameExclude, WindowFrameExcludeSubject,
        WindowFrameUnit, WindowSpec, WindowSpecDetails,
    },
    parser::{Error, parse_comma_separated, parse_parens},
    scanner::{Keyword, Reserved, Token, TokenType},
};

/// Defines different [WindowSpec] parsing modes.
#[derive(Copy, Clone)]
pub(super) enum WindowSpecMode {
    /// Parsing a window spec as part of a query defintion,
    /// i.e. within a `WINDOW <window_name> AS (<window_spec>)` clause
    ///
    /// Syntax: <https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/SELECT.html#GUID-CFA006CA-6FF1-4972-821E-6996142A51C6__GUID-D600493B-4CD7-423A-A851-E12BC37E2904>
    Query,

    /// Parsing a window spec as part of an analytical function call,
    /// e.g. within a `count(*) OVER (<window_spec>)`
    ///
    /// Syntax: <https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Analytic-Functions.html>
    Function,

    /// Parsing a window spec as part of an analytical function call, without
    /// support for an `order_by_clause` (and subsequently no `windowing_clause`.)
    ///
    /// Syntax: <https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Analytic-Functions.html>
    FunctionWithoutOrderBy,

    /// Parsing a window spec as part of an analytical function call, without
    /// support for a `windowing_clause`, ie. a [WindowFrame]
    ///
    /// Syntax: <https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Analytic-Functions.html>
    FunctionWithoutWindowFrame,
}

impl<'s, M> ParserInner<'s, M>
where
    M: MetaTracker<'s>,
{
    /// Parses a window specificiation, e.g. `(PARTITION BY ...)`
    pub(super) fn parse_window_spec(
        &mut self,
        mode: WindowSpecMode,
    ) -> Result<Node<WindowSpec<'s, M::NodeId>, M::NodeId>> {
        /// Unlike the "partition by" for join, this does not allow parentheses
        fn parse_partition_by<'s, M: MetaTracker<'s>>(
            parser: &mut ParserInner<'s, M>,
        ) -> Result<Option<PartitionBy<'s, M::NodeId>>> {
            let partition_token = if let Some(Token {
                ttype: TokenType::Identifier(_, Some(Reserved::PARTITION)),
                loc,
            }) = parser.peek_token()?
            {
                let loc = *loc;
                parser.consume_token()?;
                Node((), parser.meta_tracker.on_node_start(loc))
            } else {
                return Ok(None);
            };
            let by_token = expect_token!(|t = parser.next_token()| "the BY keyword" match {
                TokenType::Keyword(Keyword::BY) => Node((), parser.meta_tracker.on_node_start(t.loc)),
            });
            // ~ no parantheses
            let expressions = PartitionByExprs::Exprs(parse_comma_separated(parser, |parser| {
                parser.parse_expr()
            })?);
            Ok(Some(PartitionBy {
                partition_token,
                by_token,
                expressions,
            }))
        }

        fn allow_order_by(mode: WindowSpecMode) -> bool {
            match mode {
                WindowSpecMode::Query => true,
                WindowSpecMode::Function => true,
                WindowSpecMode::FunctionWithoutOrderBy => false,
                WindowSpecMode::FunctionWithoutWindowFrame => true,
            }
        }

        fn allow_frame<ID>(mode: WindowSpecMode, order_by: Option<&OrderBy<'_, ID>>) -> bool {
            match mode {
                WindowSpecMode::Query => true,
                WindowSpecMode::Function => order_by.is_some(),
                WindowSpecMode::FunctionWithoutOrderBy => false,
                WindowSpecMode::FunctionWithoutWindowFrame => false,
            }
        }

        parse_parens(self, |parser, node_id| {
            let window_spec = if let Some(t) = parser.peek_token()? {
                match t.ttype {
                    TokenType::RightParen => {
                        // ~ we're misusing the closing paren's location for
                        // an artificial node to track potential comments
                        // within the empty paren pair
                        WindowSpec::Empty(Node((), {
                            let loc = t.loc;
                            parser.meta_tracker.on_node_start(loc)
                        }))
                    }
                    TokenType::Keyword(Keyword::ORDER) if allow_order_by(mode) => {
                        let order_by = parser.parse_order_by()?;
                        let frame =
                            parser.parse_window_frame_(allow_frame(mode, order_by.as_ref()))?;
                        WindowSpec::Details(WindowSpecDetails {
                            window_name: None,
                            partition_by: None,
                            order_by,
                            frame,
                        })
                    }
                    TokenType::Identifier(_, Some(Reserved::PARTITION)) => {
                        // ~ no need to see if "partition" could be treated as
                        // a window name; oracle won't allow it anyway
                        let partition_by = parse_partition_by(parser)?;
                        let (order_by, frame) = if allow_order_by(mode) {
                            let order_by = parser.parse_order_by()?;
                            let frame =
                                parser.parse_window_frame_(allow_frame(mode, order_by.as_ref()))?;
                            (order_by, frame)
                        } else {
                            (None, None)
                        };
                        WindowSpec::Details(WindowSpecDetails {
                            window_name: None,
                            partition_by,
                            order_by,
                            frame,
                        })
                    }
                    TokenType::Identifier(_, _) => {
                        let window_name = {
                            let_next_token!(
                                parser,
                                Token {
                                    ttype: TokenType::Identifier(ident, _),
                                    loc
                                }
                            );
                            Some(Node(ident, parser.meta_tracker.on_node_start(loc)))
                        };
                        let (order_by, frame) = if allow_order_by(mode) {
                            let order_by = parser.parse_order_by()?;
                            let frame =
                                parser.parse_window_frame_(allow_frame(mode, order_by.as_ref()))?;
                            (order_by, frame)
                        } else {
                            (None, None)
                        };
                        WindowSpec::Details(WindowSpecDetails {
                            window_name,
                            partition_by: None,
                            order_by,
                            frame,
                        })
                    }
                    _ => {
                        return Err(Error::unexpected_token(
                            t,
                            "a window name, a PARTITION BY, an ORDER BY clause, or a closing parethesis",
                        ));
                    }
                }
            } else {
                // ~ at least the closing parens should have appeared
                return unexpected_eof_err!(
                    parser,
                    "a window name, a PARTITION BY, an ORDER BY clause, or a closing parethesis"
                );
            };
            Ok(Node(window_spec, node_id))
        })
    }

    fn parse_window_frame_(
        &mut self,
        // ~ `true` to attempt parsing the frame, `false` not to try at all
        allow_frame: bool,
    ) -> Result<Option<WindowFrame<'s, M::NodeId>>> {
        if !allow_frame {
            return Ok(None);
        }

        let unit_token = if let Some(Token {
            ttype: TokenType::Identifier(_, Some(reserved)),
            loc,
        }) = self.peek_token()?
        {
            let unit = match reserved {
                Reserved::ROWS => WindowFrameUnit::Rows,
                Reserved::RANGE => WindowFrameUnit::Range,
                Reserved::GROUPS => WindowFrameUnit::Groups,
                _ => return Ok(None),
            };
            let loc = *loc;
            self.consume_token()?;
            Node(unit, self.meta_tracker.on_node_start(loc))
        } else {
            return Ok(None);
        };

        enum AllowedDirections {
            Both,
            Preceding,
            Following,
        }
        fn parse_direction_token<'s, M: MetaTracker<'s>>(
            parser: &mut ParserInner<'s, M>,
            allow: AllowedDirections,
        ) -> Result<Node<WindowFrameBoundDirection, M::NodeId>> {
            let expected = match allow {
                AllowedDirections::Both => "the PRECEDING or FOLLOWING keyword",
                AllowedDirections::Preceding => "the PRECEDING keyword",
                AllowedDirections::Following => "the FOLLOWING keyword",
            };
            match parser.next_token()? {
                Some(t) => match t.ttype {
                    TokenType::Identifier(_, Some(Reserved::PRECEDING))
                        if !matches!(allow, AllowedDirections::Following) =>
                    {
                        Ok(Node(
                            WindowFrameBoundDirection::Preceding,
                            parser.meta_tracker.on_node_start(t.loc),
                        ))
                    }
                    TokenType::Identifier(_, Some(Reserved::FOLLOWING))
                        if !matches!(allow, AllowedDirections::Preceding) =>
                    {
                        Ok(Node(
                            WindowFrameBoundDirection::Following,
                            parser.meta_tracker.on_node_start(t.loc),
                        ))
                    }
                    _ => Err(Error::unexpected_token(t, expected)),
                },
                None => unexpected_eof_err!(parser, expected),
            }
        }
        fn parse_bound_type<'s, M: MetaTracker<'s>>(
            parser: &mut ParserInner<'s, M>,
            unbounded_directions: AllowedDirections,
            value_directions: AllowedDirections,
        ) -> Result<WindowFrameBoundType<'s, M::NodeId>> {
            if let Some(t) = parser.peek_token()? {
                match t.ttype {
                    TokenType::Identifier(_, Some(Reserved::UNBOUNDED)) => {
                        let unbounded_token = {
                            let loc = t.loc;
                            parser.consume_token()?;
                            Node((), parser.meta_tracker.on_node_start(loc))
                        };
                        let direction_token = parse_direction_token(parser, unbounded_directions)?;
                        return Ok(WindowFrameBoundType::Unbounded {
                            unbounded_token,
                            direction_token,
                        });
                    }
                    TokenType::Identifier(_, Some(Reserved::CURRENT)) => {
                        let current_token = {
                            let loc = t.loc;
                            parser.consume_token()?;
                            Node((), parser.meta_tracker.on_node_start(loc))
                        };
                        let row_token = expect_reserved!(|t = parser.next_token()| "the ROW keyword" match {
                            Reserved::ROW => Node((), parser.meta_tracker.on_node_start(t.loc)),
                        });
                        return Ok(WindowFrameBoundType::CurrentRow {
                            current_token,
                            row_token,
                        });
                    }
                    _ => {
                        return Ok(WindowFrameBoundType::Value {
                            expr: parser.parse_expr()?,
                            direction_token: parse_direction_token(parser, value_directions)?,
                        });
                    }
                }
            }
            unexpected_eof_err!(
                parser,
                "the UNBOUNDED or CURRENT keyword or a value expression"
            )
        }
        let bounds = match self.peek_token()? {
            None => {
                return unexpected_eof_err!(
                    self,
                    "the BETWEEN, UNBOUNDED, CURRENT keyword, or an expression"
                );
            }
            Some(Token {
                ttype: TokenType::Keyword(Keyword::BETWEEN),
                loc,
            }) => {
                let between_token = {
                    let loc = *loc;
                    self.consume_token()?;
                    Node((), self.meta_tracker.on_node_start(loc))
                };
                let start =
                    parse_bound_type(self, AllowedDirections::Preceding, AllowedDirections::Both)?;
                let and_token = expect_token!(|t = self.next_token()| "the AND keyword" match {
                    TokenType::Keyword(Keyword::AND) => Node((), self.meta_tracker.on_node_start(t.loc)),
                });
                let end = parse_bound_type(
                    self,
                    AllowedDirections::Following,
                    /*
                    // https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Analytic-Functions.html#GUID-527832F7-63C0-4445-8C16-307FA5084056__GUID-0A0B25DD-63EC-4C45-A2E5-01123E3E2AFA
                    For `RANGE` or `ROW`:
                        - If `value_expr FOLLOWING` is the start point, then the end point must be `value_expr FOLLOWING`.
                        - If `value_expr PRECEDING` is the end point, then the start point must be `value_expr PRECEDING`.

                    Personal note: on Oracle 21, this applies to the `GROUPS` unit as well.
                    Also: `... rows between unbounded preceding and 1 preceding` works fine despite the start bound not being a `<value_expr> preceding`
                     */
                    match &start {
                        // ~ can only be "preceding", hence, making it work with `<value_expr> [preceding|following]` as an end bound
                        WindowFrameBoundType::Unbounded { .. } => AllowedDirections::Both,
                        // ~ effectively enforcing the second rule stated above
                        WindowFrameBoundType::CurrentRow { .. } => AllowedDirections::Following,
                        WindowFrameBoundType::Value {
                            direction_token: Node(direction, _),
                            ..
                        } => match direction {
                            WindowFrameBoundDirection::Preceding => AllowedDirections::Both,
                            WindowFrameBoundDirection::Following => AllowedDirections::Following,
                        },
                    },
                )?;
                WindowFrameBounds::Between {
                    between_token,
                    start,
                    and_token,
                    end,
                }
            }
            _ => WindowFrameBounds::Start(parse_bound_type(
                self,
                AllowedDirections::Preceding,
                AllowedDirections::Preceding,
            )?),
        };
        let exclude = self.parse_window_frame_exclude_()?;
        Ok(Some(WindowFrame {
            unit_token,
            bounds,
            exclude,
        }))
    }

    fn parse_window_frame_exclude_(&mut self) -> Result<Option<WindowFrameExclude<M::NodeId>>> {
        if let Some(Token {
            ttype: TokenType::Identifier(_, Some(Reserved::EXCLUDE)),
            loc,
        }) = self.peek_token()?
        {
            let exclude_token = {
                let loc = *loc;
                self.consume_token()?;
                Node((), self.meta_tracker.on_node_start(loc))
            };
            let subject = expect_token!(|t = self.next_token()| "the CURRENT [ROW], GROUPS, TIES, or NO [OTHERS] keyword" match {
                TokenType::Keyword(Keyword::GROUP) => {
                    WindowFrameExcludeSubject::Group {
                        group_token: Node((), self.meta_tracker.on_node_start(t.loc)),
                    }
                }
                TokenType::Identifier(_, Some(Reserved::CURRENT)) => {
                    let current_token = Node((), self.meta_tracker.on_node_start(t.loc));
                    let row_token = expect_reserved!(|t = self.next_token()| "the ROW keyword" match {
                        Reserved::ROW => Node((), self.meta_tracker.on_node_start(t.loc)),
                    });
                    WindowFrameExcludeSubject::CurrentRow { current_token, row_token }
                },
                TokenType::Identifier(_, Some(Reserved::TIES)) => {
                    WindowFrameExcludeSubject::Ties { ties_token: Node((), self.meta_tracker.on_node_start(t.loc)) }
                }
                TokenType::Identifier(_, Some(Reserved::NO)) => {
                    let no_token = Node((), self.meta_tracker.on_node_start(t.loc));
                    let others_token = expect_reserved!(|t = self.next_token()| "the OTHERS keyword" match {
                        Reserved::OTHERS => Node((), self.meta_tracker.on_node_start(t.loc)),
                    });
                    WindowFrameExcludeSubject::NoOthers { no_token, others_token }
                }
            });
            Ok(Some(WindowFrameExclude {
                exclude_token,
                subject,
            }))
        } else {
            Ok(None)
        }
    }
}