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
use super::{Duplicates, Expr, Ident, Identifier, Node, OrderBy, WindowSpec};

#[derive(Debug)]
pub struct Function<'s, ID> {
    /// name of the function, e.g. `function_name` or
    /// `schema.package.function_name`
    pub name: Identifier<'s, ID>,

    /// parameters, e.g. arguments and additional clauses, of the function call
    pub params: FunctionParams<'s, ID>,
}

/// A generic function call's parameters, e.g. arguments.
#[derive(Debug)]
pub struct FunctionParams<'s, ID> {
    /// Arguments passed to the called function, e.g. `(1, 'asdf')`
    pub args: Node<FunctionArgs<'s, ID>, ID>,

    /// Achieves ordering within groups processed by some aggregate functions
    /// e.g. `<aggr_func>(..) WITHIN GROUP (ORDER BY ..)`
    pub within_group: Option<WithinGroup<'s, ID>>,

    /// Determines whether a calculation begins at the first or last row
    /// of an window of an analytic function call, e.g.
    /// `SELECT NTH_VALUE(...) FROM FIRST OVER (...) FROM table`
    pub from_row: Option<FromRow<ID>>,

    /// Determines whether `NULL`s are to be respected or ignored by
    /// certain aggregate or analytic function calls,
    /// e.g. `... { RESPECT | IGNORE } NULLS`.
    pub respect_nulls: Option<RespectNulls<ID>>,

    /// Analytical function call over a window,
    /// e.g. `count(1) OVER (PARTITION BY col1)`
    pub over: Option<FunctionWindow<'s, ID>>,
}

/// Arguments to a function call, e.g. `(1, 'a')`
#[derive(Debug)]
pub enum FunctionArgs<'s, ID> {
    /// an empty list of arguments, e.g. `()`.  metadata (e.g. comments) of
    /// the "inner space" of the empty list is associated with the contained
    /// node.
    None(Node<(), ID>),

    /// a list of argument values / expressions, e.g. `(1, 'hello')`;
    List(FunctionArgsList<'s, ID>),
}

impl<'s, ID> FunctionArgs<'s, ID> {
    pub(crate) fn is_empty(&self) -> bool {
        match self {
            FunctionArgs::None(_) => true,
            FunctionArgs::List(FunctionArgsList {
                duplicates: _,
                args,
            }) => args.is_empty(),
        }
    }

    pub(crate) fn len(&self) -> usize {
        match self {
            FunctionArgs::None(_) => 0,
            FunctionArgs::List(FunctionArgsList {
                duplicates: _,
                args,
            }) => args.len(),
        }
    }
}

impl<'s, ID> FunctionArgs<'s, ID> {
    /// Retrieves the duplicates clause - if any.
    pub fn duplicates(&self) -> Option<&Node<Duplicates, ID>> {
        match self {
            FunctionArgs::None(_) => None,
            FunctionArgs::List(FunctionArgsList {
                duplicates,
                args: _,
            }) => duplicates.as_ref(),
        }
    }

    /// Retrieves an iterator over the arguments.
    pub fn iter(&self) -> impl Iterator<Item = &FunctionArg<'s, ID>> {
        match self {
            FunctionArgs::None(_) => MaybeIter(None),
            FunctionArgs::List(FunctionArgsList {
                duplicates: _,
                args,
            }) => MaybeIter(Some(args.iter())),
        }
    }
}

struct MaybeIter<I>(Option<I>);

impl<I> Iterator for MaybeIter<I>
where
    I: Iterator,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        match self.0.as_mut() {
            None => None,
            Some(inner) => inner.next(),
        }
    }
}

/// A non-empty list of function arguments
#[derive(Debug)]
pub struct FunctionArgsList<'s, ID> {
    /// a possible `DISTINCT | UNIQUE | ALL` keyword at the beginning of the
    /// arguments list; allowed only for some aggregate and user-defined functions
    pub duplicates: Option<Node<Duplicates, ID>>,

    /// the list of argument expressions
    pub args: Vec<FunctionArg<'s, ID>>,
}

/// A single argument of a function call; part of a
/// [function call's parameters](FunctionParams)
#[derive(Debug)]
pub struct FunctionArg<'s, ID> {
    /// the argument itself, e.g. an expression
    pub arg: FunctionArgType<'s, ID>,

    /// additional clauses after the argument, only where supported
    pub clause: Option<FunctionArgClause<'s, ID>>,
}

impl<'s, ID, T> From<T> for FunctionArg<'s, ID>
where
    T: Into<FunctionArgType<'s, ID>>,
{
    fn from(value: T) -> Self {
        Self {
            arg: value.into(),
            clause: None,
        }
    }
}

