This repository was archived by the owner on Dec 25, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathparser.rs
2661 lines (2484 loc) · 101 KB
/
parser.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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
//! SQL Parser
use log::debug;
use super::ast::*;
use super::dialect::keywords;
use super::dialect::Dialect;
use super::tokenizer::*;
use std::error::Error;
use std::fmt;
use crate::ast::{ParsedDate, ParsedTimestamp};
// Use `Parser::expected` instead, if possible
macro_rules! parser_err {
($MSG:expr) => {
Err(ParserError::ParserError($MSG.to_string()))
};
($($arg:tt)*) => {
Err(ParserError::ParserError(format!($($arg)*)))
};
}
mod datetime;
#[derive(Debug, Clone, PartialEq)]
pub enum ParserError {
TokenizerError(String),
ParserError(String),
}
#[derive(PartialEq)]
pub enum IsOptional {
Optional,
Mandatory,
}
use IsOptional::*;
pub enum IsLateral {
Lateral,
NotLateral,
}
use IsLateral::*;
impl From<TokenizerError> for ParserError {
fn from(e: TokenizerError) -> Self {
ParserError::TokenizerError(format!("{}", e))
}
}
impl fmt::Display for ParserError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"sql parser error: {}",
match self {
ParserError::TokenizerError(s) => s,
ParserError::ParserError(s) => s,
}
)
}
}
impl Error for ParserError {}
/// SQL Parser
pub struct Parser {
tokens: Vec<Token>,
/// The index of the first unprocessed token in `self.tokens`
index: usize,
}
impl Parser {
/// Parse the specified tokens
pub fn new(tokens: Vec<Token>) -> Self {
Parser { tokens, index: 0 }
}
/// Parse a SQL statement and produce an Abstract Syntax Tree (AST)
pub fn parse_sql(dialect: &dyn Dialect, sql: String) -> Result<Vec<Statement>, ParserError> {
let mut tokenizer = Tokenizer::new(dialect, &sql);
let tokens = tokenizer.tokenize()?;
let mut parser = Parser::new(tokens);
let mut stmts = Vec::new();
let mut expecting_statement_delimiter = false;
debug!("Parsing sql '{}'...", sql);
loop {
// ignore empty statements (between successive statement delimiters)
while parser.consume_token(&Token::SemiColon) {
expecting_statement_delimiter = false;
}
if parser.peek_token().is_none() {
break;
} else if expecting_statement_delimiter {
return parser.expected("end of statement", parser.peek_token());
}
let statement = parser.parse_statement()?;
stmts.push(statement);
expecting_statement_delimiter = true;
}
Ok(stmts)
}
/// Parse a single top-level statement (such as SELECT, INSERT, CREATE, etc.),
/// stopping before the statement separator, if any.
pub fn parse_statement(&mut self) -> Result<Statement, ParserError> {
match self.next_token() {
Some(t) => match t {
Token::Word(ref w) if w.keyword != "" => match w.keyword.as_ref() {
"SELECT" | "WITH" | "VALUES" => {
self.prev_token();
Ok(Statement::Query(Box::new(self.parse_query()?)))
}
"CREATE" => Ok(self.parse_create()?),
"DROP" => Ok(self.parse_drop()?),
"DELETE" => Ok(self.parse_delete()?),
"INSERT" => Ok(self.parse_insert()?),
"UPDATE" => Ok(self.parse_update()?),
"ALTER" => Ok(self.parse_alter()?),
"COPY" => Ok(self.parse_copy()?),
"SET" => Ok(self.parse_set()?),
"SHOW" => Ok(self.parse_show()?),
"START" => Ok(self.parse_start_transaction()?),
// `BEGIN` is a nonstandard but common alias for the
// standard `START TRANSACTION` statement. It is supported
// by at least PostgreSQL and MySQL.
"BEGIN" => Ok(self.parse_begin()?),
"COMMIT" => Ok(self.parse_commit()?),
"ROLLBACK" => Ok(self.parse_rollback()?),
"PEEK" => Ok(Statement::Peek {
immediate: self.parse_keyword("IMMEDIATE"),
name: self.parse_object_name()?,
}),
"TAIL" => Ok(Statement::Tail {
name: self.parse_object_name()?,
}),
"EXPLAIN" => Ok(self.parse_explain()?),
"FLUSH" => Ok(self.parse_flush()?),
_ => parser_err!(format!(
"Unexpected keyword {:?} at the beginning of a statement",
w.to_string()
)),
},
Token::LParen => {
self.prev_token();
Ok(Statement::Query(Box::new(self.parse_query()?)))
}
unexpected => self.expected(
"a keyword at the beginning of a statement",
Some(unexpected),
),
},
None => self.expected("SQL statement", None),
}
}
/// Parse a new expression
pub fn parse_expr(&mut self) -> Result<Expr, ParserError> {
self.parse_subexpr(0)
}
/// Parse tokens until the precedence changes
pub fn parse_subexpr(&mut self, precedence: u8) -> Result<Expr, ParserError> {
debug!("parsing expr");
let mut expr = self.parse_prefix()?;
debug!("prefix: {:?}", expr);
loop {
let next_precedence = self.get_next_precedence()?;
debug!("next precedence: {:?}", next_precedence);
if precedence >= next_precedence {
break;
}
expr = self.parse_infix(expr, next_precedence)?;
}
Ok(expr)
}
/// Parse an expression prefix
pub fn parse_prefix(&mut self) -> Result<Expr, ParserError> {
let tok = self
.next_token()
.ok_or_else(|| ParserError::ParserError("Unexpected EOF".to_string()))?;
let expr = match tok {
Token::Word(w) => match w.keyword.as_ref() {
"TRUE" | "FALSE" | "NULL" => {
self.prev_token();
Ok(Expr::Value(self.parse_value()?))
}
"ARRAY" => {
self.prev_token();
Ok(Expr::Value(self.parse_value()?))
}
"CASE" => self.parse_case_expr(),
"CAST" => self.parse_cast_expr(),
"DATE" => Ok(Expr::Value(self.parse_date()?)),
"EXISTS" => self.parse_exists_expr(),
"EXTRACT" => self.parse_extract_expr(),
"INTERVAL" => self.parse_literal_interval(),
"NOT" => Ok(Expr::UnaryOp {
op: UnaryOperator::Not,
expr: Box::new(self.parse_subexpr(Self::UNARY_NOT_PREC)?),
}),
"TIME" => Ok(Expr::Value(Value::Time(self.parse_literal_string()?))),
"TIMESTAMP" => self.parse_timestamp(),
"TIMESTAMPTZ" => self.parse_timestamptz(),
// Here `w` is a word, check if it's a part of a multi-part
// identifier, a function call, or a simple identifier:
_ => match self.peek_token() {
Some(Token::LParen) | Some(Token::Period) => {
let mut id_parts: Vec<Ident> = vec![w.to_ident()];
let mut ends_with_wildcard = false;
while self.consume_token(&Token::Period) {
match self.next_token() {
Some(Token::Word(w)) => id_parts.push(w.to_ident()),
Some(Token::Mult) => {
ends_with_wildcard = true;
break;
}
unexpected => {
return self
.expected("an identifier or a '*' after '.'", unexpected);
}
}
}
if ends_with_wildcard {
Ok(Expr::QualifiedWildcard(id_parts))
} else if self.consume_token(&Token::LParen) {
self.prev_token();
self.parse_function(ObjectName(id_parts))
} else {
Ok(Expr::CompoundIdentifier(id_parts))
}
}
_ => Ok(Expr::Identifier(w.to_ident())),
},
}, // End of Token::Word
Token::Mult => Ok(Expr::Wildcard),
tok @ Token::Minus | tok @ Token::Plus => {
let op = if tok == Token::Plus {
UnaryOperator::Plus
} else {
UnaryOperator::Minus
};
Ok(Expr::UnaryOp {
op,
expr: Box::new(self.parse_subexpr(Self::PLUS_MINUS_PREC)?),
})
}
Token::Number(_)
| Token::SingleQuotedString(_)
| Token::NationalStringLiteral(_)
| Token::HexStringLiteral(_) => {
self.prev_token();
Ok(Expr::Value(self.parse_value()?))
}
Token::Parameter(s) => Ok(Expr::Parameter(match s.parse() {
Ok(n) => n,
Err(err) => return parser_err!("unable to parse parameter: {}", err),
})),
Token::LParen => {
let expr = if self.parse_keyword("SELECT") || self.parse_keyword("WITH") {
self.prev_token();
Expr::Subquery(Box::new(self.parse_query()?))
} else {
Expr::Nested(Box::new(self.parse_expr()?))
};
self.expect_token(&Token::RParen)?;
Ok(expr)
}
unexpected => self.expected("an expression", Some(unexpected)),
}?;
if self.parse_keyword("COLLATE") {
Ok(Expr::Collate {
expr: Box::new(expr),
collation: self.parse_object_name()?,
})
} else {
Ok(expr)
}
}
pub fn parse_function(&mut self, name: ObjectName) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let all = self.parse_keyword("ALL");
let distinct = self.parse_keyword("DISTINCT");
if all && distinct {
return parser_err!(format!(
"Cannot specify both ALL and DISTINCT in function: {}",
name.to_string(),
));
}
let args = self.parse_optional_args()?;
let over = if self.parse_keyword("OVER") {
// TBD: support window names (`OVER mywin`) in place of inline specification
self.expect_token(&Token::LParen)?;
let partition_by = if self.parse_keywords(vec!["PARTITION", "BY"]) {
// a list of possibly-qualified column names
self.parse_comma_separated(Parser::parse_expr)?
} else {
vec![]
};
let order_by = if self.parse_keywords(vec!["ORDER", "BY"]) {
self.parse_comma_separated(Parser::parse_order_by_expr)?
} else {
vec![]
};
let window_frame = if !self.consume_token(&Token::RParen) {
let window_frame = self.parse_window_frame()?;
self.expect_token(&Token::RParen)?;
Some(window_frame)
} else {
None
};
Some(WindowSpec {
partition_by,
order_by,
window_frame,
})
} else {
None
};
Ok(Expr::Function(Function {
name,
args,
over,
distinct,
}))
}
pub fn parse_window_frame(&mut self) -> Result<WindowFrame, ParserError> {
let units = match self.next_token() {
Some(Token::Word(w)) => w.keyword.parse::<WindowFrameUnits>()?,
unexpected => return self.expected("ROWS, RANGE, GROUPS", unexpected),
};
let (start_bound, end_bound) = if self.parse_keyword("BETWEEN") {
let start_bound = self.parse_window_frame_bound()?;
self.expect_keyword("AND")?;
let end_bound = Some(self.parse_window_frame_bound()?);
(start_bound, end_bound)
} else {
(self.parse_window_frame_bound()?, None)
};
Ok(WindowFrame {
units,
start_bound,
end_bound,
})
}
/// Parse `CURRENT ROW` or `{ <positive number> | UNBOUNDED } { PRECEDING | FOLLOWING }`
pub fn parse_window_frame_bound(&mut self) -> Result<WindowFrameBound, ParserError> {
if self.parse_keywords(vec!["CURRENT", "ROW"]) {
Ok(WindowFrameBound::CurrentRow)
} else {
let rows = if self.parse_keyword("UNBOUNDED") {
None
} else {
Some(self.parse_literal_uint()?)
};
if self.parse_keyword("PRECEDING") {
Ok(WindowFrameBound::Preceding(rows))
} else if self.parse_keyword("FOLLOWING") {
Ok(WindowFrameBound::Following(rows))
} else {
self.expected("PRECEDING or FOLLOWING", self.peek_token())
}
}
}
pub fn parse_case_expr(&mut self) -> Result<Expr, ParserError> {
let mut operand = None;
if !self.parse_keyword("WHEN") {
operand = Some(Box::new(self.parse_expr()?));
self.expect_keyword("WHEN")?;
}
let mut conditions = vec![];
let mut results = vec![];
loop {
conditions.push(self.parse_expr()?);
self.expect_keyword("THEN")?;
results.push(self.parse_expr()?);
if !self.parse_keyword("WHEN") {
break;
}
}
let else_result = if self.parse_keyword("ELSE") {
Some(Box::new(self.parse_expr()?))
} else {
None
};
self.expect_keyword("END")?;
Ok(Expr::Case {
operand,
conditions,
results,
else_result,
})
}
/// Parse a SQL CAST function e.g. `CAST(expr AS FLOAT)`
pub fn parse_cast_expr(&mut self) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let expr = self.parse_expr()?;
self.expect_keyword("AS")?;
let data_type = self.parse_data_type()?;
self.expect_token(&Token::RParen)?;
Ok(Expr::Cast {
expr: Box::new(expr),
data_type,
})
}
/// Parse a SQL EXISTS expression e.g. `WHERE EXISTS(SELECT ...)`.
pub fn parse_exists_expr(&mut self) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let exists_node = Expr::Exists(Box::new(self.parse_query()?));
self.expect_token(&Token::RParen)?;
Ok(exists_node)
}
pub fn parse_extract_expr(&mut self) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let field = self.parse_extract_field()?;
self.expect_keyword("FROM")?;
let expr = self.parse_expr()?;
self.expect_token(&Token::RParen)?;
Ok(Expr::Extract {
field,
expr: Box::new(expr),
})
}
// This function parses date/time fields for both the EXTRACT function-like
// operator and interval qualifiers. EXTRACT supports a wider set of
// date/time fields than interval qualifiers, so this function may need to
// be split in two.
pub fn parse_date_time_field(&mut self) -> Result<DateTimeField, ParserError> {
let tok = self.next_token();
if let Some(Token::Word(ref k)) = tok {
match k.keyword.as_ref() {
"YEAR" => Ok(DateTimeField::Year),
"MONTH" => Ok(DateTimeField::Month),
"DAY" => Ok(DateTimeField::Day),
"HOUR" => Ok(DateTimeField::Hour),
"MINUTE" => Ok(DateTimeField::Minute),
"SECOND" => Ok(DateTimeField::Second),
_ => self.expected("date/time field", tok)?,
}
} else {
self.expected("date/time field", tok)?
}
}
// Hacked version of parse_date_time_field to allow directly passing strs.
pub fn parse_date_time_field_given_str(
&mut self,
s: &str,
) -> Result<DateTimeField, ParserError> {
match s {
"YEAR" => Ok(DateTimeField::Year),
"MONTH" => Ok(DateTimeField::Month),
"DAY" => Ok(DateTimeField::Day),
"HOUR" => Ok(DateTimeField::Hour),
"MINUTE" => Ok(DateTimeField::Minute),
"SECOND" => Ok(DateTimeField::Second),
_ => parser_err!("Expected date/time field, found: {}", s),
}
}
/// Parse the kinds of things that can be fed to EXTRACT and DATE_TRUNC
pub fn parse_extract_field(&mut self) -> Result<ExtractField, ParserError> {
let tok = self.next_token();
let field: Result<ExtractField, _> = match tok {
Some(Token::Word(ref k)) => k.keyword.parse(),
Some(Token::SingleQuotedString(ref s)) => s.parse(),
_ => return self.expected("extract field token", tok),
};
match field {
Ok(f) => Ok(f),
Err(_) => self.expected("valid extract field", tok)?,
}
}
pub fn contains_date_time_str(&mut self, interval: &str) -> Result<bool, ParserError> {
let upper_case_interval = interval.to_uppercase();
let date_time_strs = ["YEAR", "MONTH", "DAY", "HOUR", "MINUTE", "SECOND"];
for dts in &date_time_strs {
if upper_case_interval.contains(dts) {
return Ok(true);
}
}
Ok(false)
}
fn parse_date(&mut self) -> Result<Value, ParserError> {
use std::convert::TryInto;
let value = self.parse_literal_string()?;
let pdt = Self::parse_interval_string(&value, &DateTimeField::Year)?;
match (pdt.year, pdt.month, pdt.day, pdt.hour) {
(Some(year), Some(month), Some(day), None) => {
let p_err = |e: std::num::TryFromIntError, field: &str| {
ParserError::ParserError(format!(
"{} in date '{}' is invalid: {}",
field, value, e
))
};
// type inference with try_into() fails so we need to mutate it negative
let mut year: i64 = year.try_into().map_err(|e| p_err(e, "Year"))?;
year *= pdt.positivity();
if month > 12 || month == 0 {
return parser_err!(
"Month in date '{}' must be a number between 1 and 12, got: {}",
value,
month
);
}
let month: u8 = month.try_into().expect("invalid month");
let day: u8 = day.try_into().map_err(|e| p_err(e, "Day"))?;
if day == 0 {
parser_err!("Day in date '{}' cannot be zero: {}", value, day)?;
}
Ok(Value::Date(value, ParsedDate { year, month, day }))
}
(Some(_), Some(_), Some(_), Some(hours)) => parser_err!(
"Hours cannot be supplied for DATE, got {} in '{}'",
hours,
value
),
(_, _, _, _) => Err(ParserError::ParserError(format!(
"year, day and month are all required, got: '{}'",
value
))),
}
}
fn parse_timestamp(&mut self) -> Result<Expr, ParserError> {
if self.parse_keyword("WITH") {
self.expect_keywords(&["TIME", "ZONE"])?;
return Ok(Expr::Value(self.parse_timestamp_inner(true)?));
} else if self.parse_keyword("WITHOUT") {
self.expect_keywords(&["TIME", "ZONE"])?;
}
Ok(Expr::Value(self.parse_timestamp_inner(false)?))
}
fn parse_timestamptz(&mut self) -> Result<Expr, ParserError> {
Ok(Expr::Value(self.parse_timestamp_inner(true)?))
}
fn parse_timestamp_inner(&mut self, parse_timezone: bool) -> Result<Value, ParserError> {
use std::convert::TryInto;
let value = self.parse_literal_string()?;
let pdt = Self::parse_timestamp_string(&value, parse_timezone)?;
match (
pdt.year,
pdt.month,
pdt.day,
pdt.hour,
pdt.minute,
pdt.second,
pdt.nano,
pdt.timezone_offset_second,
) {
(
Some(year),
Some(month),
Some(day),
Some(hour),
Some(minute),
Some(second),
nano,
timezone_offset_second,
) => {
let p_err = |e: std::num::TryFromIntError, field: &str| {
ParserError::ParserError(format!(
"{} in date '{}' is invalid: {}",
field, value, e
))
};
// type inference with try_into() fails so we need to mutate it negative
let mut year: i64 = year.try_into().map_err(|e| p_err(e, "Year"))?;
year *= pdt.positivity();
if month > 12 || month == 0 {
return parser_err!(
"Month in date '{}' must be a number between 1 and 12, got: {}",
value,
month
);
}
let month: u8 = month.try_into().expect("invalid month");
if month == 0 {
parser_err!("Month in timestamp '{}' cannot be zero: {}", value, day)?;
}
let day: u8 = day.try_into().map_err(|e| p_err(e, "Day"))?;
if day == 0 {
parser_err!("Day in timestamp '{}' cannot be zero: {}", value, day)?;
}
let hour: u8 = hour.try_into().map_err(|e| p_err(e, "Hour"))?;
if hour > 23 {
parser_err!("Hour in timestamp '{}' cannot be > 23: {}", value, hour)?;
}
let minute: u8 = minute.try_into().map_err(|e| p_err(e, "Minute"))?;
if minute > 59 {
parser_err!("Minute in timestamp '{}' cannot be > 59: {}", value, minute)?;
}
let second: u8 = second.try_into().map_err(|e| p_err(e, "Minute"))?;
if second > 60 {
parser_err!("Second in timestamp '{}' cannot be > 60: {}", value, second)?;
}
if parse_timezone {
return Ok(Value::TimestampTz(
value,
ParsedTimestamp {
year,
month,
day,
hour,
minute,
second,
nano: nano.unwrap_or(0),
timezone_offset_second: timezone_offset_second.unwrap_or(0),
},
));
}
Ok(Value::Timestamp(
value,
ParsedTimestamp {
year,
month,
day,
hour,
minute,
second,
nano: nano.unwrap_or(0),
timezone_offset_second: 0,
},
))
}
_ => Err(ParserError::ParserError(format!(
"timestamp is missing fields, year through second are all required, got: '{}'",
value
))),
}
}
/// Parse an INTERVAL literal.
///
/// Some syntactically valid intervals:
///
/// 1. `INTERVAL '1' DAY`
/// 2. `INTERVAL '1-1' YEAR TO MONTH`
/// 3. `INTERVAL '1' SECOND`
/// 4. `INTERVAL '1:1:1.1' HOUR (5) TO SECOND (5)`
/// 5. `INTERVAL '1.1' SECOND (2, 2)`
/// 6. `INTERVAL '1:1' HOUR (5) TO MINUTE (5)`
///
/// Note that we do not currently attempt to parse the quoted value.
pub fn parse_literal_interval(&mut self) -> Result<Expr, ParserError> {
// The SQL standard allows an optional sign before the raw_value string, but
// it is not clear if any implementations support that syntax, so we
// don't currently try to parse it. (The sign can instead be included
// inside the raw_value string.)
// The first token in an interval is a string literal which specifies
// the duration of the interval.
let mut raw_value = self.parse_literal_string()?;
let leading_field = if self.contains_date_time_str(&raw_value)? {
// Hack to allow INTERVAL types like:
// INTERVAL '-30 day'
let (new_raw_value, leading_field) = {
let split = raw_value.split(" ").collect::<Vec<&str>>();
if split.len() == 2 {
(
String::from(split[0]),
self.parse_date_time_field_given_str(&split[1].to_uppercase())?,
)
} else {
return parser_err!("Invalid INTERVAL: {:#?}", raw_value);
}
};
raw_value = new_raw_value;
leading_field
} else {
// Following the string literal is a qualifier which indicates the units
// of the duration specified in the string literal.
//
// Note that PostgreSQL allows omitting the qualifier, but we currently
// require at least the leading field, in accordance with the ANSI spec.
self.parse_date_time_field()?
};
let (leading_precision, last_field, fsec_precision) =
if leading_field == DateTimeField::Second {
// SQL mandates special syntax for `SECOND TO SECOND` literals.
// Instead of
// `SECOND [(<leading precision>)] TO SECOND[(<fractional seconds precision>)]`
// one must use the special format:
// `SECOND [( <leading precision> [ , <fractional seconds precision>] )]`
let last_field = None;
let (leading_precision, fsec_precision) = self.parse_optional_precision_scale()?;
(leading_precision, last_field, fsec_precision)
} else {
let leading_precision = self.parse_optional_precision()?;
if self.parse_keyword("TO") {
let last_field = Some(self.parse_date_time_field()?);
let fsec_precision = if last_field == Some(DateTimeField::Second) {
self.parse_optional_precision()?
} else {
None
};
(leading_precision, last_field, fsec_precision)
} else {
(leading_precision, None, None)
}
};
let value = Self::parse_interval_string(&raw_value, &leading_field)?;
Ok(Expr::Value(Value::Interval(IntervalValue {
value: raw_value,
parsed: value,
leading_field,
leading_precision,
last_field,
fractional_seconds_precision: fsec_precision,
})))
}
/// Parse an operator following an expression
pub fn parse_infix(&mut self, expr: Expr, precedence: u8) -> Result<Expr, ParserError> {
debug!("parsing infix");
let tok = self.next_token().unwrap(); // safe as EOF's precedence is the lowest
let regular_binary_operator = match tok {
Token::Eq => Some(BinaryOperator::Eq),
Token::Neq => Some(BinaryOperator::NotEq),
Token::Gt => Some(BinaryOperator::Gt),
Token::GtEq => Some(BinaryOperator::GtEq),
Token::Lt => Some(BinaryOperator::Lt),
Token::LtEq => Some(BinaryOperator::LtEq),
Token::Plus => Some(BinaryOperator::Plus),
Token::Minus => Some(BinaryOperator::Minus),
Token::Mult => Some(BinaryOperator::Multiply),
Token::Mod => Some(BinaryOperator::Modulus),
Token::Div => Some(BinaryOperator::Divide),
Token::JsonGet => Some(BinaryOperator::JsonGet),
Token::JsonGetAsText => Some(BinaryOperator::JsonGetAsText),
Token::JsonGetPath => Some(BinaryOperator::JsonGetPath),
Token::JsonGetPathAsText => Some(BinaryOperator::JsonGetPathAsText),
Token::JsonContainsJson => Some(BinaryOperator::JsonContainsJson),
Token::JsonContainedInJson => Some(BinaryOperator::JsonContainedInJson),
Token::JsonContainsField => Some(BinaryOperator::JsonContainsField),
Token::JsonContainsAnyFields => Some(BinaryOperator::JsonContainsAnyFields),
Token::JsonContainsAllFields => Some(BinaryOperator::JsonContainsAllFields),
Token::JsonConcat => Some(BinaryOperator::JsonConcat),
Token::JsonDeletePath => Some(BinaryOperator::JsonDeletePath),
Token::JsonContainsPath => Some(BinaryOperator::JsonContainsPath),
Token::JsonApplyPathPredicate => Some(BinaryOperator::JsonApplyPathPredicate),
Token::Word(ref k) => match k.keyword.as_ref() {
"AND" => Some(BinaryOperator::And),
"OR" => Some(BinaryOperator::Or),
"LIKE" => Some(BinaryOperator::Like),
"NOT" => {
if self.parse_keyword("LIKE") {
Some(BinaryOperator::NotLike)
} else {
None
}
}
_ => None,
},
_ => None,
};
if let Some(op) = regular_binary_operator {
let any = self.parse_keyword("ANY");
let some = !any && self.parse_keyword("SOME");
let all = !any && !some && self.parse_keyword("ALL");
if any || some || all {
use BinaryOperator::*;
match op {
Eq | NotEq | Gt | GtEq | Lt | LtEq => (),
_ => self.expected("comparison operator", Some(tok))?,
}
self.expect_token(&Token::LParen)?;
let query = self.parse_query()?;
self.expect_token(&Token::RParen)?;
if any || some {
Ok(Expr::Any {
left: Box::new(expr),
op,
right: Box::new(query),
some,
})
} else {
Ok(Expr::All {
left: Box::new(expr),
op,
right: Box::new(query),
})
}
} else {
Ok(Expr::BinaryOp {
left: Box::new(expr),
op,
right: Box::new(self.parse_subexpr(precedence)?),
})
}
} else if let Token::Word(ref k) = tok {
match k.keyword.as_ref() {
"IS" => {
if self.parse_keyword("NULL") {
Ok(Expr::IsNull(Box::new(expr)))
} else if self.parse_keywords(vec!["NOT", "NULL"]) {
Ok(Expr::IsNotNull(Box::new(expr)))
} else {
self.expected("NULL or NOT NULL after IS", self.peek_token())
}
}
"NOT" | "IN" | "BETWEEN" => {
self.prev_token();
let negated = self.parse_keyword("NOT");
if self.parse_keyword("IN") {
self.parse_in(expr, negated)
} else if self.parse_keyword("BETWEEN") {
self.parse_between(expr, negated)
} else {
self.expected("IN or BETWEEN after NOT", self.peek_token())
}
}
// Can only happen if `get_next_precedence` got out of sync with this function
_ => panic!("No infix parser for token {:?}", tok),
}
} else if Token::DoubleColon == tok {
self.parse_pg_cast(expr)
} else {
// Can only happen if `get_next_precedence` got out of sync with this function
panic!("No infix parser for token {:?}", tok)
}
}
/// parse
///
/// ```text
/// <unquoted interval string> ::=
/// [ <sign> ] { <year-month literal> | <day-time literal> }
/// <year-month literal> ::=
/// <years value> [ <minus sign> <months value> ]
/// | <months value>
/// <day-time literal> ::=
/// <day-time interval>
/// | <time interval>
/// <day-time interval> ::=
/// <days value> [ <space> <hours value> [ <colon> <minutes value>
/// [ <colon> <seconds value> ] ] ]
/// <time interval> ::=
/// <hours value> [ <colon> <minutes value> [ <colon> <seconds value> ] ]
/// | <minutes value> [ <colon> <seconds value> ]
/// | <seconds value>
/// ```
pub fn parse_interval_string(
value: &str,
leading_field: &DateTimeField,
) -> Result<ParsedDateTime, ParserError> {
if value.is_empty() {
return Err(ParserError::ParserError(
"Interval date string is empty!".to_string(),
));
}
let toks = datetime::tokenize_interval(value)?;
datetime::build_parsed_datetime(&toks, leading_field, value)
}
pub fn parse_timestamp_string(
value: &str,
parse_timezone: bool,
) -> Result<ParsedDateTime, ParserError> {
if value.is_empty() {
return Err(ParserError::ParserError(
"Timestamp string is empty!".to_string(),
));
}
let (ts_string, tz_string) = datetime::split_timestamp_string(value);
let mut pdt = Self::parse_interval_string(ts_string, &DateTimeField::Year)?;
if !parse_timezone || tz_string.is_empty() {
return Ok(pdt);
}
pdt.timezone_offset_second = Some(datetime::parse_timezone_offset_second(tz_string)?);
Ok(pdt)
}
/// Parses the parens following the `[ NOT ] IN` operator
pub fn parse_in(&mut self, expr: Expr, negated: bool) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
let in_op = if self.parse_keyword("SELECT") || self.parse_keyword("WITH") {
self.prev_token();
Expr::InSubquery {
expr: Box::new(expr),
subquery: Box::new(self.parse_query()?),
negated,
}
} else {
Expr::InList {
expr: Box::new(expr),
list: self.parse_comma_separated(Parser::parse_expr)?,
negated,
}
};
self.expect_token(&Token::RParen)?;
Ok(in_op)
}
/// Parses `BETWEEN <low> AND <high>`, assuming the `BETWEEN` keyword was already consumed
pub fn parse_between(&mut self, expr: Expr, negated: bool) -> Result<Expr, ParserError> {
// Stop parsing subexpressions for <low> and <high> on tokens with
// precedence lower than that of `BETWEEN`, such as `AND`, `IS`, etc.
let low = self.parse_subexpr(Self::BETWEEN_PREC)?;
self.expect_keyword("AND")?;
let high = self.parse_subexpr(Self::BETWEEN_PREC)?;
Ok(Expr::Between {
expr: Box::new(expr),
negated,
low: Box::new(low),
high: Box::new(high),
})
}
/// Parse a postgresql casting style which is in the form of `expr::datatype`
pub fn parse_pg_cast(&mut self, expr: Expr) -> Result<Expr, ParserError> {
Ok(Expr::Cast {
expr: Box::new(expr),
data_type: self.parse_data_type()?,
})
}
const UNARY_NOT_PREC: u8 = 15;
const BETWEEN_PREC: u8 = 20;
const PLUS_MINUS_PREC: u8 = 30;
/// Get the precedence of the next token
pub fn get_next_precedence(&self) -> Result<u8, ParserError> {
if let Some(token) = self.peek_token() {
debug!("get_next_precedence() {:?}", token);
match &token {
Token::Word(k) if k.keyword == "OR" => Ok(5),
Token::Word(k) if k.keyword == "AND" => Ok(10),
Token::Word(k) if k.keyword == "NOT" => match &self.peek_nth_token(1) {
// The precedence of NOT varies depending on keyword that
// follows it. If it is followed by IN, BETWEEN, or LIKE,
// it takes on the precedence of those tokens. Otherwise it
// is not an infix operator, and therefore has zero
// precedence.
Some(Token::Word(k)) if k.keyword == "IN" => Ok(Self::BETWEEN_PREC),
Some(Token::Word(k)) if k.keyword == "BETWEEN" => Ok(Self::BETWEEN_PREC),
Some(Token::Word(k)) if k.keyword == "LIKE" => Ok(Self::BETWEEN_PREC),
_ => Ok(0),
},
Token::Word(k) if k.keyword == "IS" => Ok(17),
Token::Word(k) if k.keyword == "IN" => Ok(Self::BETWEEN_PREC),
Token::Word(k) if k.keyword == "BETWEEN" => Ok(Self::BETWEEN_PREC),
Token::Word(k) if k.keyword == "LIKE" => Ok(Self::BETWEEN_PREC),
Token::Eq | Token::Lt | Token::LtEq | Token::Neq | Token::Gt | Token::GtEq => {
Ok(20)
}
Token::Plus | Token::Minus => Ok(Self::PLUS_MINUS_PREC),
Token::Mult | Token::Div | Token::Mod => Ok(40),
Token::DoubleColon => Ok(50),
// TODO(jamii) it's not clear what precedence postgres gives to json operators
Token::JsonGet
| Token::JsonGetAsText