forked from jackc/sqlfmt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql.y
3474 lines (3189 loc) · 74.7 KB
/
sql.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
%{
package sqlfmt
%}
%union {
sqlSelect *SelectStmt
simpleSelect *SimpleSelect
fields []Expr
expr Expr
str string
identifiers []string
anyNames []AnyName
intoClause *IntoClause
fromClause *FromClause
whereClause *WhereClause
orderExpr OrderExpr
orderClause *OrderClause
groupByClause *GroupByClause
limitClause *LimitClause
lockingClause *LockingClause
lockingItem LockingItem
boolean bool
placeholder interface{}
columnRef ColumnRef
whenClauses []WhenClause
whenClause WhenClause
pgType PgType
pgTypes []PgType
row Row
valuesRow ValuesRow
valuesClause ValuesClause
funcApplication FuncApplication
funcArgs []FuncArg
funcArg FuncArg
withinGroupClause *WithinGroupClause
filterClause *FilterClause
relationExpr *RelationExpr
windowDefinitions []WindowDefinition
windowDefinition WindowDefinition
windowSpecification WindowSpecification
overClause *OverClause
partitionClause PartitionClause
frameClause *FrameClause
frameBound *FrameBound
arrayExpr ArrayExpr
anyName AnyName
indirectionEl IndirectionEl
indirection Indirection
iconst IntegerConst
optArrayBounds []IntegerConst
optInterval *OptInterval
intervalSecond *IntervalSecond
subqueryOp SubqueryOp
extractList *ExtractList
overlayList OverlayList
positionList *PositionList
substrList SubstrList
trimList TrimList
xmlAttributes XmlAttributes
xmlAttributeEls []XmlAttributeEl
xmlAttributeEl XmlAttributeEl
xmlExistsArgument XmlExistsArgument
xmlRootVersion XmlRootVersion
}
%type <sqlSelect> top
%type <sqlSelect> SelectStmt
%type <sqlSelect> select_no_parens
%type <sqlSelect> select_with_parens select_clause
%type <simpleSelect> simple_select
%type <valuesClause> values_clause
%type <fields> opt_target_list target_list distinct_clause expr_list
%type <placeholder> opt_all_clause
%type <expr> aliasableExpr
%type <expr> target_el a_expr b_expr c_expr
%type <fromClause> from_clause
%type <identifiers> identifierSeq
%type <expr> joinExpr
%type <intoClause> OptTempTableName into_clause
%type <boolean> opt_table
%type <whereClause> where_clause
%type <orderExpr> sortby
%type <orderClause> opt_sort_clause sort_clause sortby_list
%type <str> opt_asc_desc opt_nulls_order opt_charset
%type <placeholder> row_or_rows
first_or_next
opt_asymmetric
%type <fields> opt_type_modifiers
%type <withinGroupClause> within_group_clause
%type <filterClause> filter_clause
%type <relationExpr> relation_expr
%type <extractList> extract_list
%type <expr> extract_arg
%type <overlayList> overlay_list
%type <expr> overlay_placing substr_from substr_for
%type <positionList> position_list
%type <placeholder> substr_list
%type <trimList> trim_list
%type <limitClause> select_limit opt_select_limit
%type <expr>
limit_clause
offset_clause
select_limit_value
select_offset_value
opt_select_fetch_first_value
select_offset_value2
%type <lockingClause> opt_for_locking_clause for_locking_clause for_locking_items
%type <lockingItem> for_locking_item
%type <str> for_locking_strength opt_nowait_or_skip
%type <anyNames> qualified_name_list locked_rels_list
%type <indirectionEl> indirection_el
%type <indirection> indirection opt_indirection
%type <str> attr_name ColId param_name
%type <anyName> qualified_name
%type <str> MathOp all_Op sub_type
%type <anyName> qual_Op qual_all_Op
%type <groupByClause> group_clause
%type <fields> group_by_list
%type <expr> group_by_item
%type <expr> in_expr
%type <expr> having_clause
%type <boolean> all_or_distinct opt_varying opt_timezone
%type <expr> SignedIconst Sconst AexprConst
%type <iconst> Iconst opt_float
%type <expr> case_expr case_arg case_default
%type <whenClauses> when_clause_list
%type <whenClause> when_clause
%type <expr> ctext_expr
%type <valuesRow> ctext_expr_list ctext_row
%type <row> row explicit_row implicit_row
%type <funcApplication> func_application
%type <funcArgs> func_arg_list
%type <funcArg> func_arg_expr
%type <expr> func_expr func_expr_common_subexpr
%type <windowDefinitions> window_definition_list window_clause
%type <windowDefinition> window_definition
%type <windowSpecification> window_specification
%type <overClause> over_clause
%type <str> opt_existing_window_name
%type <partitionClause> opt_partition_clause
%type <frameClause> opt_frame_clause frame_extent
%type <frameBound> frame_bound
%type <optInterval> opt_interval
%type <intervalSecond> interval_second
%type <arrayExpr> array_expr array_expr_list
%type <columnRef> columnref
%type <anyName> any_name attrs any_operator
%type <subqueryOp> subquery_Op
%type <xmlAttributes> xml_attributes
%type <xmlAttributeEls> xml_attribute_list
%type <xmlAttributeEl> xml_attribute_el
%type <xmlExistsArgument> xmlexists_argument
%type <str> document_or_content xml_whitespace_option
%type <xmlRootVersion> xml_root_version
%type <str> opt_xml_root_standalone
%type <str>
ColLabel
unreserved_keyword
col_name_keyword
type_function_name
type_func_name_keyword
reserved_keyword
%type <anyName> func_name
%type <pgType>
GenericType
Numeric
Typename
SimpleTypename
Character
CharacterWithLength
CharacterWithoutLength
character
BitWithLength
BitWithoutLength
Bit
ConstTypename
ConstBit
ConstCharacter
ConstDatetime
%type <pgTypes> type_list
%type <optArrayBounds> opt_array_bounds
/*
* Non-keyword token types. These are hard-wired into the "flex" lexer.
* They must be listed first so that their numeric codes do not depend on
* the set of keywords. PL/pgsql depends on this so that it can share the
* same lexer. If you add/change tokens here, fix PL/pgsql to match!
*
* DOT_DOT is unused in the core SQL grammar, and so will always provoke
* parse errors. It is needed by PL/pgsql.
*/
%token <str> IDENT FCONST SCONST BCONST XCONST Op
/* ival in PostgreSQL */
%token <str> ICONST PARAM
%token TYPECAST DOT_DOT COLON_EQUALS EQUALS_GREATER
%token LESS_EQUALS GREATER_EQUALS NOT_EQUALS
/* ordinary key words in alphabetical order */
%token <str> ABORT_P ABSOLUTE_P ACCESS ACTION ADD_P ADMIN AFTER
AGGREGATE ALL ALSO ALTER ALWAYS ANALYSE ANALYZE AND ANY ARRAY AS ASC
ASSERTION ASSIGNMENT ASYMMETRIC AT ATTRIBUTE AUTHORIZATION
BACKWARD BEFORE BEGIN_P BETWEEN BIGINT BINARY BIT
BOOLEAN_P BOTH BY
CACHE CALLED CASCADE CASCADED CASE CAST CATALOG_P CHAIN CHAR_P
CHARACTER CHARACTERISTICS CHECK CHECKPOINT CLASS CLOSE
CLUSTER COALESCE COLLATE COLLATION COLUMN COMMENT COMMENTS COMMIT
COMMITTED CONCURRENTLY CONFIGURATION CONFLICT CONNECTION CONSTRAINT
CONSTRAINTS CONTENT_P CONTINUE_P CONVERSION_P COPY COST CREATE
CROSS CSV CUBE CURRENT_P
CURRENT_CATALOG CURRENT_DATE CURRENT_ROLE CURRENT_SCHEMA
CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURSOR CYCLE
DATA_P DATABASE DAY_P DEALLOCATE DEC DECIMAL_P DECLARE DEFAULT DEFAULTS
DEFERRABLE DEFERRED DEFINER DELETE_P DELIMITER DELIMITERS DESC
DICTIONARY DISABLE_P DISCARD DISTINCT DO DOCUMENT_P DOMAIN_P DOUBLE_P DROP
EACH ELSE ENABLE_P ENCODING ENCRYPTED END_P ENUM_P ESCAPE EVENT EXCEPT
EXCLUDE EXCLUDING EXCLUSIVE EXECUTE EXISTS EXPLAIN
EXTENSION EXTERNAL EXTRACT
FALSE_P FAMILY FETCH FILTER FIRST_P FLOAT_P FOLLOWING FOR
FORCE FOREIGN FORWARD FREEZE FROM FULL FUNCTION FUNCTIONS
GLOBAL GRANT GRANTED GREATEST GROUP_P GROUPING
HANDLER HAVING HEADER_P HOLD HOUR_P
IDENTITY_P IF_P ILIKE IMMEDIATE IMMUTABLE IMPLICIT_P IMPORT_P IN_P
INCLUDING INCREMENT INDEX INDEXES INHERIT INHERITS INITIALLY INLINE_P
INNER_P INOUT INPUT_P INSENSITIVE INSERT INSTEAD INT_P INTEGER
INTERSECT INTERVAL INTO INVOKER IS ISNULL ISOLATION
JOIN
KEY
LABEL LANGUAGE LARGE_P LAST_P LATERAL_P
LEADING LEAKPROOF LEAST LEFT LEVEL LIKE LIMIT LISTEN LOAD LOCAL
LOCALTIME LOCALTIMESTAMP LOCATION LOCK_P LOCKED LOGGED
MAPPING MATCH MATERIALIZED MAXVALUE MINUTE_P MINVALUE MODE MONTH_P MOVE
NAME_P NAMES NATIONAL NATURAL NCHAR NEXT NO NONE
NOT NOTHING NOTIFY NOTNULL NOWAIT NULL_P NULLIF
NULLS_P NUMERIC
OBJECT_P OF OFF OFFSET OIDS ON ONLY OPERATOR OPTION OPTIONS OR
ORDER ORDINALITY OUT_P OUTER_P OVER OVERLAPS OVERLAY OWNED OWNER
PARSER PARTIAL PARTITION PASSING PASSWORD PLACING PLANS POLICY POSITION
PRECEDING PRECISION PRESERVE PREPARE PREPARED PRIMARY
PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROGRAM
QUOTE
RANGE READ REAL REASSIGN RECHECK RECURSIVE REF REFERENCES REFRESH REINDEX
RELATIVE_P RELEASE RENAME REPEATABLE REPLACE REPLICA
RESET RESTART RESTRICT RETURNING RETURNS REVOKE RIGHT ROLE ROLLBACK ROLLUP
ROW ROWS RULE
SAVEPOINT SCHEMA SCROLL SEARCH SECOND_P SECURITY SELECT SEQUENCE SEQUENCES
SERIALIZABLE SERVER SESSION SESSION_USER SET SETS SETOF SHARE SHOW
SIMILAR SIMPLE SKIP SMALLINT SNAPSHOT SOME SQL_P STABLE STANDALONE_P START
STATEMENT STATISTICS STDIN STDOUT STORAGE STRICT_P STRIP_P SUBSTRING
SYMMETRIC SYSID SYSTEM_P
TABLE TABLES TABLESAMPLE TABLESPACE TEMP TEMPLATE TEMPORARY TEXT_P THEN
TIME TIMESTAMP TO TRAILING TRANSACTION TRANSFORM TREAT TRIGGER TRIM TRUE_P
TRUNCATE TRUSTED TYPE_P TYPES_P
UNBOUNDED UNCOMMITTED UNENCRYPTED UNION UNIQUE UNKNOWN UNLISTEN UNLOGGED
UNTIL UPDATE USER USING
VACUUM VALID VALIDATE VALIDATOR VALUE_P VALUES VARCHAR VARIADIC VARYING
VERBOSE VERSION_P VIEW VIEWS VOLATILE
WHEN WHERE WHITESPACE_P WINDOW WITH WITHIN WITHOUT WORK WRAPPER WRITE
XML_P XMLATTRIBUTES XMLCONCAT XMLELEMENT XMLEXISTS XMLFOREST XMLPARSE
XMLPI XMLROOT XMLSERIALIZE
YEAR_P YES_P
ZONE
/*
* The grammar thinks these are keywords, but they are not in the kwlist.h
* list and so can never be entered directly. The filter in parser.c
* creates these tokens when required (based on looking one token ahead).
*
* NOT_LA exists so that productions such as NOT LIKE can be given the same
* precedence as LIKE; otherwise they'd effectively have the same precedence
* as NOT, at least with respect to their left-hand subexpression.
* NULLS_LA and WITH_LA are needed to make the grammar LALR(1).
*/
%token NOT_LA NULLS_LA WITH_LA
%left OP
/* Precedence: lowest to highest */
%nonassoc SET /* see relation_expr_opt_alias */
%left UNION EXCEPT
%left INTERSECT
%left OR
%left AND
%right NOT
%nonassoc IS ISNULL NOTNULL /* IS sets precedence for IS NULL, etc */
%nonassoc '<' '>' '=' LESS_EQUALS GREATER_EQUALS NOT_EQUALS
%nonassoc BETWEEN IN_P LIKE ILIKE SIMILAR NOT_LA
%nonassoc ESCAPE /* ESCAPE must be just above LIKE/ILIKE/SIMILAR */
%nonassoc OVERLAPS
%left POSTFIXOP /* dummy for postfix Op rules */
/*
* To support target_el without AS, we must give IDENT an explicit priority
* between POSTFIXOP and Op. We can safely assign the same priority to
* various unreserved keywords as needed to resolve ambiguities (this can't
* have any bad effects since obviously the keywords will still behave the
* same as if they weren't keywords). We need to do this for PARTITION,
* RANGE, ROWS to support opt_existing_window_name; and for RANGE, ROWS
* so that they can follow a_expr without creating postfix-operator problems;
* and for NULL so that it can follow b_expr in ColQualList without creating
* postfix-operator problems.
*
* To support CUBE and ROLLUP in GROUP BY without reserving them, we give them
* an explicit priority lower than '(', so that a rule with CUBE '(' will shift
* rather than reducing a conflicting rule that takes CUBE as a function name.
* Using the same precedence as IDENT seems right for the reasons given above.
*
* The frame_bound productions UNBOUNDED PRECEDING and UNBOUNDED FOLLOWING
* are even messier: since UNBOUNDED is an unreserved keyword (per spec!),
* there is no principled way to distinguish these from the productions
* a_expr PRECEDING/FOLLOWING. We hack this up by giving UNBOUNDED slightly
* lower precedence than PRECEDING and FOLLOWING. At present this doesn't
* appear to cause UNBOUNDED to be treated differently from other unreserved
* keywords anywhere else in the grammar, but it's definitely risky. We can
* blame any funny behavior of UNBOUNDED on the SQL standard, though.
*/
%nonassoc UNBOUNDED /* ideally should have same precedence as IDENT */
%nonassoc IDENT NULL_P PARTITION RANGE ROWS PRECEDING FOLLOWING CUBE ROLLUP
%left Op OPERATOR /* multi-character ops and user-defined operators */
%left '+' '-'
%left '*' '/' '%'
%left '^'
/* Unary Operators */
%left AT /* sets precedence for AT TIME ZONE */
%left COLLATE
%right UMINUS
%left '[' ']'
%left '(' ')'
%left TYPECAST
%left '.'
/*
* These might seem to be low-precedence, but actually they are not part
* of the arithmetic hierarchy at all in their use as JOIN operators.
* We make them high-precedence to support their use as function names.
* They wouldn't be given a precedence at all, were it not that we need
* left-associativity among the JOIN rules themselves.
*/
%left JOIN CROSS LEFT FULL RIGHT INNER_P NATURAL
/* kluge to keep xml_whitespace_option from causing shift/reduce conflicts */
%right PRESERVE STRIP_P
%%
top:
SelectStmt
{
$$ = $1
yylex.(*sqlLex).stmt = $1
}
| SelectStmt ';'
{
$$ = $1
$$.Semicolon = true
yylex.(*sqlLex).stmt = $1
}
opt_asc_desc:
ASC { $$ = "asc" }
| DESC { $$ = "desc" }
| /*EMPTY*/ { $$ = "" }
opt_nulls_order:
NULLS_LA FIRST_P { $$ = "first" }
| NULLS_LA LAST_P { $$ = "last" }
| /*EMPTY*/ { $$ = "" }
/*
* Ideally param_name should be ColId, but that causes too many conflicts.
*/
param_name: type_function_name
aliasableExpr:
a_expr
{
$$ = $1
}
| a_expr AS IDENT
{
$$ = AliasedExpr{Expr: $1, Alias: $3}
}
| a_expr IDENT
{
$$ = AliasedExpr{Expr: $1, Alias: $2}
}
any_name:
ColId
{
$$ = AnyName{$1}
}
| ColId attrs
{
$$ = AnyName{$1}
$$ = append($$, $2...)
}
attrs:
'.' attr_name
{
$$ = AnyName{$2}
}
| attrs '.' attr_name
{
$$ = append($1, $3)
}
any_operator:
all_Op
{
$$ = AnyName{$1}
}
| ColId '.' any_operator
{
$$ = append(AnyName{$1}, $3...)
}
/*****************************************************************************
*
* Type syntax
* SQL introduces a large amount of type-specific syntax.
* Define individual clauses to handle these cases, and use
* the generic case to handle regular type-extensible Postgres syntax.
* - thomas 1997-10-10
*
*****************************************************************************/
Typename:
SimpleTypename opt_array_bounds
{
$$ = $1
$$.ArrayBounds = $2
}
| SETOF SimpleTypename opt_array_bounds
{
$$ = $2
$$.Setof = true
$$.ArrayBounds = $3
}
/* SQL standard syntax, currently only one-dimensional */
| SimpleTypename ARRAY '[' Iconst ']'
{
$$ = $1
$$.ArrayWord = true
$$.ArrayBounds = []IntegerConst{$4}
}
| SETOF SimpleTypename ARRAY '[' Iconst ']'
{
$$ = $2
$$.Setof = true
$$.ArrayWord = true
$$.ArrayBounds = []IntegerConst{$5}
}
| SimpleTypename ARRAY
{
$$ = $1
$$.ArrayWord = true
}
| SETOF SimpleTypename ARRAY
{
$$ = $2
$$.Setof = true
$$.ArrayWord = true
}
opt_array_bounds:
opt_array_bounds '[' ']'
{
$$ = append($1, "")
}
| opt_array_bounds '[' Iconst ']'
{
$$ = append($1, $3)
}
| /*EMPTY*/
{ $$ = nil }
SimpleTypename:
GenericType
| Numeric
| Bit
| Character
| ConstDatetime
| ConstInterval opt_interval
{
$$ = PgType{Name: AnyName{"interval"}, OptInterval: $2}
}
| ConstInterval '(' Iconst ')'
{
$$ = PgType{Name: AnyName{"interval"}, TypeMods: []Expr{$3}}
}
/* We have a separate ConstTypename to allow defaulting fixed-length
* types such as CHAR() and BIT() to an unspecified length.
* SQL9x requires that these default to a length of one, but this
* makes no sense for constructs like CHAR 'hi' and BIT '0101',
* where there is an obvious better choice to make.
* Note that ConstInterval is not included here since it must
* be pushed up higher in the rules to accommodate the postfix
* options (e.g. INTERVAL '1' YEAR). Likewise, we have to handle
* the generic-type-name case in AExprConst to avoid premature
* reduce/reduce conflicts against function names.
*/
ConstTypename:
Numeric
| ConstBit
| ConstCharacter
| ConstDatetime
/*
* GenericType covers all type names that don't have special syntax mandated
* by the standard, including qualified names. We also allow type modifiers.
* To avoid parsing conflicts against function invocations, the modifiers
* have to be shown as expr_list here, but parse analysis will only accept
* constants for them.
*/
GenericType:
type_function_name opt_type_modifiers
{
$$ = PgType{Name: AnyName{$1}, TypeMods: $2}
}
| type_function_name attrs opt_type_modifiers
{
$$ = PgType{Name: append(AnyName{$1}, $2...), TypeMods: $3}
}
opt_type_modifiers:
'(' expr_list ')' { $$ = $2 }
| /* EMPTY */ { $$ = nil }
/*
* SQL numeric data types
*/
Numeric:
INT_P
{
$$ = PgType{Name: AnyName{"int"}}
}
| INTEGER
{
$$ = PgType{Name: AnyName{"integer"}}
}
| SMALLINT
{
$$ = PgType{Name: AnyName{"smallint"}}
}
| BIGINT
{
$$ = PgType{Name: AnyName{"bigint"}}
}
| REAL
{
$$ = PgType{Name: AnyName{"real"}}
}
| FLOAT_P opt_float
{
$$ = PgType{Name: AnyName{"float"}}
if $2 != IntegerConst("") {
$$.TypeMods = []Expr{$2}
}
}
| DOUBLE_P PRECISION
{
$$ = PgType{Name: AnyName{"double precision"}}
}
| DECIMAL_P opt_type_modifiers
{
$$ = PgType{Name: AnyName{"decimal"}, TypeMods: $2}
}
| DEC opt_type_modifiers
{
$$ = PgType{Name: AnyName{"dec"}, TypeMods: $2}
}
| NUMERIC opt_type_modifiers
{
$$ = PgType{Name: AnyName{"numeric"}, TypeMods: $2}
}
| BOOLEAN_P
{
$$ = PgType{Name: AnyName{"bool"}}
}
opt_float:
'(' Iconst ')'
{
$$ = $2
}
| /*EMPTY*/
{
$$ = IntegerConst("")
}
Bit:
BitWithLength
| BitWithoutLength
ConstBit:
BitWithLength
| BitWithoutLength
BitWithLength:
BIT opt_varying '(' expr_list ')'
{
$$ = PgType{}
if $2 {
$$.Name = AnyName{"varbit"}
} else {
$$.Name = AnyName{"bit"}
}
$$.TypeMods = $4
}
BitWithoutLength:
BIT opt_varying
{
$$ = PgType{}
if $2 {
$$ = PgType{Name: AnyName{"varbit"}}
} else {
$$ = PgType{Name: AnyName{"bit"}}
}
}
/*
* SQL character data types
* The following implements CHAR() and VARCHAR().
*/
Character:
CharacterWithLength
| CharacterWithoutLength
ConstCharacter:
CharacterWithLength
| CharacterWithoutLength
CharacterWithLength:
character '(' Iconst ')' opt_charset
{
$$ = $1
$$.TypeMods = []Expr{$3}
$$.CharSet = $5
}
CharacterWithoutLength:
character opt_charset
{
$$ = $1
$$.CharSet = $2
}
character:
CHARACTER opt_varying
{
if $2 {
$$ = PgType{Name: AnyName{"varchar"}}
} else {
$$ = PgType{Name: AnyName{"char"}}
}
}
| CHAR_P opt_varying
{
if $2 {
$$ = PgType{Name: AnyName{"varchar"}}
} else {
$$ = PgType{Name: AnyName{"char"}}
}
}
| VARCHAR
{
$$ = PgType{Name: AnyName{"varchar"}}
}
| NATIONAL CHARACTER opt_varying
{
if $3 {
$$ = PgType{Name: AnyName{"varchar"}}
} else {
$$ = PgType{Name: AnyName{"char"}}
}
}
| NATIONAL CHAR_P opt_varying
{
if $3 {
$$ = PgType{Name: AnyName{"varchar"}}
} else {
$$ = PgType{Name: AnyName{"char"}}
}
}
| NCHAR opt_varying
{
if $2 {
$$ = PgType{Name: AnyName{"varchar"}}
} else {
$$ = PgType{Name: AnyName{"char"}}
}
}
opt_varying:
VARYING
{
$$ = true
}
| /*EMPTY*/
{
$$ = false
}
opt_charset:
CHARACTER SET ColId
{
$$ = $3
}
| /*EMPTY*/
{
$$ = ""
}
/*
* SQL date/time types
*/
ConstDatetime:
TIMESTAMP '(' Iconst ')' opt_timezone
{
$$ = PgType{Name: AnyName{"timestamp"}, TypeMods: []Expr{$3}, WithTimeZone: $5}
}
| TIMESTAMP opt_timezone
{
$$ = PgType{Name: AnyName{"timestamp"}, WithTimeZone: $2}
}
| TIME '(' Iconst ')' opt_timezone
{
$$ = PgType{Name: AnyName{"time"}, TypeMods: []Expr{$3}, WithTimeZone: $5}
}
| TIME opt_timezone
{
$$ = PgType{Name: AnyName{"time"}, WithTimeZone: $2}
}
ConstInterval:
INTERVAL
opt_timezone:
WITH_LA TIME ZONE
{
$$ = true
}
| WITHOUT TIME ZONE
{
$$ = false
}
| /*EMPTY*/
{
$$ = false
}
opt_interval:
YEAR_P
{
$$ = &OptInterval{Left: "year"}
}
| MONTH_P
{
$$ = &OptInterval{Left: "month"}
}
| DAY_P
{
$$ = &OptInterval{Left: "day"}
}
| HOUR_P
{
$$ = &OptInterval{Left: "hour"}
}
| MINUTE_P
{
$$ = &OptInterval{Left: "minute"}
}
| interval_second
{
$$ = &OptInterval{Second: $1}
}
| YEAR_P TO MONTH_P
{
$$ = &OptInterval{Left: "year", Right: "month"}
}
| DAY_P TO HOUR_P
{
$$ = &OptInterval{Left: "day", Right: "hour"}
}
| DAY_P TO MINUTE_P
{
$$ = &OptInterval{Left: "day", Right: "minute"}
}
| DAY_P TO interval_second
{
$$ = &OptInterval{Left: "day", Second: $3}
}
| HOUR_P TO MINUTE_P
{
$$ = &OptInterval{Left: "hour", Right: "minute"}
}
| HOUR_P TO interval_second
{
$$ = &OptInterval{Left: "hour", Second: $3}
}
| MINUTE_P TO interval_second
{
$$ = &OptInterval{Left: "minute", Second: $3}
}
| /*EMPTY*/
{
$$ = nil
}
interval_second:
SECOND_P
{
$$ = &IntervalSecond{}
}
| SECOND_P '(' Iconst ')'
{
$$ = &IntervalSecond{Precision: $3}
}
/*****************************************************************************
*
* expression grammar
*
*****************************************************************************/
/*
* General expressions
* This is the heart of the expression syntax.
*
* We have two expression types: a_expr is the unrestricted kind, and
* b_expr is a subset that must be used in some places to avoid shift/reduce
* conflicts. For example, we can't do BETWEEN as "BETWEEN a_expr AND a_expr"
* because that use of AND conflicts with AND as a boolean operator. So,
* b_expr is used in BETWEEN and we remove boolean keywords from b_expr.
*
* Note that '(' a_expr ')' is a b_expr, so an unrestricted expression can
* always be used by surrounding it with parens.
*
* c_expr is all the productions that are common to a_expr and b_expr;
* it's factored out just to eliminate redundant coding.
*
* Be careful of productions involving more than one terminal token.
* By default, bison will assign such productions the precedence of their
* last terminal, but in nearly all cases you want it to be the precedence
* of the first terminal instead; otherwise you will not get the behavior
* you expect! So we use %prec annotations freely to set precedences.
*/
a_expr:
c_expr
| a_expr TYPECAST Typename
{
$$ = TypecastExpr{Expr: $1, Typename: $3}
}
| a_expr COLLATE any_name
{
$$ = CollateExpr{Expr: $1, Collation: $3}
}
| a_expr AT TIME ZONE a_expr %prec AT
{
$$ = AtTimeZoneExpr{Expr: $1, TimeZone: $5}
}
/*
* These operators must be called out explicitly in order to make use
* of bison's automatic operator-precedence handling. All other
* operator names are handled by the generic productions using "Op",
* below; and all those operators will have the same precedence.
*
* If you add more explicitly-known operators, be sure to add them
* also to b_expr and to the MathOp list below.
*/
| '+' a_expr %prec UMINUS
{
$$ = UnaryExpr{Operator: AnyName{"+"}, Expr: $2}
}
| '-' a_expr %prec UMINUS
{
$$ = UnaryExpr{Operator: AnyName{"-"}, Expr: $2}
}
| a_expr '+' a_expr
{
$$ = BinaryExpr{Left: $1, Operator: AnyName{"+"}, Right: $3}
}
| a_expr '-' a_expr
{
$$ = BinaryExpr{Left: $1, Operator: AnyName{"-"}, Right: $3}
}
| a_expr '*' a_expr
{
$$ = BinaryExpr{Left: $1, Operator: AnyName{"*"}, Right: $3}
}
| a_expr '/' a_expr
{
$$ = BinaryExpr{Left: $1, Operator: AnyName{"/"}, Right: $3}
}
| a_expr '%' a_expr
{
$$ = BinaryExpr{Left: $1, Operator: AnyName{"%"}, Right: $3}
}
| a_expr '^' a_expr
{
$$ = BinaryExpr{Left: $1, Operator: AnyName{"^"}, Right: $3}
}
| a_expr '<' a_expr
{
$$ = BinaryExpr{Left: $1, Operator: AnyName{"<"}, Right: $3}
}
| a_expr '>' a_expr
{
$$ = BinaryExpr{Left: $1, Operator: AnyName{">"}, Right: $3}
}
| a_expr '=' a_expr
{
$$ = BinaryExpr{Left: $1, Operator: AnyName{"="}, Right: $3}
}
| a_expr LESS_EQUALS a_expr
{
$$ = BinaryExpr{Left: $1, Operator: AnyName{"<="}, Right: $3}
}
| a_expr GREATER_EQUALS a_expr
{
$$ = BinaryExpr{Left: $1, Operator: AnyName{">="}, Right: $3}
}
| a_expr NOT_EQUALS a_expr
{
$$ = BinaryExpr{Left: $1, Operator: AnyName{"!="}, Right: $3}
}
| a_expr qual_Op a_expr %prec Op
{
$$ = BinaryExpr{Left: $1, Operator: $2, Right: $3}
}
| qual_Op a_expr %prec Op
{
$$ = UnaryExpr{Operator: $1, Expr: $2}
}