/// A function argument
#[derive(Debug)]
pub enum FunctionArgType<'s, ID> {
    /// The `*` wildcard; only allowed in for a few built-in functions,
    /// e.g. `COUNT(*)`.
    Wildcard(Node<(), ID>),

    /// The expression argument to a call of the `EXTRACT` built-in function
    ExtractExpr(ExtractExpr<'s, ID>),

    /// A named parameter, e.g. `FOO => 'bar'`
    ///
    /// Built-In functions do not allow named parameters.
    Named(NamedFunctionArg<'s, ID>),

    /// A general, value expression as an argument, e.g. `1 + 2` or `'hello'`
    Expr(Expr<'s, ID>),
}

impl<'s, ID> From<Expr<'s, ID>> for FunctionArgType<'s, ID> {
    fn from(value: Expr<'s, ID>) -> Self {
        Self::Expr(value)
    }
}

impl<'s, ID> From<ExtractExpr<'s, ID>> for FunctionArgType<'s, ID> {
    fn from(value: ExtractExpr<'s, ID>) -> Self {
        Self::ExtractExpr(value)
    }
}

impl<'s, ID> From<NamedFunctionArg<'s, ID>> for FunctionArgType<'s, ID> {
    fn from(value: NamedFunctionArg<'s, ID>) -> Self {
        Self::Named(value)
    }
}

/// Additional clauses for [function arguments](FunctionArg)
#[derive(Debug)]
pub enum FunctionArgClause<'s, ID> {
    /// e.g. `USING {CHAR_CS | NCHAR_CS}` for the built-ins `CHR` and
    /// `TRANSLATE…USING` functions
    UsingCharset(UsingCharset<ID>),

    /// e.g. `RESPECT NULLS` as a clause directly after an argument; only some
    /// built-in functions (e.g.`FIRST_VALUE`) allow such an argument clause
    RespectNulls(RespectNulls<ID>),

    /// e.g. `ON OVERFLOW TRUNCATE '...' WITH COUNT` as part of the built-in
    /// `LISTAGG` function.
    OnOverflow(OnOverflow<'s, ID>),
}

impl<'s, ID> From<UsingCharset<ID>> for FunctionArgClause<'s, ID> {
    fn from(value: UsingCharset<ID>) -> Self {
        Self::UsingCharset(value)
    }
}

impl<'s, ID> From<RespectNulls<ID>> for FunctionArgClause<'s, ID> {
    fn from(value: RespectNulls<ID>) -> Self {
        Self::RespectNulls(value)
    }
}

impl<'s, ID> From<OnOverflow<'s, ID>> for FunctionArgClause<'s, ID> {
    fn from(value: OnOverflow<'s, ID>) -> Self {
        Self::OnOverflow(value)
    }
}

/// A named function argument, e.g. `FOO => 'bar'`
#[derive(Debug)]
pub struct NamedFunctionArg<'s, ID> {
    /// the name of the parameter to which an argument is supplied
    pub name: Node<Ident<'s>, ID>,
    /// the operator / separator token, i.e. `=>`
    pub operator_token: Node<(), ID>,
    /// the argument value
    pub arg: Expr<'s, ID>,
}

/// Definition of an analytical window application as part of a [function call](Function),
/// e.g. `count(1) OVER (PARTITION BY col1)`
#[derive(Debug)]
pub struct FunctionWindow<'s, ID> {
    /// the `OVER` keyword
    pub over_token: Node<(), ID>,

    /// the definition of the window,
    /// e.g. `window_name` or `(PARTITION BY ...)`
    pub window: FunctionWindowType<'s, ID>,
}

/// A reference to or a definition of an analytical window as part of a
/// [function call](Function).
#[derive(Debug)]
pub enum FunctionWindowType<'s, ID> {
    /// Reference by name to a defined window
    Named(Node<Ident<'s>, ID>),

    /// Specification of a window
    Specified(Node<WindowSpec<'s, ID>, ID>),
}

/// Represents a `WITHIN GROUP (ORDER BY ...)` clause part of some analytical
/// function calls.
///
/// See [FunctionParams::within_group]
#[derive(Debug)]
pub struct WithinGroup<'s, ID> {
    /// the `WITHIN` keyword
    pub within_token: Node<(), ID>,

    /// the `GROUP` keyword
    pub group_token: Node<(), ID>,

    /// the order by within parentheses, e.g. `(ORDER BY <expr> ..)`
    pub order_by: Node<OrderBy<'s, ID>, ID>,
}

/// `USING (N)CHAR_CS` clause part of the built-in `CHR` or
/// `TRANSLATE…USING` functions
///
/// See [FunctionArgClause::UsingCharset]
#[derive(Debug)]
pub struct UsingCharset<ID> {
    /// the `USING` keyword
    pub using_token: Node<(), ID>,

