-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathsql-parser.y
2458 lines (2261 loc) · 76.2 KB
/
sql-parser.y
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
// Copyright 2012 Cloudera Inc.
//
// 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.
package com.cloudera.impala.analysis;
import com.cloudera.impala.catalog.Type;
import com.cloudera.impala.catalog.ScalarType;
import com.cloudera.impala.catalog.ArrayType;
import com.cloudera.impala.catalog.MapType;
import com.cloudera.impala.catalog.StructType;
import com.cloudera.impala.catalog.StructField;
import com.cloudera.impala.catalog.RowFormat;
import com.cloudera.impala.catalog.View;
import com.cloudera.impala.common.AnalysisException;
import com.cloudera.impala.analysis.ColumnDesc;
import com.cloudera.impala.analysis.UnionStmt.UnionOperand;
import com.cloudera.impala.analysis.UnionStmt.Qualifier;
import com.cloudera.impala.thrift.TFunctionCategory;
import com.cloudera.impala.thrift.TDescribeTableOutputStyle;
import com.cloudera.impala.thrift.THdfsFileFormat;
import com.cloudera.impala.thrift.TPrivilegeLevel;
import com.cloudera.impala.thrift.TTablePropertyType;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java_cup.runtime.Symbol;
import com.google.common.collect.Lists;
parser code {:
private Symbol errorToken_;
// Set if the errorToken_ to be printed in the error message has a different name, e.g.
// when parsing identifiers instead of defined keywords. This is necessary to avoid
// conflicting keywords.
private String expectedTokenName_;
// list of expected tokens ids from current parsing state
// for generating syntax error message
private final List<Integer> expectedTokenIds_ = new ArrayList<Integer>();
// to avoid reporting trivial tokens as expected tokens in error messages
private boolean reportExpectedToken(Integer tokenId, int numExpectedTokens) {
if (SqlScanner.isKeyword(tokenId) ||
tokenId.intValue() == SqlParserSymbols.COMMA ||
tokenId.intValue() == SqlParserSymbols.IDENT) {
return true;
} else {
// if this is the only valid token, always report it
return numExpectedTokens == 1;
}
}
private String getErrorTypeMessage(int lastTokenId) {
String msg = null;
switch (lastTokenId) {
case SqlParserSymbols.UNMATCHED_STRING_LITERAL:
msg = "Unmatched string literal";
break;
case SqlParserSymbols.NUMERIC_OVERFLOW:
msg = "Numeric overflow";
break;
default:
msg = "Syntax error";
break;
}
return msg;
}
// override to save error token
public void syntax_error(java_cup.runtime.Symbol token) {
errorToken_ = token;
// derive expected tokens from current parsing state
expectedTokenIds_.clear();
int state = ((Symbol)stack.peek()).parse_state;
// get row of actions table corresponding to current parsing state
// the row consists of pairs of <tokenId, actionId>
// a pair is stored as row[i] (tokenId) and row[i+1] (actionId)
// the last pair is a special error action
short[] row = action_tab[state];
short tokenId;
// the expected tokens are all the symbols with a
// corresponding action from the current parsing state
for (int i = 0; i < row.length-2; ++i) {
// get tokenId and skip actionId
tokenId = row[i++];
expectedTokenIds_.add(Integer.valueOf(tokenId));
}
}
// override to keep it from calling report_fatal_error()
@Override
public void unrecovered_syntax_error(Symbol cur_token)
throws Exception {
throw new Exception(getErrorTypeMessage(cur_token.sym));
}
/**
* Manually throw a parse error on a given symbol for special circumstances.
*
* @symbolName
* name of symbol on which to fail parsing
* @symbolId
* id of symbol from SqlParserSymbols on which to fail parsing
*/
public void parseError(String symbolName, int symbolId) throws Exception {
parseError(symbolName, symbolId, null);
}
/**
* Same as parseError() above but allows the error token to have a different
* name printed as the expected token.
*/
public void parseError(String symbolName, int symbolId, String expectedTokenName)
throws Exception {
expectedTokenName_ = expectedTokenName;
Symbol errorToken = getSymbolFactory().newSymbol(symbolName, symbolId,
((Symbol) stack.peek()), ((Symbol) stack.peek()), null);
// Call syntax error to gather information about expected tokens, etc.
// syntax_error does not throw an exception
syntax_error(errorToken);
// Unrecovered_syntax_error throws an exception and will terminate parsing
unrecovered_syntax_error(errorToken);
}
// Returns error string, consisting of a shortened offending line
// with a '^' under the offending token. Assumes
// that parse() has been called and threw an exception
public String getErrorMsg(String stmt) {
if (errorToken_ == null || stmt == null) return null;
String[] lines = stmt.split("\n");
StringBuffer result = new StringBuffer();
result.append(getErrorTypeMessage(errorToken_.sym) + " in line ");
result.append(errorToken_.left);
result.append(":\n");
// errorToken_.left is the line number of error.
// errorToken_.right is the column number of the error.
String errorLine = lines[errorToken_.left - 1];
// If the error is that additional tokens are expected past the end,
// errorToken_.right will be past the end of the string.
int lastCharIndex = Math.min(errorLine.length(), errorToken_.right);
int maxPrintLength = 60;
int errorLoc = 0;
if (errorLine.length() <= maxPrintLength) {
// The line is short. Print the entire line.
result.append(errorLine);
result.append('\n');
errorLoc = errorToken_.right;
} else {
// The line is too long. Print maxPrintLength/2 characters before the error and
// after the error.
int contextLength = maxPrintLength / 2 - 3;
String leftSubStr;
if (errorToken_.right > maxPrintLength / 2) {
leftSubStr = "..." + errorLine.substring(errorToken_.right - contextLength,
lastCharIndex);
} else {
leftSubStr = errorLine.substring(0, errorToken_.right);
}
errorLoc = leftSubStr.length();
result.append(leftSubStr);
if (errorLine.length() - errorToken_.right > maxPrintLength / 2) {
result.append(errorLine.substring(errorToken_.right,
errorToken_.right + contextLength) + "...");
} else {
result.append(errorLine.substring(lastCharIndex));
}
result.append("\n");
}
// print error indicator
for (int i = 0; i < errorLoc - 1; ++i) {
result.append(' ');
}
result.append("^\n");
// only report encountered and expected tokens for syntax errors
if (errorToken_.sym == SqlParserSymbols.UNMATCHED_STRING_LITERAL ||
errorToken_.sym == SqlParserSymbols.NUMERIC_OVERFLOW) {
return result.toString();
}
// append last encountered token
result.append("Encountered: ");
String lastToken =
SqlScanner.tokenIdMap.get(Integer.valueOf(errorToken_.sym));
if (lastToken != null) {
result.append(lastToken);
} else {
result.append("Unknown last token with id: " + errorToken_.sym);
}
// append expected tokens
result.append('\n');
result.append("Expected: ");
if (expectedTokenName_ == null) {
String expectedToken = null;
Integer tokenId = null;
for (int i = 0; i < expectedTokenIds_.size(); ++i) {
tokenId = expectedTokenIds_.get(i);
if (reportExpectedToken(tokenId, expectedTokenIds_.size())) {
expectedToken = SqlScanner.tokenIdMap.get(tokenId);
result.append(expectedToken + ", ");
}
}
// remove trailing ", "
result.delete(result.length()-2, result.length());
} else {
result.append(expectedTokenName_);
}
result.append('\n');
return result.toString();
}
:};
// List of keywords. Please keep them sorted alphabetically.
terminal
KW_ADD, KW_AGGREGATE, KW_ALL, KW_ALTER, KW_ANALYTIC, KW_AND, KW_ANTI, KW_API_VERSION,
KW_ARRAY, KW_AS, KW_ASC, KW_AVRO, KW_BETWEEN, KW_BIGINT, KW_BINARY, KW_BOOLEAN, KW_BY,
KW_CACHED, KW_CASE, KW_CAST, KW_CHANGE, KW_CHAR, KW_CLASS, KW_CLOSE_FN, KW_COLUMN,
KW_COLUMNS, KW_COMMENT, KW_COMPUTE, KW_CREATE, KW_CROSS, KW_CURRENT, KW_DATA,
KW_DATABASE, KW_DATABASES, KW_DATE, KW_DATETIME, KW_DECIMAL, KW_DELIMITED, KW_DESC,
KW_DESCRIBE, KW_DISTINCT, KW_DIV, KW_DOUBLE, KW_DROP, KW_ELSE, KW_END, KW_ESCAPED,
KW_EXISTS, KW_EXPLAIN, KW_EXTERNAL, KW_FALSE, KW_FIELDS, KW_FILEFORMAT, KW_FINALIZE_FN,
KW_FIRST, KW_FLOAT, KW_FOLLOWING, KW_FOR, KW_FORMAT, KW_FORMATTED, KW_FROM, KW_FULL,
KW_FUNCTION, KW_FUNCTIONS, KW_GRANT, KW_GROUP, KW_HAVING, KW_IF, KW_IN, KW_INCREMENTAL,
KW_INIT_FN, KW_INNER, KW_INPATH, KW_INSERT, KW_INT, KW_INTERMEDIATE, KW_INTERVAL,
KW_INTO, KW_INVALIDATE, KW_IS, KW_JOIN, KW_LAST, KW_LEFT, KW_LIKE, KW_LIMIT, KW_LINES,
KW_LOAD, KW_LOCATION, KW_MAP, KW_MERGE_FN, KW_METADATA, KW_NOT, KW_NULL, KW_NULLS,
KW_OFFSET, KW_ON, KW_OR, KW_ORDER, KW_OUTER, KW_OVER, KW_OVERWRITE, KW_PARQUET,
KW_PARQUETFILE, KW_PARTITION, KW_PARTITIONED, KW_PARTITIONS, KW_PRECEDING,
KW_PREPARE_FN, KW_PRODUCED, KW_RANGE, KW_RCFILE, KW_REFRESH, KW_REGEXP, KW_RENAME,
KW_REPLACE, KW_RETURNS, KW_REVOKE, KW_RIGHT, KW_RLIKE, KW_ROLE, KW_ROLES, KW_ROW,
KW_ROWS, KW_SCHEMA, KW_SCHEMAS, KW_SELECT, KW_SEMI, KW_SEQUENCEFILE, KW_SERDEPROPERTIES,
KW_SERIALIZE_FN, KW_SET, KW_SHOW, KW_SMALLINT, KW_STORED, KW_STRAIGHT_JOIN,
KW_STRING, KW_STRUCT, KW_SYMBOL, KW_TABLE, KW_TABLES, KW_TBLPROPERTIES, KW_TERMINATED,
KW_TEXTFILE, KW_THEN,
KW_TIMESTAMP, KW_TINYINT, KW_STATS, KW_TO, KW_TRUE, KW_UNBOUNDED, KW_UNCACHED,
KW_UNION, KW_UPDATE_FN, KW_USE, KW_USING,
KW_VALUES, KW_VARCHAR, KW_VIEW, KW_WHEN, KW_WHERE, KW_WITH;
terminal COLON, COMMA, DOT, DOTDOTDOT, STAR, LPAREN, RPAREN, LBRACKET, RBRACKET,
DIVIDE, MOD, ADD, SUBTRACT;
terminal BITAND, BITOR, BITXOR, BITNOT;
terminal EQUAL, NOT, LESSTHAN, GREATERTHAN;
terminal String IDENT;
terminal String EMPTY_IDENT;
terminal String NUMERIC_OVERFLOW;
terminal String COMMENTED_PLAN_HINTS;
terminal BigDecimal INTEGER_LITERAL;
terminal BigDecimal DECIMAL_LITERAL;
terminal String STRING_LITERAL;
terminal String UNMATCHED_STRING_LITERAL;
nonterminal StatementBase stmt;
// Single select statement.
nonterminal SelectStmt select_stmt;
// Single values statement.
nonterminal ValuesStmt values_stmt;
// Select or union statement.
nonterminal QueryStmt query_stmt;
nonterminal QueryStmt opt_query_stmt;
// Single select_stmt or parenthesized query_stmt.
nonterminal QueryStmt union_operand;
// List of select or union blocks connected by UNION operators or a single select block.
nonterminal List<UnionOperand> union_operand_list;
// List of union operands consisting of constant selects.
nonterminal List<UnionOperand> values_operand_list;
// USE stmt
nonterminal UseStmt use_stmt;
nonterminal SetStmt set_stmt;
nonterminal ShowTablesStmt show_tables_stmt;
nonterminal ShowDbsStmt show_dbs_stmt;
nonterminal ShowPartitionsStmt show_partitions_stmt;
nonterminal ShowStatsStmt show_stats_stmt;
nonterminal String show_pattern;
nonterminal DescribeStmt describe_stmt;
nonterminal ShowCreateTableStmt show_create_tbl_stmt;
nonterminal TDescribeTableOutputStyle describe_output_style;
nonterminal LoadDataStmt load_stmt;
nonterminal ResetMetadataStmt reset_metadata_stmt;
// List of select blocks connected by UNION operators, with order by or limit.
nonterminal QueryStmt union_with_order_by_or_limit;
nonterminal SelectList select_clause;
nonterminal SelectList select_list;
nonterminal SelectListItem select_list_item;
nonterminal SelectListItem star_expr;
nonterminal Expr expr, non_pred_expr, arithmetic_expr, timestamp_arithmetic_expr;
nonterminal ArrayList<Expr> expr_list;
nonterminal String alias_clause;
nonterminal ArrayList<String> ident_list;
nonterminal ArrayList<String> opt_ident_list;
nonterminal TableName table_name;
nonterminal FunctionName function_name;
nonterminal Expr where_clause;
nonterminal Predicate predicate, between_predicate, comparison_predicate,
compound_predicate, in_predicate, like_predicate, exists_predicate;
nonterminal ArrayList<Expr> group_by_clause, opt_partition_by_clause;
nonterminal Expr having_clause;
nonterminal ArrayList<OrderByElement> order_by_elements, opt_order_by_clause;
nonterminal OrderByElement order_by_element;
nonterminal Boolean opt_order_param;
nonterminal Boolean opt_nulls_order_param;
nonterminal Expr opt_offset_param;
nonterminal LimitElement opt_limit_offset_clause;
nonterminal Expr opt_limit_clause, opt_offset_clause;
nonterminal Expr cast_expr, case_else_clause, analytic_expr;
nonterminal Expr function_call_expr;
nonterminal AnalyticWindow opt_window_clause;
nonterminal AnalyticWindow.Type window_type;
nonterminal AnalyticWindow.Boundary window_boundary;
nonterminal LiteralExpr literal;
nonterminal CaseExpr case_expr;
nonterminal ArrayList<CaseWhenClause> case_when_clause_list;
nonterminal FunctionParams function_params;
nonterminal SlotRef column_ref;
nonterminal ArrayList<TableRef> from_clause, table_ref_list;
nonterminal WithClause opt_with_clause;
nonterminal ArrayList<View> with_view_def_list;
nonterminal View with_view_def;
nonterminal TableRef table_ref;
nonterminal Subquery subquery;
nonterminal JoinOperator join_operator;
nonterminal opt_inner, opt_outer;
nonterminal ArrayList<String> opt_plan_hints;
nonterminal Type type;
nonterminal Expr sign_chain_expr;
nonterminal InsertStmt insert_stmt;
nonterminal StatementBase explain_stmt;
// Optional partition spec
nonterminal PartitionSpec opt_partition_spec;
// Required partition spec
nonterminal PartitionSpec partition_spec;
nonterminal ArrayList<PartitionKeyValue> partition_clause;
nonterminal ArrayList<PartitionKeyValue> static_partition_key_value_list;
nonterminal ArrayList<PartitionKeyValue> partition_key_value_list;
nonterminal PartitionKeyValue partition_key_value;
nonterminal PartitionKeyValue static_partition_key_value;
nonterminal Qualifier union_op;
nonterminal AlterTableStmt alter_tbl_stmt;
nonterminal StatementBase alter_view_stmt;
nonterminal ComputeStatsStmt compute_stats_stmt;
nonterminal DropDbStmt drop_db_stmt;
nonterminal DropStatsStmt drop_stats_stmt;
nonterminal DropTableOrViewStmt drop_tbl_or_view_stmt;
nonterminal CreateDbStmt create_db_stmt;
nonterminal CreateTableAsSelectStmt create_tbl_as_select_stmt;
nonterminal CreateTableLikeStmt create_tbl_like_stmt;
nonterminal CreateTableLikeFileStmt create_tbl_like_file_stmt;
nonterminal CreateTableStmt create_unpartitioned_tbl_stmt, create_partitioned_tbl_stmt;
nonterminal CreateViewStmt create_view_stmt;
nonterminal CreateDataSrcStmt create_data_src_stmt;
nonterminal DropDataSrcStmt drop_data_src_stmt;
nonterminal ShowDataSrcsStmt show_data_srcs_stmt;
nonterminal StructField struct_field_def;
nonterminal ColumnDesc column_def, view_column_def;
nonterminal ArrayList<ColumnDesc> column_def_list, view_column_def_list;
nonterminal ArrayList<ColumnDesc> partition_column_defs, view_column_defs;
nonterminal ArrayList<StructField> struct_field_def_list;
// Options for DDL commands - CREATE/DROP/ALTER
nonterminal HdfsCachingOp cache_op_val;
nonterminal String comment_val;
nonterminal Boolean external_val;
nonterminal String opt_init_string_val;
nonterminal THdfsFileFormat file_format_val;
nonterminal THdfsFileFormat file_format_create_table_val;
nonterminal Boolean if_exists_val;
nonterminal Boolean if_not_exists_val;
nonterminal Boolean replace_existing_cols_val;
nonterminal HdfsUri location_val;
nonterminal RowFormat row_format_val;
nonterminal String field_terminator_val;
nonterminal String line_terminator_val;
nonterminal String escaped_by_val;
nonterminal String terminator_val;
nonterminal TTablePropertyType table_property_type;
nonterminal HashMap serde_properties;
nonterminal HashMap tbl_properties;
nonterminal HashMap properties_map;
// Used to simplify commands that accept either KW_DATABASE(S) or KW_SCHEMA(S)
nonterminal String db_or_schema_kw;
nonterminal String dbs_or_schemas_kw;
// Used to simplify commands where KW_COLUMN is optional
nonterminal String opt_kw_column;
// Used to simplify commands where KW_TABLE is optional
nonterminal String opt_kw_table;
nonterminal Boolean overwrite_val;
// For GRANT/REVOKE/AUTH DDL statements
nonterminal ShowRolesStmt show_roles_stmt;
nonterminal ShowGrantRoleStmt show_grant_role_stmt;
nonterminal CreateDropRoleStmt create_drop_role_stmt;
nonterminal GrantRevokeRoleStmt grant_role_stmt;
nonterminal GrantRevokeRoleStmt revoke_role_stmt;
nonterminal GrantRevokePrivStmt grant_privilege_stmt;
nonterminal GrantRevokePrivStmt revoke_privilege_stmt;
nonterminal PrivilegeSpec privilege_spec;
nonterminal TPrivilegeLevel privilege;
nonterminal Boolean opt_with_grantopt;
nonterminal Boolean opt_grantopt_for;
nonterminal Boolean opt_kw_role;
// To avoid creating common keywords such as 'SERVER' or 'SOURCES' we treat them as
// identifiers rather than keywords. Throws a parse exception if the identifier does not
// match the expected string.
nonterminal Boolean source_ident;
nonterminal Boolean sources_ident;
nonterminal Boolean server_ident;
nonterminal Boolean uri_ident;
nonterminal Boolean option_ident;
// For Create/Drop/Show function ddl
nonterminal FunctionArgs function_def_args;
nonterminal FunctionArgs function_def_arg_list;
nonterminal Boolean opt_is_aggregate_fn;
nonterminal Boolean opt_is_varargs;
nonterminal Type opt_aggregate_fn_intermediate_type;
nonterminal CreateUdfStmt create_udf_stmt;
nonterminal CreateUdaStmt create_uda_stmt;
nonterminal ShowFunctionsStmt show_functions_stmt;
nonterminal DropFunctionStmt drop_function_stmt;
nonterminal TFunctionCategory opt_function_category;
// Accepts space separated key='v' arguments.
nonterminal HashMap create_function_args_map;
nonterminal CreateFunctionStmtBase.OptArg create_function_arg_key;
precedence left KW_OR;
precedence left KW_AND;
precedence right KW_NOT, NOT;
precedence left KW_BETWEEN, KW_IN, KW_IS, KW_EXISTS;
precedence left KW_LIKE, KW_RLIKE, KW_REGEXP;
precedence left EQUAL, LESSTHAN, GREATERTHAN;
precedence left ADD, SUBTRACT;
precedence left STAR, DIVIDE, MOD, KW_DIV;
precedence left BITAND, BITOR, BITXOR, BITNOT;
precedence left KW_ORDER, KW_BY, KW_LIMIT;
precedence left LPAREN, RPAREN;
// Support chaining of timestamp arithmetic exprs.
precedence left KW_INTERVAL;
// These tokens need to be at the end for create_function_args_map to accept
// no keys. Otherwise, the grammar has shift/reduce conflicts.
precedence left KW_COMMENT;
precedence left KW_SYMBOL;
precedence left KW_PREPARE_FN;
precedence left KW_CLOSE_FN;
precedence left KW_UPDATE_FN;
precedence left KW_FINALIZE_FN;
precedence left KW_INIT_FN;
precedence left KW_MERGE_FN;
precedence left KW_SERIALIZE_FN;
precedence left KW_OVER;
start with stmt;
stmt ::=
query_stmt:query
{: RESULT = query; :}
| insert_stmt:insert
{: RESULT = insert; :}
| use_stmt:use
{: RESULT = use; :}
| show_tables_stmt:show_tables
{: RESULT = show_tables; :}
| show_dbs_stmt:show_dbs
{: RESULT = show_dbs; :}
| show_partitions_stmt:show_partitions
{: RESULT = show_partitions; :}
| show_stats_stmt:show_stats
{: RESULT = show_stats; :}
| show_functions_stmt:show_functions
{: RESULT = show_functions; :}
| show_data_srcs_stmt:show_data_srcs
{: RESULT = show_data_srcs; :}
| show_create_tbl_stmt:show_create_tbl
{: RESULT = show_create_tbl; :}
| describe_stmt:describe
{: RESULT = describe; :}
| alter_tbl_stmt:alter_tbl
{: RESULT = alter_tbl; :}
| alter_view_stmt:alter_view
{: RESULT = alter_view; :}
| compute_stats_stmt:compute_stats
{: RESULT = compute_stats; :}
| drop_stats_stmt:drop_stats
{: RESULT = drop_stats; :}
| create_tbl_as_select_stmt:create_tbl_as_select
{: RESULT = create_tbl_as_select; :}
| create_tbl_like_stmt:create_tbl_like
{: RESULT = create_tbl_like; :}
| create_tbl_like_file_stmt:create_tbl_like_file
{: RESULT = create_tbl_like_file; :}
| create_unpartitioned_tbl_stmt:create_tbl
{: RESULT = create_tbl; :}
| create_partitioned_tbl_stmt:create_tbl
{: RESULT = create_tbl; :}
| create_view_stmt:create_view
{: RESULT = create_view; :}
| create_data_src_stmt:create_data_src
{: RESULT = create_data_src; :}
| create_db_stmt:create_db
{: RESULT = create_db; :}
| create_udf_stmt:create_udf
{: RESULT = create_udf; :}
| create_uda_stmt:create_uda
{: RESULT = create_uda; :}
| drop_db_stmt:drop_db
{: RESULT = drop_db; :}
| drop_tbl_or_view_stmt:drop_tbl
{: RESULT = drop_tbl; :}
| drop_function_stmt:drop_function
{: RESULT = drop_function; :}
| drop_data_src_stmt:drop_data_src
{: RESULT = drop_data_src; :}
| explain_stmt:explain
{: RESULT = explain; :}
| load_stmt: load
{: RESULT = load; :}
| reset_metadata_stmt: reset_metadata
{: RESULT = reset_metadata; :}
| set_stmt:set
{: RESULT = set; :}
| show_roles_stmt:show_roles
{: RESULT = show_roles; :}
| show_grant_role_stmt:show_grant_role
{: RESULT = show_grant_role; :}
| create_drop_role_stmt:create_drop_role
{: RESULT = create_drop_role; :}
| grant_role_stmt:grant_role
{: RESULT = grant_role; :}
| revoke_role_stmt:revoke_role
{: RESULT = revoke_role; :}
| grant_privilege_stmt:grant_privilege
{: RESULT = grant_privilege; :}
| revoke_privilege_stmt:revoke_privilege
{: RESULT = revoke_privilege; :}
;
load_stmt ::=
KW_LOAD KW_DATA KW_INPATH STRING_LITERAL:path overwrite_val:overwrite KW_INTO KW_TABLE
table_name:table opt_partition_spec:partition
{: RESULT = new LoadDataStmt(table, new HdfsUri(path), overwrite, partition); :}
;
overwrite_val ::=
KW_OVERWRITE
{: RESULT = Boolean.TRUE; :}
| /* empty */
{: RESULT = Boolean.FALSE; :}
;
reset_metadata_stmt ::=
KW_INVALIDATE KW_METADATA
{: RESULT = new ResetMetadataStmt(null, false); :}
| KW_INVALIDATE KW_METADATA table_name:table
{: RESULT = new ResetMetadataStmt(table, false); :}
| KW_REFRESH table_name:table
{: RESULT = new ResetMetadataStmt(table, true); :}
;
explain_stmt ::=
KW_EXPLAIN query_stmt:query
{:
query.setIsExplain();
RESULT = query;
:}
| KW_EXPLAIN insert_stmt:insert
{:
insert.setIsExplain();
RESULT = insert;
:}
| KW_EXPLAIN create_tbl_as_select_stmt:ctas_stmt
{:
ctas_stmt.setIsExplain();
RESULT = ctas_stmt;
:}
;
// Insert statements have two optional clauses: the column permutation (INSERT into
// tbl(col1,...) etc) and the PARTITION clause. If the column permutation is present, the
// query statement clause is optional as well.
insert_stmt ::=
opt_with_clause:w KW_INSERT KW_OVERWRITE opt_kw_table table_name:table LPAREN
opt_ident_list:col_perm RPAREN partition_clause:list opt_plan_hints:hints
opt_query_stmt:query
{: RESULT = new InsertStmt(w, table, true, list, hints, query, col_perm); :}
| opt_with_clause:w KW_INSERT KW_OVERWRITE opt_kw_table table_name:table
partition_clause:list opt_plan_hints:hints query_stmt:query
{: RESULT = new InsertStmt(w, table, true, list, hints, query, null); :}
| opt_with_clause:w KW_INSERT KW_INTO opt_kw_table table_name:table LPAREN
opt_ident_list:col_perm RPAREN partition_clause:list opt_plan_hints:hints
opt_query_stmt:query
{: RESULT = new InsertStmt(w, table, false, list, hints, query, col_perm); :}
| opt_with_clause:w KW_INSERT KW_INTO opt_kw_table table_name:table
partition_clause:list opt_plan_hints:hints query_stmt:query
{: RESULT = new InsertStmt(w, table, false, list, hints, query, null); :}
;
opt_query_stmt ::=
query_stmt:query
{: RESULT = query; :}
| /* empty */
{: RESULT = null; :}
;
opt_ident_list ::=
ident_list:ident
{: RESULT = ident; :}
| /* empty */
{: RESULT = Lists.newArrayList(); :}
;
opt_kw_table ::=
KW_TABLE
| /* empty */
;
show_roles_stmt ::=
KW_SHOW KW_ROLES
{: RESULT = new ShowRolesStmt(false, null); :}
| KW_SHOW KW_ROLE KW_GRANT KW_GROUP IDENT:group
{: RESULT = new ShowRolesStmt(false, group); :}
| KW_SHOW KW_CURRENT KW_ROLES
{: RESULT = new ShowRolesStmt(true, null); :}
;
show_grant_role_stmt ::=
KW_SHOW KW_GRANT KW_ROLE IDENT:role
{: RESULT = new ShowGrantRoleStmt(role, null); :}
| KW_SHOW KW_GRANT KW_ROLE IDENT:role KW_ON server_ident:server_kw
{:
RESULT = new ShowGrantRoleStmt(role,
PrivilegeSpec.createServerScopedPriv(TPrivilegeLevel.ALL));
:}
| KW_SHOW KW_GRANT KW_ROLE IDENT:role KW_ON KW_DATABASE IDENT:db_name
{:
RESULT = new ShowGrantRoleStmt(role,
PrivilegeSpec.createDbScopedPriv(TPrivilegeLevel.ALL, db_name));
:}
| KW_SHOW KW_GRANT KW_ROLE IDENT:role KW_ON KW_TABLE table_name:tbl_name
{:
RESULT = new ShowGrantRoleStmt(role,
PrivilegeSpec.createTableScopedPriv(TPrivilegeLevel.ALL, tbl_name));
:}
| KW_SHOW KW_GRANT KW_ROLE IDENT:role KW_ON uri_ident:uri_kw STRING_LITERAL:uri
{:
RESULT = new ShowGrantRoleStmt(role,
PrivilegeSpec.createUriScopedPriv(TPrivilegeLevel.ALL, new HdfsUri(uri)));
:}
;
create_drop_role_stmt ::=
KW_CREATE KW_ROLE IDENT:role
{: RESULT = new CreateDropRoleStmt(role, false); :}
| KW_DROP KW_ROLE IDENT:role
{: RESULT = new CreateDropRoleStmt(role, true); :}
;
grant_role_stmt ::=
KW_GRANT KW_ROLE IDENT:role KW_TO KW_GROUP IDENT:group
{: RESULT = new GrantRevokeRoleStmt(role, group, true); :}
;
revoke_role_stmt ::=
KW_REVOKE KW_ROLE IDENT:role KW_FROM KW_GROUP IDENT:group
{: RESULT = new GrantRevokeRoleStmt(role, group, false); :}
;
grant_privilege_stmt ::=
KW_GRANT privilege_spec:priv KW_TO opt_kw_role:opt_role IDENT:role
opt_with_grantopt:grant_opt
{: RESULT = new GrantRevokePrivStmt(role, priv, true, grant_opt); :}
;
revoke_privilege_stmt ::=
KW_REVOKE opt_grantopt_for:grant_opt privilege_spec:priv KW_FROM
opt_kw_role:opt_role IDENT:role
{: RESULT = new GrantRevokePrivStmt(role, priv, false, grant_opt); :}
;
privilege_spec ::=
privilege:priv KW_ON server_ident:server_kw
{: RESULT = PrivilegeSpec.createServerScopedPriv(priv); :}
| privilege:priv KW_ON KW_DATABASE IDENT:db_name
{: RESULT = PrivilegeSpec.createDbScopedPriv(priv, db_name); :}
| privilege:priv KW_ON KW_TABLE table_name:tbl_name
{: RESULT = PrivilegeSpec.createTableScopedPriv(priv, tbl_name); :}
| privilege:priv KW_ON uri_ident:uri_kw STRING_LITERAL:uri
{: RESULT = PrivilegeSpec.createUriScopedPriv(priv, new HdfsUri(uri)); :}
;
privilege ::=
KW_SELECT
{: RESULT = TPrivilegeLevel.SELECT; :}
| KW_INSERT
{: RESULT = TPrivilegeLevel.INSERT; :}
| KW_ALL
{: RESULT = TPrivilegeLevel.ALL; :}
;
opt_grantopt_for ::=
KW_GRANT option_ident:option KW_FOR
{: RESULT = true; :}
| /* empty */
{: RESULT = false; :}
;
opt_with_grantopt ::=
KW_WITH KW_GRANT option_ident:option
{: RESULT = true; :}
| /* empty */
{: RESULT = false; :}
;
opt_kw_role ::=
KW_ROLE
| /* empty */
;
alter_tbl_stmt ::=
KW_ALTER KW_TABLE table_name:table replace_existing_cols_val:replace KW_COLUMNS
LPAREN column_def_list:col_defs RPAREN
{: RESULT = new AlterTableAddReplaceColsStmt(table, col_defs, replace); :}
| KW_ALTER KW_TABLE table_name:table KW_ADD if_not_exists_val:if_not_exists
partition_spec:partition location_val:location cache_op_val:cache_op
{:
RESULT = new AlterTableAddPartitionStmt(table, partition,
location, if_not_exists, cache_op);
:}
| KW_ALTER KW_TABLE table_name:table KW_DROP opt_kw_column IDENT:col_name
{: RESULT = new AlterTableDropColStmt(table, col_name); :}
| KW_ALTER KW_TABLE table_name:table KW_CHANGE opt_kw_column IDENT:col_name
column_def:col_def
{: RESULT = new AlterTableChangeColStmt(table, col_name, col_def); :}
| KW_ALTER KW_TABLE table_name:table KW_DROP if_exists_val:if_exists
partition_spec:partition
{: RESULT = new AlterTableDropPartitionStmt(table, partition, if_exists); :}
| KW_ALTER KW_TABLE table_name:table opt_partition_spec:partition KW_SET KW_FILEFORMAT
file_format_val:file_format
{: RESULT = new AlterTableSetFileFormatStmt(table, partition, file_format); :}
| KW_ALTER KW_TABLE table_name:table opt_partition_spec:partition KW_SET
KW_LOCATION STRING_LITERAL:location
{: RESULT = new AlterTableSetLocationStmt(table, partition, new HdfsUri(location)); :}
| KW_ALTER KW_TABLE table_name:table KW_RENAME KW_TO table_name:new_table
{: RESULT = new AlterTableOrViewRenameStmt(table, new_table, true); :}
| KW_ALTER KW_TABLE table_name:table opt_partition_spec:partition KW_SET
table_property_type:target LPAREN properties_map:properties RPAREN
{: RESULT = new AlterTableSetTblProperties(table, partition, target, properties); :}
| KW_ALTER KW_TABLE table_name:table opt_partition_spec:partition KW_SET
cache_op_val:cache_op
{:
// Ensure a parser error is thrown for ALTER statements if no cache op is specified.
if (cache_op == null) {
parser.parseError("set", SqlParserSymbols.KW_SET);
}
RESULT = new AlterTableSetCachedStmt(table, partition, cache_op);
:}
;
table_property_type ::=
KW_TBLPROPERTIES
{: RESULT = TTablePropertyType.TBL_PROPERTY; :}
| KW_SERDEPROPERTIES
{: RESULT = TTablePropertyType.SERDE_PROPERTY; :}
;
opt_kw_column ::=
KW_COLUMN
| /* empty */
;
replace_existing_cols_val ::=
KW_REPLACE
{: RESULT = true; :}
| KW_ADD
{: RESULT = false; :}
;
create_db_stmt ::=
KW_CREATE db_or_schema_kw if_not_exists_val:if_not_exists IDENT:db_name
comment_val:comment location_val:location
{: RESULT = new CreateDbStmt(db_name, comment, location, if_not_exists); :}
;
create_tbl_like_stmt ::=
KW_CREATE external_val:external KW_TABLE if_not_exists_val:if_not_exists
table_name:table KW_LIKE table_name:other_table comment_val:comment
KW_STORED KW_AS file_format_val:file_format location_val:location
{:
RESULT = new CreateTableLikeStmt(table, other_table, external, comment,
file_format, location, if_not_exists);
:}
| KW_CREATE external_val:external KW_TABLE if_not_exists_val:if_not_exists
table_name:table KW_LIKE table_name:other_table comment_val:comment
location_val:location
{:
RESULT = new CreateTableLikeStmt(table, other_table, external, comment,
null, location, if_not_exists);
:}
;
create_tbl_like_file_stmt ::=
KW_CREATE external_val:external KW_TABLE if_not_exists_val:if_not_exists
table_name:table KW_LIKE file_format_val:schema_file_format
STRING_LITERAL:schema_location partition_column_defs:partition_col_defs
comment_val:comment row_format_val:row_format serde_properties:serde_props
file_format_create_table_val:file_format location_val:location cache_op_val:cache_op
tbl_properties:tbl_props
{:
RESULT = new CreateTableLikeFileStmt(table, schema_file_format,
new HdfsUri(schema_location), partition_col_defs, external, comment, row_format,
file_format, location, cache_op, if_not_exists, tbl_props, serde_props);
:}
;
create_tbl_as_select_stmt ::=
KW_CREATE external_val:external KW_TABLE if_not_exists_val:if_not_exists
table_name:table comment_val:comment row_format_val:row_format
serde_properties:serde_props file_format_create_table_val:file_format
location_val:location cache_op_val:cache_op tbl_properties:tbl_props
KW_AS query_stmt:query
{:
// Initialize with empty List of columns and partition columns. The
// columns will be added from the query statement during analysis
CreateTableStmt create_stmt = new CreateTableStmt(table, new ArrayList<ColumnDesc>(),
new ArrayList<ColumnDesc>(), external, comment, row_format,
file_format, location, cache_op, if_not_exists, tbl_props, serde_props);
RESULT = new CreateTableAsSelectStmt(create_stmt, query);
:}
;
// Create unpartitioned tables with and without column definitions.
// We cannot coalesce this production with create_partitioned_tbl_stmt because
// that results in an unresolvable reduce/reduce conflict due to the many
// optional clauses (not clear which rule to reduce on 'empty').
// TODO: Clean up by consolidating everything after the column defs and
// partition clause into a CreateTableParams.
create_unpartitioned_tbl_stmt ::=
KW_CREATE external_val:external KW_TABLE if_not_exists_val:if_not_exists
table_name:table LPAREN column_def_list:col_defs RPAREN comment_val:comment
row_format_val:row_format serde_properties:serde_props
file_format_create_table_val:file_format location_val:location cache_op_val:cache_op
tbl_properties:tbl_props
{:
RESULT = new CreateTableStmt(table, col_defs, new ArrayList<ColumnDesc>(), external,
comment, row_format, file_format, location, cache_op, if_not_exists, tbl_props,
serde_props);
:}
| KW_CREATE external_val:external KW_TABLE if_not_exists_val:if_not_exists
table_name:table comment_val:comment row_format_val:row_format
serde_properties:serde_props file_format_create_table_val:file_format
location_val:location cache_op_val:cache_op tbl_properties:tbl_props
{:
RESULT = new CreateTableStmt(table, new ArrayList<ColumnDesc>(),
new ArrayList<ColumnDesc>(), external, comment, row_format, file_format,
location, cache_op, if_not_exists, tbl_props, serde_props);
:}
| KW_CREATE external_val:external KW_TABLE if_not_exists_val:if_not_exists
table_name:table LPAREN column_def_list:col_defs RPAREN
KW_PRODUCED KW_BY KW_DATA source_ident:is_source_id IDENT:data_src_name
opt_init_string_val:init_string comment_val:comment
{:
// Need external_val in the grammar to avoid shift/reduce conflict with other
// CREATE TABLE statements.
if (external) parser.parseError("external", SqlParserSymbols.KW_EXTERNAL);
RESULT = new CreateTableDataSrcStmt(table, col_defs, data_src_name, init_string,
comment, if_not_exists);
:}
;
// Create partitioned tables with and without column definitions.
// TODO: Clean up by consolidating everything after the column defs and
// partition clause into a CreateTableParams.
create_partitioned_tbl_stmt ::=
KW_CREATE external_val:external KW_TABLE if_not_exists_val:if_not_exists
table_name:table LPAREN column_def_list:col_defs RPAREN KW_PARTITIONED KW_BY
LPAREN column_def_list:partition_col_defs RPAREN comment_val:comment
row_format_val:row_format serde_properties:serde_props
file_format_create_table_val:file_format location_val:location cache_op_val:cache_op
tbl_properties:tbl_props
{:
RESULT = new CreateTableStmt(table, col_defs, partition_col_defs, external, comment,
row_format, file_format, location, cache_op, if_not_exists, tbl_props,
serde_props);
:}
| KW_CREATE external_val:external KW_TABLE if_not_exists_val:if_not_exists
table_name:table KW_PARTITIONED KW_BY
LPAREN column_def_list:partition_col_defs RPAREN
comment_val:comment row_format_val:row_format serde_properties:serde_props
file_format_create_table_val:file_format location_val:location cache_op_val:cache_op
tbl_properties:tbl_props
{:
RESULT = new CreateTableStmt(table, new ArrayList<ColumnDesc>(), partition_col_defs,
external, comment, row_format, file_format, location, cache_op, if_not_exists,
tbl_props, serde_props);
:}
;
create_udf_stmt ::=
KW_CREATE KW_FUNCTION if_not_exists_val:if_not_exists
function_name:fn_name function_def_args:fn_args
KW_RETURNS type:return_type
KW_LOCATION STRING_LITERAL:binary_path
create_function_args_map:arg_map
{:
RESULT = new CreateUdfStmt(fn_name, fn_args, return_type, new HdfsUri(binary_path),
if_not_exists, arg_map);
:}
;
create_uda_stmt ::=
KW_CREATE KW_AGGREGATE KW_FUNCTION if_not_exists_val:if_not_exists
function_name:fn_name function_def_args:fn_args
KW_RETURNS type:return_type
opt_aggregate_fn_intermediate_type:intermediate_type
KW_LOCATION STRING_LITERAL:binary_path
create_function_args_map:arg_map
{:
RESULT = new CreateUdaStmt(fn_name, fn_args, return_type, intermediate_type,
new HdfsUri(binary_path), if_not_exists, arg_map);
:}
;
cache_op_val ::=
KW_CACHED KW_IN STRING_LITERAL:pool_name
{: RESULT = new HdfsCachingOp(pool_name); :}
| KW_UNCACHED
{: RESULT = new HdfsCachingOp(); :}
| /* empty */
{: RESULT = null; :}
;
comment_val ::=
KW_COMMENT STRING_LITERAL:comment
{: RESULT = comment; :}
| /* empty */
{: RESULT = null; :}
;
location_val ::=
KW_LOCATION STRING_LITERAL:location
{: RESULT = new HdfsUri(location); :}
| /* empty */
{: RESULT = null; :}
;
opt_init_string_val ::=
LPAREN STRING_LITERAL:init_string RPAREN
{: RESULT = init_string; :}
| /* empty */
{: RESULT = null; :}
;
external_val ::=
KW_EXTERNAL
{: RESULT = true; :}
|
{: RESULT = false; :}
;
if_not_exists_val ::=
KW_IF KW_NOT KW_EXISTS
{: RESULT = true; :}
|
{: RESULT = false; :}
;
row_format_val ::=
KW_ROW KW_FORMAT KW_DELIMITED field_terminator_val:field_terminator
escaped_by_val:escaped_by line_terminator_val:line_terminator
{: RESULT = new RowFormat(field_terminator, line_terminator, escaped_by); :}
|/* empty */
{: RESULT = RowFormat.DEFAULT_ROW_FORMAT; :}
;
escaped_by_val ::=
KW_ESCAPED KW_BY STRING_LITERAL:escaped_by
{: RESULT = escaped_by; :}
| /* empty */
{: RESULT = null; :}
;
line_terminator_val ::=