    /// the `NCHAR_CS` keyword
    pub charset_token: Node<Charset, ID>,
}

/// Denotes a chosen character set; used as part of the `CHR` and
/// `TRANSLATE…USING` functions.
#[derive(Debug, Copy, Clone)]
pub enum Charset {
    /// `CHAR_CS` denoting the database character set
    Database,
    /// `NCHAR_CS` denoting the national character set
    National,
}

/// Arguments to a call of the `EXTRACT` built-in function,
///  e.g. `SELECT EXTRACT(month FROM SYSDATE) FROM DUAL`
#[derive(Debug)]
pub struct ExtractExpr<'s, ID> {
    pub datetime_token: Node<ExtractDatetime, ID>,
    pub from_token: Node<(), ID>,
    pub expr: Expr<'s, ID>,
}

/// Datetime field parameter to the `EXTRACT` built-in function
#[derive(Debug, Copy, Clone)]
pub enum ExtractDatetime {
    Year,
    Month,
    Day,
    Hour,
    Minute,
    Second,
    TimezoneHour,
    TimezoneMinute,
    TimezoneRegion,
    TimezoneAbbreviation,
}

/// The `FROM {FIRST | LAST}` clause
#[derive(Debug)]
pub struct FromRow<ID> {
    /// the `FROM` keyword
    pub from_token: Node<(), ID>,
    /// either the `FIRST` or `LAST` keyword
    pub type_token: Node<FromRowType, ID>,
}

/// The particular type of [FromRow]
#[derive(Debug, Copy, Clone)]
pub enum FromRowType {
    First,
    Last,
}

/// The `{RESPECT | IGNORE} NULLS` clause
///
/// See [FunctionParams::respect_nulls]
#[derive(Debug)]
pub struct RespectNulls<ID> {
    /// either the `RESPECT` or `IGNORE` keyword
    pub type_token: Node<RespectNullsType, ID>,
    /// the `NULLS` keywords
    pub nulls_token: Node<(), ID>,
}

/// The particular type of [RespectNulls]
#[derive(Debug, Copy, Clone)]
pub enum RespectNullsType {
    /// e.g. `RESPECT NULLS`
    Respect,
    /// e.g. `IGNORE NULLS`
    Ignore,
}

/// The "ON OVERFLOW ..." clause used with the built-in `LISTAGG` function
#[derive(Debug)]
pub struct OnOverflow<'s, ID> {
    /// the `ON` keyword
    pub on_token: Node<(), ID>,
    /// the `OVERFLOW` keyword
    pub overflow_token: Node<(), ID>,
    /// either the `ERROR` keyword or the `TRUNCATE ...` clause
    pub action: OnOverflowAction<'s, ID>,
}

/// An action to carry out ["ON OVERFLOW"](OnOverflow) as part of a `LISTAGG`
/// function call.
#[derive(Debug)]
pub enum OnOverflowAction<'s, ID> {
    /// e.g. `... ON OVERFLOW ERROR`
    Error { error_token: Node<(), ID> },
    /// e.g. `... ON OVERFLOW TRUNCATE ['...'] [{WITH | WITHOUT} COUNT]`
    Truncate {
        /// the `TRUNCATE` keyword
        truncate_token: Node<(), ID>,
        /// the truncation indicator (note: Oracle will accept only
        /// _constant_ or _literal_ expressions; the parser does _not_
        /// enforce this.)
        indicator: Option<Expr<'s, ID>>,
        /// the optional `{WITH | WITHOUT} COUNT` clause
        with_count: Option<OnOverflowCount<ID>>,
    },
}

/// The `{WITH | WITHOUT} COUNT` clause of a
/// [`... ON OVERFLOW TRUNCATE ...` clause](OnOverflowAction::Truncate)
///
/// This is part of the [OnOverflow] clause in a call to the `LISTAGG`
/// built-in function.
#[derive(Debug)]
pub struct OnOverflowCount<ID> {
    /// the `WITH` or `WITHOUT` keyword; defines whether a count of truncated
    /// values is to be produced or not
    pub count_option: Node<OnOverflowCountOption, ID>,
    /// the `COUNT` keyword
    pub count_token: Node<(), ID>,
}

/// Defines whether or not a count is desirable upon a
/// [`... OVERFLOW TRUNCATE ...`](OnOverflowCount).
///
/// This is part of the [OnOverflow] clause in a call to the `LISTAGG`
/// built-in function.
#[derive(Debug, Copy, Clone)]
pub enum OnOverflowCountOption {
    /// Include the count at the end of the truncation
    With,
    /// Do not produce a count at the end of the truncation
    Without,
}